[DAGCombine] Fix getStoreMergeAndAliasCandidates's AA-enabled chain walking
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitIMINMAX(SDNode *N);
249     SDValue visitAND(SDNode *N);
250     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251     SDValue visitOR(SDNode *N);
252     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitXOR(SDNode *N);
254     SDValue SimplifyVBinOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitBSWAP(SDNode *N);
260     SDValue visitCTLZ(SDNode *N);
261     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTTZ(SDNode *N);
263     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTPOP(SDNode *N);
265     SDValue visitSELECT(SDNode *N);
266     SDValue visitVSELECT(SDNode *N);
267     SDValue visitSELECT_CC(SDNode *N);
268     SDValue visitSETCC(SDNode *N);
269     SDValue visitSIGN_EXTEND(SDNode *N);
270     SDValue visitZERO_EXTEND(SDNode *N);
271     SDValue visitANY_EXTEND(SDNode *N);
272     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274     SDValue visitTRUNCATE(SDNode *N);
275     SDValue visitBITCAST(SDNode *N);
276     SDValue visitBUILD_PAIR(SDNode *N);
277     SDValue visitFADD(SDNode *N);
278     SDValue visitFSUB(SDNode *N);
279     SDValue visitFMUL(SDNode *N);
280     SDValue visitFMA(SDNode *N);
281     SDValue visitFDIV(SDNode *N);
282     SDValue visitFREM(SDNode *N);
283     SDValue visitFSQRT(SDNode *N);
284     SDValue visitFCOPYSIGN(SDNode *N);
285     SDValue visitSINT_TO_FP(SDNode *N);
286     SDValue visitUINT_TO_FP(SDNode *N);
287     SDValue visitFP_TO_SINT(SDNode *N);
288     SDValue visitFP_TO_UINT(SDNode *N);
289     SDValue visitFP_ROUND(SDNode *N);
290     SDValue visitFP_ROUND_INREG(SDNode *N);
291     SDValue visitFP_EXTEND(SDNode *N);
292     SDValue visitFNEG(SDNode *N);
293     SDValue visitFABS(SDNode *N);
294     SDValue visitFCEIL(SDNode *N);
295     SDValue visitFTRUNC(SDNode *N);
296     SDValue visitFFLOOR(SDNode *N);
297     SDValue visitFMINNUM(SDNode *N);
298     SDValue visitFMAXNUM(SDNode *N);
299     SDValue visitBRCOND(SDNode *N);
300     SDValue visitBR_CC(SDNode *N);
301     SDValue visitLOAD(SDNode *N);
302
303     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
304     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
305
306     SDValue visitSTORE(SDNode *N);
307     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
308     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
309     SDValue visitBUILD_VECTOR(SDNode *N);
310     SDValue visitCONCAT_VECTORS(SDNode *N);
311     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
312     SDValue visitVECTOR_SHUFFLE(SDNode *N);
313     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
314     SDValue visitINSERT_SUBVECTOR(SDNode *N);
315     SDValue visitMLOAD(SDNode *N);
316     SDValue visitMSTORE(SDNode *N);
317     SDValue visitMGATHER(SDNode *N);
318     SDValue visitMSCATTER(SDNode *N);
319     SDValue visitFP_TO_FP16(SDNode *N);
320     SDValue visitFP16_TO_FP(SDNode *N);
321
322     SDValue visitFADDForFMACombine(SDNode *N);
323     SDValue visitFSUBForFMACombine(SDNode *N);
324     SDValue visitFMULForFMACombine(SDNode *N);
325
326     SDValue XformToShuffleWithZero(SDNode *N);
327     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
328
329     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
330
331     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
332     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
333     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
334     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
335                              SDValue N3, ISD::CondCode CC,
336                              bool NotExtCompare = false);
337     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
338                           SDLoc DL, bool foldBooleans = true);
339
340     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
341                            SDValue &CC) const;
342     bool isOneUseSetCC(SDValue N) const;
343
344     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
345                                          unsigned HiOp);
346     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
347     SDValue CombineExtLoad(SDNode *N);
348     SDValue combineRepeatedFPDivisors(SDNode *N);
349     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
350     SDValue BuildSDIV(SDNode *N);
351     SDValue BuildSDIVPow2(SDNode *N);
352     SDValue BuildUDIV(SDNode *N);
353     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
354     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
355     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
356                                  SDNodeFlags *Flags);
357     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
358                                  SDNodeFlags *Flags);
359     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
360                                bool DemandHighBits = true);
361     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
362     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
363                               SDValue InnerPos, SDValue InnerNeg,
364                               unsigned PosOpcode, unsigned NegOpcode,
365                               SDLoc DL);
366     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
367     SDValue ReduceLoadWidth(SDNode *N);
368     SDValue ReduceLoadOpStoreWidth(SDNode *N);
369     SDValue TransformFPLoadStorePair(SDNode *N);
370     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
371     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
372
373     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
374
375     /// Walk up chain skipping non-aliasing memory nodes,
376     /// looking for aliasing nodes and adding them to the Aliases vector.
377     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
378                           SmallVectorImpl<SDValue> &Aliases);
379
380     /// Return true if there is any possibility that the two addresses overlap.
381     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
382
383     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
384     /// chain (aliasing node.)
385     SDValue FindBetterChain(SDNode *N, SDValue Chain);
386
387     /// Do FindBetterChain for a store and any possibly adjacent stores on
388     /// consecutive chains.
389     bool findBetterNeighborChains(StoreSDNode *St);
390
391     /// Holds a pointer to an LSBaseSDNode as well as information on where it
392     /// is located in a sequence of memory operations connected by a chain.
393     struct MemOpLink {
394       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
395       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
396       // Ptr to the mem node.
397       LSBaseSDNode *MemNode;
398       // Offset from the base ptr.
399       int64_t OffsetFromBase;
400       // What is the sequence number of this mem node.
401       // Lowest mem operand in the DAG starts at zero.
402       unsigned SequenceNum;
403     };
404
405     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
406     /// constant build_vector of the stored constant values in Stores.
407     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
408                                          SDLoc SL,
409                                          ArrayRef<MemOpLink> Stores,
410                                          SmallVectorImpl<SDValue> &Chains,
411                                          EVT Ty) const;
412
413     /// This is a helper function for MergeConsecutiveStores. When the source
414     /// elements of the consecutive stores are all constants or all extracted
415     /// vector elements, try to merge them into one larger store.
416     /// \return True if a merged store was created.
417     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
418                                          EVT MemVT, unsigned NumStores,
419                                          bool IsConstantSrc, bool UseVector);
420
421     /// This is a helper function for MergeConsecutiveStores.
422     /// Stores that may be merged are placed in StoreNodes.
423     /// Loads that may alias with those stores are placed in AliasLoadNodes.
424     void getStoreMergeAndAliasCandidates(
425         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
426         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
427
428     /// Merge consecutive store operations into a wide store.
429     /// This optimization uses wide integers or vectors when possible.
430     /// \return True if some memory operations were changed.
431     bool MergeConsecutiveStores(StoreSDNode *N);
432
433     /// \brief Try to transform a truncation where C is a constant:
434     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
435     ///
436     /// \p N needs to be a truncation and its first operand an AND. Other
437     /// requirements are checked by the function (e.g. that trunc is
438     /// single-use) and if missed an empty SDValue is returned.
439     SDValue distributeTruncateThroughAnd(SDNode *N);
440
441   public:
442     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
443         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
444           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
445       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
446     }
447
448     /// Runs the dag combiner on all nodes in the work list
449     void Run(CombineLevel AtLevel);
450
451     SelectionDAG &getDAG() const { return DAG; }
452
453     /// Returns a type large enough to hold any valid shift amount - before type
454     /// legalization these can be huge.
455     EVT getShiftAmountTy(EVT LHSTy) {
456       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
457       if (LHSTy.isVector())
458         return LHSTy;
459       auto &DL = DAG.getDataLayout();
460       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
461                         : TLI.getPointerTy(DL);
462     }
463
464     /// This method returns true if we are running before type legalization or
465     /// if the specified VT is legal.
466     bool isTypeLegal(const EVT &VT) {
467       if (!LegalTypes) return true;
468       return TLI.isTypeLegal(VT);
469     }
470
471     /// Convenience wrapper around TargetLowering::getSetCCResultType
472     EVT getSetCCResultType(EVT VT) const {
473       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
474     }
475   };
476 }
477
478
479 namespace {
480 /// This class is a DAGUpdateListener that removes any deleted
481 /// nodes from the worklist.
482 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
483   DAGCombiner &DC;
484 public:
485   explicit WorklistRemover(DAGCombiner &dc)
486     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
487
488   void NodeDeleted(SDNode *N, SDNode *E) override {
489     DC.removeFromWorklist(N);
490   }
491 };
492 }
493
494 //===----------------------------------------------------------------------===//
495 //  TargetLowering::DAGCombinerInfo implementation
496 //===----------------------------------------------------------------------===//
497
498 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
499   ((DAGCombiner*)DC)->AddToWorklist(N);
500 }
501
502 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
503   ((DAGCombiner*)DC)->removeFromWorklist(N);
504 }
505
506 SDValue TargetLowering::DAGCombinerInfo::
507 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
508   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
509 }
510
511 SDValue TargetLowering::DAGCombinerInfo::
512 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
513   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
514 }
515
516
517 SDValue TargetLowering::DAGCombinerInfo::
518 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
519   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
520 }
521
522 void TargetLowering::DAGCombinerInfo::
523 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
524   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
525 }
526
527 //===----------------------------------------------------------------------===//
528 // Helper Functions
529 //===----------------------------------------------------------------------===//
530
531 void DAGCombiner::deleteAndRecombine(SDNode *N) {
532   removeFromWorklist(N);
533
534   // If the operands of this node are only used by the node, they will now be
535   // dead. Make sure to re-visit them and recursively delete dead nodes.
536   for (const SDValue &Op : N->ops())
537     // For an operand generating multiple values, one of the values may
538     // become dead allowing further simplification (e.g. split index
539     // arithmetic from an indexed load).
540     if (Op->hasOneUse() || Op->getNumValues() > 1)
541       AddToWorklist(Op.getNode());
542
543   DAG.DeleteNode(N);
544 }
545
546 /// Return 1 if we can compute the negated form of the specified expression for
547 /// the same cost as the expression itself, or 2 if we can compute the negated
548 /// form more cheaply than the expression itself.
549 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
550                                const TargetLowering &TLI,
551                                const TargetOptions *Options,
552                                unsigned Depth = 0) {
553   // fneg is removable even if it has multiple uses.
554   if (Op.getOpcode() == ISD::FNEG) return 2;
555
556   // Don't allow anything with multiple uses.
557   if (!Op.hasOneUse()) return 0;
558
559   // Don't recurse exponentially.
560   if (Depth > 6) return 0;
561
562   switch (Op.getOpcode()) {
563   default: return false;
564   case ISD::ConstantFP:
565     // Don't invert constant FP values after legalize.  The negated constant
566     // isn't necessarily legal.
567     return LegalOperations ? 0 : 1;
568   case ISD::FADD:
569     // FIXME: determine better conditions for this xform.
570     if (!Options->UnsafeFPMath) return 0;
571
572     // After operation legalization, it might not be legal to create new FSUBs.
573     if (LegalOperations &&
574         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
575       return 0;
576
577     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
578     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
579                                     Options, Depth + 1))
580       return V;
581     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
582     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
583                               Depth + 1);
584   case ISD::FSUB:
585     // We can't turn -(A-B) into B-A when we honor signed zeros.
586     if (!Options->UnsafeFPMath) return 0;
587
588     // fold (fneg (fsub A, B)) -> (fsub B, A)
589     return 1;
590
591   case ISD::FMUL:
592   case ISD::FDIV:
593     if (Options->HonorSignDependentRoundingFPMath()) return 0;
594
595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
596     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
597                                     Options, Depth + 1))
598       return V;
599
600     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
601                               Depth + 1);
602
603   case ISD::FP_EXTEND:
604   case ISD::FP_ROUND:
605   case ISD::FSIN:
606     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
607                               Depth + 1);
608   }
609 }
610
611 /// If isNegatibleForFree returns true, return the newly negated expression.
612 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
613                                     bool LegalOperations, unsigned Depth = 0) {
614   const TargetOptions &Options = DAG.getTarget().Options;
615   // fneg is removable even if it has multiple uses.
616   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
617
618   // Don't allow anything with multiple uses.
619   assert(Op.hasOneUse() && "Unknown reuse!");
620
621   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
622
623   const SDNodeFlags *Flags = Op.getNode()->getFlags();
624
625   switch (Op.getOpcode()) {
626   default: llvm_unreachable("Unknown code");
627   case ISD::ConstantFP: {
628     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
629     V.changeSign();
630     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
631   }
632   case ISD::FADD:
633     // FIXME: determine better conditions for this xform.
634     assert(Options.UnsafeFPMath);
635
636     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
637     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
638                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
639       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
640                          GetNegatedExpression(Op.getOperand(0), DAG,
641                                               LegalOperations, Depth+1),
642                          Op.getOperand(1), Flags);
643     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
644     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
645                        GetNegatedExpression(Op.getOperand(1), DAG,
646                                             LegalOperations, Depth+1),
647                        Op.getOperand(0), Flags);
648   case ISD::FSUB:
649     // We can't turn -(A-B) into B-A when we honor signed zeros.
650     assert(Options.UnsafeFPMath);
651
652     // fold (fneg (fsub 0, B)) -> B
653     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
654       if (N0CFP->isZero())
655         return Op.getOperand(1);
656
657     // fold (fneg (fsub A, B)) -> (fsub B, A)
658     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
659                        Op.getOperand(1), Op.getOperand(0), Flags);
660
661   case ISD::FMUL:
662   case ISD::FDIV:
663     assert(!Options.HonorSignDependentRoundingFPMath());
664
665     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
666     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
667                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
668       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
669                          GetNegatedExpression(Op.getOperand(0), DAG,
670                                               LegalOperations, Depth+1),
671                          Op.getOperand(1), Flags);
672
673     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
674     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
675                        Op.getOperand(0),
676                        GetNegatedExpression(Op.getOperand(1), DAG,
677                                             LegalOperations, Depth+1), Flags);
678
679   case ISD::FP_EXTEND:
680   case ISD::FSIN:
681     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
682                        GetNegatedExpression(Op.getOperand(0), DAG,
683                                             LegalOperations, Depth+1));
684   case ISD::FP_ROUND:
685       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
686                          GetNegatedExpression(Op.getOperand(0), DAG,
687                                               LegalOperations, Depth+1),
688                          Op.getOperand(1));
689   }
690 }
691
692 // Return true if this node is a setcc, or is a select_cc
693 // that selects between the target values used for true and false, making it
694 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
695 // the appropriate nodes based on the type of node we are checking. This
696 // simplifies life a bit for the callers.
697 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
698                                     SDValue &CC) const {
699   if (N.getOpcode() == ISD::SETCC) {
700     LHS = N.getOperand(0);
701     RHS = N.getOperand(1);
702     CC  = N.getOperand(2);
703     return true;
704   }
705
706   if (N.getOpcode() != ISD::SELECT_CC ||
707       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
708       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
709     return false;
710
711   if (TLI.getBooleanContents(N.getValueType()) ==
712       TargetLowering::UndefinedBooleanContent)
713     return false;
714
715   LHS = N.getOperand(0);
716   RHS = N.getOperand(1);
717   CC  = N.getOperand(4);
718   return true;
719 }
720
721 /// Return true if this is a SetCC-equivalent operation with only one use.
722 /// If this is true, it allows the users to invert the operation for free when
723 /// it is profitable to do so.
724 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
725   SDValue N0, N1, N2;
726   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
727     return true;
728   return false;
729 }
730
731 /// Returns true if N is a BUILD_VECTOR node whose
732 /// elements are all the same constant or undefined.
733 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
734   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
735   if (!C)
736     return false;
737
738   APInt SplatUndef;
739   unsigned SplatBitSize;
740   bool HasAnyUndefs;
741   EVT EltVT = N->getValueType(0).getVectorElementType();
742   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
743                              HasAnyUndefs) &&
744           EltVT.getSizeInBits() >= SplatBitSize);
745 }
746
747 // \brief Returns the SDNode if it is a constant integer BuildVector
748 // or constant integer.
749 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
750   if (isa<ConstantSDNode>(N))
751     return N.getNode();
752   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
753     return N.getNode();
754   return nullptr;
755 }
756
757 // \brief Returns the SDNode if it is a constant float BuildVector
758 // or constant float.
759 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
760   if (isa<ConstantFPSDNode>(N))
761     return N.getNode();
762   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
763     return N.getNode();
764   return nullptr;
765 }
766
767 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
768 // int.
769 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
770   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
771     return CN;
772
773   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
774     BitVector UndefElements;
775     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
776
777     // BuildVectors can truncate their operands. Ignore that case here.
778     // FIXME: We blindly ignore splats which include undef which is overly
779     // pessimistic.
780     if (CN && UndefElements.none() &&
781         CN->getValueType(0) == N.getValueType().getScalarType())
782       return CN;
783   }
784
785   return nullptr;
786 }
787
788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
789 // float.
790 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
791   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
792     return CN;
793
794   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
795     BitVector UndefElements;
796     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
797
798     if (CN && UndefElements.none())
799       return CN;
800   }
801
802   return nullptr;
803 }
804
805 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
806                                     SDValue N0, SDValue N1) {
807   EVT VT = N0.getValueType();
808   if (N0.getOpcode() == Opc) {
809     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
810       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
811         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
812         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
813           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
814         return SDValue();
815       }
816       if (N0.hasOneUse()) {
817         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
818         // use
819         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
820         if (!OpNode.getNode())
821           return SDValue();
822         AddToWorklist(OpNode.getNode());
823         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
824       }
825     }
826   }
827
828   if (N1.getOpcode() == Opc) {
829     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
830       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
831         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
832         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
833           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
834         return SDValue();
835       }
836       if (N1.hasOneUse()) {
837         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
838         // use
839         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
840         if (!OpNode.getNode())
841           return SDValue();
842         AddToWorklist(OpNode.getNode());
843         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
844       }
845     }
846   }
847
848   return SDValue();
849 }
850
851 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
852                                bool AddTo) {
853   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
854   ++NodesCombined;
855   DEBUG(dbgs() << "\nReplacing.1 ";
856         N->dump(&DAG);
857         dbgs() << "\nWith: ";
858         To[0].getNode()->dump(&DAG);
859         dbgs() << " and " << NumTo-1 << " other values\n");
860   for (unsigned i = 0, e = NumTo; i != e; ++i)
861     assert((!To[i].getNode() ||
862             N->getValueType(i) == To[i].getValueType()) &&
863            "Cannot combine value to value of different type!");
864
865   WorklistRemover DeadNodes(*this);
866   DAG.ReplaceAllUsesWith(N, To);
867   if (AddTo) {
868     // Push the new nodes and any users onto the worklist
869     for (unsigned i = 0, e = NumTo; i != e; ++i) {
870       if (To[i].getNode()) {
871         AddToWorklist(To[i].getNode());
872         AddUsersToWorklist(To[i].getNode());
873       }
874     }
875   }
876
877   // Finally, if the node is now dead, remove it from the graph.  The node
878   // may not be dead if the replacement process recursively simplified to
879   // something else needing this node.
880   if (N->use_empty())
881     deleteAndRecombine(N);
882   return SDValue(N, 0);
883 }
884
885 void DAGCombiner::
886 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
887   // Replace all uses.  If any nodes become isomorphic to other nodes and
888   // are deleted, make sure to remove them from our worklist.
889   WorklistRemover DeadNodes(*this);
890   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
891
892   // Push the new node and any (possibly new) users onto the worklist.
893   AddToWorklist(TLO.New.getNode());
894   AddUsersToWorklist(TLO.New.getNode());
895
896   // Finally, if the node is now dead, remove it from the graph.  The node
897   // may not be dead if the replacement process recursively simplified to
898   // something else needing this node.
899   if (TLO.Old.getNode()->use_empty())
900     deleteAndRecombine(TLO.Old.getNode());
901 }
902
903 /// Check the specified integer node value to see if it can be simplified or if
904 /// things it uses can be simplified by bit propagation. If so, return true.
905 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
906   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
907   APInt KnownZero, KnownOne;
908   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
909     return false;
910
911   // Revisit the node.
912   AddToWorklist(Op.getNode());
913
914   // Replace the old value with the new one.
915   ++NodesCombined;
916   DEBUG(dbgs() << "\nReplacing.2 ";
917         TLO.Old.getNode()->dump(&DAG);
918         dbgs() << "\nWith: ";
919         TLO.New.getNode()->dump(&DAG);
920         dbgs() << '\n');
921
922   CommitTargetLoweringOpt(TLO);
923   return true;
924 }
925
926 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
927   SDLoc dl(Load);
928   EVT VT = Load->getValueType(0);
929   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
930
931   DEBUG(dbgs() << "\nReplacing.9 ";
932         Load->dump(&DAG);
933         dbgs() << "\nWith: ";
934         Trunc.getNode()->dump(&DAG);
935         dbgs() << '\n');
936   WorklistRemover DeadNodes(*this);
937   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
938   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
939   deleteAndRecombine(Load);
940   AddToWorklist(Trunc.getNode());
941 }
942
943 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
944   Replace = false;
945   SDLoc dl(Op);
946   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
947     EVT MemVT = LD->getMemoryVT();
948     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
949       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
950                                                        : ISD::EXTLOAD)
951       : LD->getExtensionType();
952     Replace = true;
953     return DAG.getExtLoad(ExtType, dl, PVT,
954                           LD->getChain(), LD->getBasePtr(),
955                           MemVT, LD->getMemOperand());
956   }
957
958   unsigned Opc = Op.getOpcode();
959   switch (Opc) {
960   default: break;
961   case ISD::AssertSext:
962     return DAG.getNode(ISD::AssertSext, dl, PVT,
963                        SExtPromoteOperand(Op.getOperand(0), PVT),
964                        Op.getOperand(1));
965   case ISD::AssertZext:
966     return DAG.getNode(ISD::AssertZext, dl, PVT,
967                        ZExtPromoteOperand(Op.getOperand(0), PVT),
968                        Op.getOperand(1));
969   case ISD::Constant: {
970     unsigned ExtOpc =
971       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
972     return DAG.getNode(ExtOpc, dl, PVT, Op);
973   }
974   }
975
976   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
977     return SDValue();
978   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
979 }
980
981 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
982   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
983     return SDValue();
984   EVT OldVT = Op.getValueType();
985   SDLoc dl(Op);
986   bool Replace = false;
987   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
988   if (!NewOp.getNode())
989     return SDValue();
990   AddToWorklist(NewOp.getNode());
991
992   if (Replace)
993     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
994   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
995                      DAG.getValueType(OldVT));
996 }
997
998 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
999   EVT OldVT = Op.getValueType();
1000   SDLoc dl(Op);
1001   bool Replace = false;
1002   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1003   if (!NewOp.getNode())
1004     return SDValue();
1005   AddToWorklist(NewOp.getNode());
1006
1007   if (Replace)
1008     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1009   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1010 }
1011
1012 /// Promote the specified integer binary operation if the target indicates it is
1013 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1014 /// i32 since i16 instructions are longer.
1015 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1016   if (!LegalOperations)
1017     return SDValue();
1018
1019   EVT VT = Op.getValueType();
1020   if (VT.isVector() || !VT.isInteger())
1021     return SDValue();
1022
1023   // If operation type is 'undesirable', e.g. i16 on x86, consider
1024   // promoting it.
1025   unsigned Opc = Op.getOpcode();
1026   if (TLI.isTypeDesirableForOp(Opc, VT))
1027     return SDValue();
1028
1029   EVT PVT = VT;
1030   // Consult target whether it is a good idea to promote this operation and
1031   // what's the right type to promote it to.
1032   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1033     assert(PVT != VT && "Don't know what type to promote to!");
1034
1035     bool Replace0 = false;
1036     SDValue N0 = Op.getOperand(0);
1037     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1038     if (!NN0.getNode())
1039       return SDValue();
1040
1041     bool Replace1 = false;
1042     SDValue N1 = Op.getOperand(1);
1043     SDValue NN1;
1044     if (N0 == N1)
1045       NN1 = NN0;
1046     else {
1047       NN1 = PromoteOperand(N1, PVT, Replace1);
1048       if (!NN1.getNode())
1049         return SDValue();
1050     }
1051
1052     AddToWorklist(NN0.getNode());
1053     if (NN1.getNode())
1054       AddToWorklist(NN1.getNode());
1055
1056     if (Replace0)
1057       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1058     if (Replace1)
1059       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1060
1061     DEBUG(dbgs() << "\nPromoting ";
1062           Op.getNode()->dump(&DAG));
1063     SDLoc dl(Op);
1064     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1065                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1066   }
1067   return SDValue();
1068 }
1069
1070 /// Promote the specified integer shift operation if the target indicates it is
1071 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1072 /// i32 since i16 instructions are longer.
1073 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1074   if (!LegalOperations)
1075     return SDValue();
1076
1077   EVT VT = Op.getValueType();
1078   if (VT.isVector() || !VT.isInteger())
1079     return SDValue();
1080
1081   // If operation type is 'undesirable', e.g. i16 on x86, consider
1082   // promoting it.
1083   unsigned Opc = Op.getOpcode();
1084   if (TLI.isTypeDesirableForOp(Opc, VT))
1085     return SDValue();
1086
1087   EVT PVT = VT;
1088   // Consult target whether it is a good idea to promote this operation and
1089   // what's the right type to promote it to.
1090   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1091     assert(PVT != VT && "Don't know what type to promote to!");
1092
1093     bool Replace = false;
1094     SDValue N0 = Op.getOperand(0);
1095     if (Opc == ISD::SRA)
1096       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1097     else if (Opc == ISD::SRL)
1098       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1099     else
1100       N0 = PromoteOperand(N0, PVT, Replace);
1101     if (!N0.getNode())
1102       return SDValue();
1103
1104     AddToWorklist(N0.getNode());
1105     if (Replace)
1106       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1107
1108     DEBUG(dbgs() << "\nPromoting ";
1109           Op.getNode()->dump(&DAG));
1110     SDLoc dl(Op);
1111     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1112                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1113   }
1114   return SDValue();
1115 }
1116
1117 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1118   if (!LegalOperations)
1119     return SDValue();
1120
1121   EVT VT = Op.getValueType();
1122   if (VT.isVector() || !VT.isInteger())
1123     return SDValue();
1124
1125   // If operation type is 'undesirable', e.g. i16 on x86, consider
1126   // promoting it.
1127   unsigned Opc = Op.getOpcode();
1128   if (TLI.isTypeDesirableForOp(Opc, VT))
1129     return SDValue();
1130
1131   EVT PVT = VT;
1132   // Consult target whether it is a good idea to promote this operation and
1133   // what's the right type to promote it to.
1134   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1135     assert(PVT != VT && "Don't know what type to promote to!");
1136     // fold (aext (aext x)) -> (aext x)
1137     // fold (aext (zext x)) -> (zext x)
1138     // fold (aext (sext x)) -> (sext x)
1139     DEBUG(dbgs() << "\nPromoting ";
1140           Op.getNode()->dump(&DAG));
1141     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1142   }
1143   return SDValue();
1144 }
1145
1146 bool DAGCombiner::PromoteLoad(SDValue Op) {
1147   if (!LegalOperations)
1148     return false;
1149
1150   EVT VT = Op.getValueType();
1151   if (VT.isVector() || !VT.isInteger())
1152     return false;
1153
1154   // If operation type is 'undesirable', e.g. i16 on x86, consider
1155   // promoting it.
1156   unsigned Opc = Op.getOpcode();
1157   if (TLI.isTypeDesirableForOp(Opc, VT))
1158     return false;
1159
1160   EVT PVT = VT;
1161   // Consult target whether it is a good idea to promote this operation and
1162   // what's the right type to promote it to.
1163   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1164     assert(PVT != VT && "Don't know what type to promote to!");
1165
1166     SDLoc dl(Op);
1167     SDNode *N = Op.getNode();
1168     LoadSDNode *LD = cast<LoadSDNode>(N);
1169     EVT MemVT = LD->getMemoryVT();
1170     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1171       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1172                                                        : ISD::EXTLOAD)
1173       : LD->getExtensionType();
1174     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1175                                    LD->getChain(), LD->getBasePtr(),
1176                                    MemVT, LD->getMemOperand());
1177     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1178
1179     DEBUG(dbgs() << "\nPromoting ";
1180           N->dump(&DAG);
1181           dbgs() << "\nTo: ";
1182           Result.getNode()->dump(&DAG);
1183           dbgs() << '\n');
1184     WorklistRemover DeadNodes(*this);
1185     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1186     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1187     deleteAndRecombine(N);
1188     AddToWorklist(Result.getNode());
1189     return true;
1190   }
1191   return false;
1192 }
1193
1194 /// \brief Recursively delete a node which has no uses and any operands for
1195 /// which it is the only use.
1196 ///
1197 /// Note that this both deletes the nodes and removes them from the worklist.
1198 /// It also adds any nodes who have had a user deleted to the worklist as they
1199 /// may now have only one use and subject to other combines.
1200 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1201   if (!N->use_empty())
1202     return false;
1203
1204   SmallSetVector<SDNode *, 16> Nodes;
1205   Nodes.insert(N);
1206   do {
1207     N = Nodes.pop_back_val();
1208     if (!N)
1209       continue;
1210
1211     if (N->use_empty()) {
1212       for (const SDValue &ChildN : N->op_values())
1213         Nodes.insert(ChildN.getNode());
1214
1215       removeFromWorklist(N);
1216       DAG.DeleteNode(N);
1217     } else {
1218       AddToWorklist(N);
1219     }
1220   } while (!Nodes.empty());
1221   return true;
1222 }
1223
1224 //===----------------------------------------------------------------------===//
1225 //  Main DAG Combiner implementation
1226 //===----------------------------------------------------------------------===//
1227
1228 void DAGCombiner::Run(CombineLevel AtLevel) {
1229   // set the instance variables, so that the various visit routines may use it.
1230   Level = AtLevel;
1231   LegalOperations = Level >= AfterLegalizeVectorOps;
1232   LegalTypes = Level >= AfterLegalizeTypes;
1233
1234   // Add all the dag nodes to the worklist.
1235   for (SDNode &Node : DAG.allnodes())
1236     AddToWorklist(&Node);
1237
1238   // Create a dummy node (which is not added to allnodes), that adds a reference
1239   // to the root node, preventing it from being deleted, and tracking any
1240   // changes of the root.
1241   HandleSDNode Dummy(DAG.getRoot());
1242
1243   // while the worklist isn't empty, find a node and
1244   // try and combine it.
1245   while (!WorklistMap.empty()) {
1246     SDNode *N;
1247     // The Worklist holds the SDNodes in order, but it may contain null entries.
1248     do {
1249       N = Worklist.pop_back_val();
1250     } while (!N);
1251
1252     bool GoodWorklistEntry = WorklistMap.erase(N);
1253     (void)GoodWorklistEntry;
1254     assert(GoodWorklistEntry &&
1255            "Found a worklist entry without a corresponding map entry!");
1256
1257     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1258     // N is deleted from the DAG, since they too may now be dead or may have a
1259     // reduced number of uses, allowing other xforms.
1260     if (recursivelyDeleteUnusedNodes(N))
1261       continue;
1262
1263     WorklistRemover DeadNodes(*this);
1264
1265     // If this combine is running after legalizing the DAG, re-legalize any
1266     // nodes pulled off the worklist.
1267     if (Level == AfterLegalizeDAG) {
1268       SmallSetVector<SDNode *, 16> UpdatedNodes;
1269       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1270
1271       for (SDNode *LN : UpdatedNodes) {
1272         AddToWorklist(LN);
1273         AddUsersToWorklist(LN);
1274       }
1275       if (!NIsValid)
1276         continue;
1277     }
1278
1279     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1280
1281     // Add any operands of the new node which have not yet been combined to the
1282     // worklist as well. Because the worklist uniques things already, this
1283     // won't repeatedly process the same operand.
1284     CombinedNodes.insert(N);
1285     for (const SDValue &ChildN : N->op_values())
1286       if (!CombinedNodes.count(ChildN.getNode()))
1287         AddToWorklist(ChildN.getNode());
1288
1289     SDValue RV = combine(N);
1290
1291     if (!RV.getNode())
1292       continue;
1293
1294     ++NodesCombined;
1295
1296     // If we get back the same node we passed in, rather than a new node or
1297     // zero, we know that the node must have defined multiple values and
1298     // CombineTo was used.  Since CombineTo takes care of the worklist
1299     // mechanics for us, we have no work to do in this case.
1300     if (RV.getNode() == N)
1301       continue;
1302
1303     assert(N->getOpcode() != ISD::DELETED_NODE &&
1304            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1305            "Node was deleted but visit returned new node!");
1306
1307     DEBUG(dbgs() << " ... into: ";
1308           RV.getNode()->dump(&DAG));
1309
1310     // Transfer debug value.
1311     DAG.TransferDbgValues(SDValue(N, 0), RV);
1312     if (N->getNumValues() == RV.getNode()->getNumValues())
1313       DAG.ReplaceAllUsesWith(N, RV.getNode());
1314     else {
1315       assert(N->getValueType(0) == RV.getValueType() &&
1316              N->getNumValues() == 1 && "Type mismatch");
1317       SDValue OpV = RV;
1318       DAG.ReplaceAllUsesWith(N, &OpV);
1319     }
1320
1321     // Push the new node and any users onto the worklist
1322     AddToWorklist(RV.getNode());
1323     AddUsersToWorklist(RV.getNode());
1324
1325     // Finally, if the node is now dead, remove it from the graph.  The node
1326     // may not be dead if the replacement process recursively simplified to
1327     // something else needing this node. This will also take care of adding any
1328     // operands which have lost a user to the worklist.
1329     recursivelyDeleteUnusedNodes(N);
1330   }
1331
1332   // If the root changed (e.g. it was a dead load, update the root).
1333   DAG.setRoot(Dummy.getValue());
1334   DAG.RemoveDeadNodes();
1335 }
1336
1337 SDValue DAGCombiner::visit(SDNode *N) {
1338   switch (N->getOpcode()) {
1339   default: break;
1340   case ISD::TokenFactor:        return visitTokenFactor(N);
1341   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1342   case ISD::ADD:                return visitADD(N);
1343   case ISD::SUB:                return visitSUB(N);
1344   case ISD::ADDC:               return visitADDC(N);
1345   case ISD::SUBC:               return visitSUBC(N);
1346   case ISD::ADDE:               return visitADDE(N);
1347   case ISD::SUBE:               return visitSUBE(N);
1348   case ISD::MUL:                return visitMUL(N);
1349   case ISD::SDIV:               return visitSDIV(N);
1350   case ISD::UDIV:               return visitUDIV(N);
1351   case ISD::SREM:               return visitSREM(N);
1352   case ISD::UREM:               return visitUREM(N);
1353   case ISD::MULHU:              return visitMULHU(N);
1354   case ISD::MULHS:              return visitMULHS(N);
1355   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1356   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1357   case ISD::SMULO:              return visitSMULO(N);
1358   case ISD::UMULO:              return visitUMULO(N);
1359   case ISD::SDIVREM:            return visitSDIVREM(N);
1360   case ISD::UDIVREM:            return visitUDIVREM(N);
1361   case ISD::SMIN:
1362   case ISD::SMAX:
1363   case ISD::UMIN:
1364   case ISD::UMAX:               return visitIMINMAX(N);
1365   case ISD::AND:                return visitAND(N);
1366   case ISD::OR:                 return visitOR(N);
1367   case ISD::XOR:                return visitXOR(N);
1368   case ISD::SHL:                return visitSHL(N);
1369   case ISD::SRA:                return visitSRA(N);
1370   case ISD::SRL:                return visitSRL(N);
1371   case ISD::ROTR:
1372   case ISD::ROTL:               return visitRotate(N);
1373   case ISD::BSWAP:              return visitBSWAP(N);
1374   case ISD::CTLZ:               return visitCTLZ(N);
1375   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1376   case ISD::CTTZ:               return visitCTTZ(N);
1377   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1378   case ISD::CTPOP:              return visitCTPOP(N);
1379   case ISD::SELECT:             return visitSELECT(N);
1380   case ISD::VSELECT:            return visitVSELECT(N);
1381   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1382   case ISD::SETCC:              return visitSETCC(N);
1383   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1384   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1385   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1386   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1387   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1388   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1389   case ISD::BITCAST:            return visitBITCAST(N);
1390   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1391   case ISD::FADD:               return visitFADD(N);
1392   case ISD::FSUB:               return visitFSUB(N);
1393   case ISD::FMUL:               return visitFMUL(N);
1394   case ISD::FMA:                return visitFMA(N);
1395   case ISD::FDIV:               return visitFDIV(N);
1396   case ISD::FREM:               return visitFREM(N);
1397   case ISD::FSQRT:              return visitFSQRT(N);
1398   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1399   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1400   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1401   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1402   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1403   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1404   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1405   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1406   case ISD::FNEG:               return visitFNEG(N);
1407   case ISD::FABS:               return visitFABS(N);
1408   case ISD::FFLOOR:             return visitFFLOOR(N);
1409   case ISD::FMINNUM:            return visitFMINNUM(N);
1410   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1411   case ISD::FCEIL:              return visitFCEIL(N);
1412   case ISD::FTRUNC:             return visitFTRUNC(N);
1413   case ISD::BRCOND:             return visitBRCOND(N);
1414   case ISD::BR_CC:              return visitBR_CC(N);
1415   case ISD::LOAD:               return visitLOAD(N);
1416   case ISD::STORE:              return visitSTORE(N);
1417   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1418   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1419   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1420   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1421   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1422   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1423   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1424   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1425   case ISD::MGATHER:            return visitMGATHER(N);
1426   case ISD::MLOAD:              return visitMLOAD(N);
1427   case ISD::MSCATTER:           return visitMSCATTER(N);
1428   case ISD::MSTORE:             return visitMSTORE(N);
1429   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1430   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1431   }
1432   return SDValue();
1433 }
1434
1435 SDValue DAGCombiner::combine(SDNode *N) {
1436   SDValue RV = visit(N);
1437
1438   // If nothing happened, try a target-specific DAG combine.
1439   if (!RV.getNode()) {
1440     assert(N->getOpcode() != ISD::DELETED_NODE &&
1441            "Node was deleted but visit returned NULL!");
1442
1443     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1444         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1445
1446       // Expose the DAG combiner to the target combiner impls.
1447       TargetLowering::DAGCombinerInfo
1448         DagCombineInfo(DAG, Level, false, this);
1449
1450       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1451     }
1452   }
1453
1454   // If nothing happened still, try promoting the operation.
1455   if (!RV.getNode()) {
1456     switch (N->getOpcode()) {
1457     default: break;
1458     case ISD::ADD:
1459     case ISD::SUB:
1460     case ISD::MUL:
1461     case ISD::AND:
1462     case ISD::OR:
1463     case ISD::XOR:
1464       RV = PromoteIntBinOp(SDValue(N, 0));
1465       break;
1466     case ISD::SHL:
1467     case ISD::SRA:
1468     case ISD::SRL:
1469       RV = PromoteIntShiftOp(SDValue(N, 0));
1470       break;
1471     case ISD::SIGN_EXTEND:
1472     case ISD::ZERO_EXTEND:
1473     case ISD::ANY_EXTEND:
1474       RV = PromoteExtend(SDValue(N, 0));
1475       break;
1476     case ISD::LOAD:
1477       if (PromoteLoad(SDValue(N, 0)))
1478         RV = SDValue(N, 0);
1479       break;
1480     }
1481   }
1482
1483   // If N is a commutative binary node, try commuting it to enable more
1484   // sdisel CSE.
1485   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1486       N->getNumValues() == 1) {
1487     SDValue N0 = N->getOperand(0);
1488     SDValue N1 = N->getOperand(1);
1489
1490     // Constant operands are canonicalized to RHS.
1491     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1492       SDValue Ops[] = {N1, N0};
1493       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1494                                             N->getFlags());
1495       if (CSENode)
1496         return SDValue(CSENode, 0);
1497     }
1498   }
1499
1500   return RV;
1501 }
1502
1503 /// Given a node, return its input chain if it has one, otherwise return a null
1504 /// sd operand.
1505 static SDValue getInputChainForNode(SDNode *N) {
1506   if (unsigned NumOps = N->getNumOperands()) {
1507     if (N->getOperand(0).getValueType() == MVT::Other)
1508       return N->getOperand(0);
1509     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1510       return N->getOperand(NumOps-1);
1511     for (unsigned i = 1; i < NumOps-1; ++i)
1512       if (N->getOperand(i).getValueType() == MVT::Other)
1513         return N->getOperand(i);
1514   }
1515   return SDValue();
1516 }
1517
1518 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1519   // If N has two operands, where one has an input chain equal to the other,
1520   // the 'other' chain is redundant.
1521   if (N->getNumOperands() == 2) {
1522     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1523       return N->getOperand(0);
1524     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1525       return N->getOperand(1);
1526   }
1527
1528   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1529   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1530   SmallPtrSet<SDNode*, 16> SeenOps;
1531   bool Changed = false;             // If we should replace this token factor.
1532
1533   // Start out with this token factor.
1534   TFs.push_back(N);
1535
1536   // Iterate through token factors.  The TFs grows when new token factors are
1537   // encountered.
1538   for (unsigned i = 0; i < TFs.size(); ++i) {
1539     SDNode *TF = TFs[i];
1540
1541     // Check each of the operands.
1542     for (const SDValue &Op : TF->op_values()) {
1543
1544       switch (Op.getOpcode()) {
1545       case ISD::EntryToken:
1546         // Entry tokens don't need to be added to the list. They are
1547         // redundant.
1548         Changed = true;
1549         break;
1550
1551       case ISD::TokenFactor:
1552         if (Op.hasOneUse() &&
1553             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1554           // Queue up for processing.
1555           TFs.push_back(Op.getNode());
1556           // Clean up in case the token factor is removed.
1557           AddToWorklist(Op.getNode());
1558           Changed = true;
1559           break;
1560         }
1561         // Fall thru
1562
1563       default:
1564         // Only add if it isn't already in the list.
1565         if (SeenOps.insert(Op.getNode()).second)
1566           Ops.push_back(Op);
1567         else
1568           Changed = true;
1569         break;
1570       }
1571     }
1572   }
1573
1574   SDValue Result;
1575
1576   // If we've changed things around then replace token factor.
1577   if (Changed) {
1578     if (Ops.empty()) {
1579       // The entry token is the only possible outcome.
1580       Result = DAG.getEntryNode();
1581     } else {
1582       // New and improved token factor.
1583       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1584     }
1585
1586     // Add users to worklist if AA is enabled, since it may introduce
1587     // a lot of new chained token factors while removing memory deps.
1588     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1589       : DAG.getSubtarget().useAA();
1590     return CombineTo(N, Result, UseAA /*add to worklist*/);
1591   }
1592
1593   return Result;
1594 }
1595
1596 /// MERGE_VALUES can always be eliminated.
1597 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1598   WorklistRemover DeadNodes(*this);
1599   // Replacing results may cause a different MERGE_VALUES to suddenly
1600   // be CSE'd with N, and carry its uses with it. Iterate until no
1601   // uses remain, to ensure that the node can be safely deleted.
1602   // First add the users of this node to the work list so that they
1603   // can be tried again once they have new operands.
1604   AddUsersToWorklist(N);
1605   do {
1606     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1607       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1608   } while (!N->use_empty());
1609   deleteAndRecombine(N);
1610   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1611 }
1612
1613 static bool isNullConstant(SDValue V) {
1614   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1615   return Const != nullptr && Const->isNullValue();
1616 }
1617
1618 static bool isNullFPConstant(SDValue V) {
1619   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1620   return Const != nullptr && Const->isZero() && !Const->isNegative();
1621 }
1622
1623 static bool isAllOnesConstant(SDValue V) {
1624   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1625   return Const != nullptr && Const->isAllOnesValue();
1626 }
1627
1628 static bool isOneConstant(SDValue V) {
1629   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1630   return Const != nullptr && Const->isOne();
1631 }
1632
1633 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1634 /// ContantSDNode pointer else nullptr.
1635 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1636   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1637   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1638 }
1639
1640 SDValue DAGCombiner::visitADD(SDNode *N) {
1641   SDValue N0 = N->getOperand(0);
1642   SDValue N1 = N->getOperand(1);
1643   EVT VT = N0.getValueType();
1644
1645   // fold vector ops
1646   if (VT.isVector()) {
1647     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1648       return FoldedVOp;
1649
1650     // fold (add x, 0) -> x, vector edition
1651     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1652       return N0;
1653     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1654       return N1;
1655   }
1656
1657   // fold (add x, undef) -> undef
1658   if (N0.getOpcode() == ISD::UNDEF)
1659     return N0;
1660   if (N1.getOpcode() == ISD::UNDEF)
1661     return N1;
1662   // fold (add c1, c2) -> c1+c2
1663   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1664   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1665   if (N0C && N1C)
1666     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1667   // canonicalize constant to RHS
1668   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1669      !isConstantIntBuildVectorOrConstantInt(N1))
1670     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1671   // fold (add x, 0) -> x
1672   if (isNullConstant(N1))
1673     return N0;
1674   // fold (add Sym, c) -> Sym+c
1675   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1676     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1677         GA->getOpcode() == ISD::GlobalAddress)
1678       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1679                                   GA->getOffset() +
1680                                     (uint64_t)N1C->getSExtValue());
1681   // fold ((c1-A)+c2) -> (c1+c2)-A
1682   if (N1C && N0.getOpcode() == ISD::SUB)
1683     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1684       SDLoc DL(N);
1685       return DAG.getNode(ISD::SUB, DL, VT,
1686                          DAG.getConstant(N1C->getAPIntValue()+
1687                                          N0C->getAPIntValue(), DL, VT),
1688                          N0.getOperand(1));
1689     }
1690   // reassociate add
1691   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1692     return RADD;
1693   // fold ((0-A) + B) -> B-A
1694   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1696   // fold (A + (0-B)) -> A-B
1697   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1698     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1699   // fold (A+(B-A)) -> B
1700   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1701     return N1.getOperand(0);
1702   // fold ((B-A)+A) -> B
1703   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1704     return N0.getOperand(0);
1705   // fold (A+(B-(A+C))) to (B-C)
1706   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1707       N0 == N1.getOperand(1).getOperand(0))
1708     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1709                        N1.getOperand(1).getOperand(1));
1710   // fold (A+(B-(C+A))) to (B-C)
1711   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1712       N0 == N1.getOperand(1).getOperand(1))
1713     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1714                        N1.getOperand(1).getOperand(0));
1715   // fold (A+((B-A)+or-C)) to (B+or-C)
1716   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1717       N1.getOperand(0).getOpcode() == ISD::SUB &&
1718       N0 == N1.getOperand(0).getOperand(1))
1719     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1720                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1721
1722   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1723   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1724     SDValue N00 = N0.getOperand(0);
1725     SDValue N01 = N0.getOperand(1);
1726     SDValue N10 = N1.getOperand(0);
1727     SDValue N11 = N1.getOperand(1);
1728
1729     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1730       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1731                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1732                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1733   }
1734
1735   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1736     return SDValue(N, 0);
1737
1738   // fold (a+b) -> (a|b) iff a and b share no bits.
1739   if (VT.isInteger() && !VT.isVector()) {
1740     APInt LHSZero, LHSOne;
1741     APInt RHSZero, RHSOne;
1742     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1743
1744     if (LHSZero.getBoolValue()) {
1745       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1746
1747       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1748       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1749       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1750         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1751           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1752       }
1753     }
1754   }
1755
1756   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1757   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1758       isNullConstant(N1.getOperand(0).getOperand(0)))
1759     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1760                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1761                                    N1.getOperand(0).getOperand(1),
1762                                    N1.getOperand(1)));
1763   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1764       isNullConstant(N0.getOperand(0).getOperand(0)))
1765     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1766                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1767                                    N0.getOperand(0).getOperand(1),
1768                                    N0.getOperand(1)));
1769
1770   if (N1.getOpcode() == ISD::AND) {
1771     SDValue AndOp0 = N1.getOperand(0);
1772     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1773     unsigned DestBits = VT.getScalarType().getSizeInBits();
1774
1775     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1776     // and similar xforms where the inner op is either ~0 or 0.
1777     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1778       SDLoc DL(N);
1779       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1780     }
1781   }
1782
1783   // add (sext i1), X -> sub X, (zext i1)
1784   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1785       N0.getOperand(0).getValueType() == MVT::i1 &&
1786       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1787     SDLoc DL(N);
1788     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1789     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1790   }
1791
1792   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1793   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1794     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1795     if (TN->getVT() == MVT::i1) {
1796       SDLoc DL(N);
1797       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1798                                  DAG.getConstant(1, DL, VT));
1799       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1800     }
1801   }
1802
1803   return SDValue();
1804 }
1805
1806 SDValue DAGCombiner::visitADDC(SDNode *N) {
1807   SDValue N0 = N->getOperand(0);
1808   SDValue N1 = N->getOperand(1);
1809   EVT VT = N0.getValueType();
1810
1811   // If the flag result is dead, turn this into an ADD.
1812   if (!N->hasAnyUseOfValue(1))
1813     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1814                      DAG.getNode(ISD::CARRY_FALSE,
1815                                  SDLoc(N), MVT::Glue));
1816
1817   // canonicalize constant to RHS.
1818   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1819   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1820   if (N0C && !N1C)
1821     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1822
1823   // fold (addc x, 0) -> x + no carry out
1824   if (isNullConstant(N1))
1825     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1826                                         SDLoc(N), MVT::Glue));
1827
1828   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1829   APInt LHSZero, LHSOne;
1830   APInt RHSZero, RHSOne;
1831   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1832
1833   if (LHSZero.getBoolValue()) {
1834     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1835
1836     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1837     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1838     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1839       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1840                        DAG.getNode(ISD::CARRY_FALSE,
1841                                    SDLoc(N), MVT::Glue));
1842   }
1843
1844   return SDValue();
1845 }
1846
1847 SDValue DAGCombiner::visitADDE(SDNode *N) {
1848   SDValue N0 = N->getOperand(0);
1849   SDValue N1 = N->getOperand(1);
1850   SDValue CarryIn = N->getOperand(2);
1851
1852   // canonicalize constant to RHS
1853   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1854   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1855   if (N0C && !N1C)
1856     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1857                        N1, N0, CarryIn);
1858
1859   // fold (adde x, y, false) -> (addc x, y)
1860   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1861     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1862
1863   return SDValue();
1864 }
1865
1866 // Since it may not be valid to emit a fold to zero for vector initializers
1867 // check if we can before folding.
1868 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1869                              SelectionDAG &DAG,
1870                              bool LegalOperations, bool LegalTypes) {
1871   if (!VT.isVector())
1872     return DAG.getConstant(0, DL, VT);
1873   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1874     return DAG.getConstant(0, DL, VT);
1875   return SDValue();
1876 }
1877
1878 SDValue DAGCombiner::visitSUB(SDNode *N) {
1879   SDValue N0 = N->getOperand(0);
1880   SDValue N1 = N->getOperand(1);
1881   EVT VT = N0.getValueType();
1882
1883   // fold vector ops
1884   if (VT.isVector()) {
1885     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1886       return FoldedVOp;
1887
1888     // fold (sub x, 0) -> x, vector edition
1889     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1890       return N0;
1891   }
1892
1893   // fold (sub x, x) -> 0
1894   // FIXME: Refactor this and xor and other similar operations together.
1895   if (N0 == N1)
1896     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1897   // fold (sub c1, c2) -> c1-c2
1898   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1899   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1900   if (N0C && N1C)
1901     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1902   // fold (sub x, c) -> (add x, -c)
1903   if (N1C) {
1904     SDLoc DL(N);
1905     return DAG.getNode(ISD::ADD, DL, VT, N0,
1906                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1907   }
1908   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1909   if (isAllOnesConstant(N0))
1910     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1911   // fold A-(A-B) -> B
1912   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1913     return N1.getOperand(1);
1914   // fold (A+B)-A -> B
1915   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1916     return N0.getOperand(1);
1917   // fold (A+B)-B -> A
1918   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1919     return N0.getOperand(0);
1920   // fold C2-(A+C1) -> (C2-C1)-A
1921   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1922     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1923   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1924     SDLoc DL(N);
1925     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1926                                    DL, VT);
1927     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1928                        N1.getOperand(0));
1929   }
1930   // fold ((A+(B+or-C))-B) -> A+or-C
1931   if (N0.getOpcode() == ISD::ADD &&
1932       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1933        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1934       N0.getOperand(1).getOperand(0) == N1)
1935     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1936                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1937   // fold ((A+(C+B))-B) -> A+C
1938   if (N0.getOpcode() == ISD::ADD &&
1939       N0.getOperand(1).getOpcode() == ISD::ADD &&
1940       N0.getOperand(1).getOperand(1) == N1)
1941     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1942                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1943   // fold ((A-(B-C))-C) -> A-B
1944   if (N0.getOpcode() == ISD::SUB &&
1945       N0.getOperand(1).getOpcode() == ISD::SUB &&
1946       N0.getOperand(1).getOperand(1) == N1)
1947     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1948                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1949
1950   // If either operand of a sub is undef, the result is undef
1951   if (N0.getOpcode() == ISD::UNDEF)
1952     return N0;
1953   if (N1.getOpcode() == ISD::UNDEF)
1954     return N1;
1955
1956   // If the relocation model supports it, consider symbol offsets.
1957   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1958     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1959       // fold (sub Sym, c) -> Sym-c
1960       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1961         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1962                                     GA->getOffset() -
1963                                       (uint64_t)N1C->getSExtValue());
1964       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1965       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1966         if (GA->getGlobal() == GB->getGlobal())
1967           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1968                                  SDLoc(N), VT);
1969     }
1970
1971   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1972   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1973     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1974     if (TN->getVT() == MVT::i1) {
1975       SDLoc DL(N);
1976       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1977                                  DAG.getConstant(1, DL, VT));
1978       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1979     }
1980   }
1981
1982   return SDValue();
1983 }
1984
1985 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1986   SDValue N0 = N->getOperand(0);
1987   SDValue N1 = N->getOperand(1);
1988   EVT VT = N0.getValueType();
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, SDLoc(N), VT, N0, N1),
1993                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1994                                  MVT::Glue));
1995
1996   // fold (subc x, x) -> 0 + no borrow
1997   if (N0 == N1) {
1998     SDLoc DL(N);
1999     return CombineTo(N, DAG.getConstant(0, DL, VT),
2000                      DAG.getNode(ISD::CARRY_FALSE, DL,
2001                                  MVT::Glue));
2002   }
2003
2004   // fold (subc x, 0) -> x + no borrow
2005   if (isNullConstant(N1))
2006     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2007                                         MVT::Glue));
2008
2009   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2010   if (isAllOnesConstant(N0))
2011     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2012                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2013                                  MVT::Glue));
2014
2015   return SDValue();
2016 }
2017
2018 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2019   SDValue N0 = N->getOperand(0);
2020   SDValue N1 = N->getOperand(1);
2021   SDValue CarryIn = N->getOperand(2);
2022
2023   // fold (sube x, y, false) -> (subc x, y)
2024   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2025     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2026
2027   return SDValue();
2028 }
2029
2030 SDValue DAGCombiner::visitMUL(SDNode *N) {
2031   SDValue N0 = N->getOperand(0);
2032   SDValue N1 = N->getOperand(1);
2033   EVT VT = N0.getValueType();
2034
2035   // fold (mul x, undef) -> 0
2036   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2037     return DAG.getConstant(0, SDLoc(N), VT);
2038
2039   bool N0IsConst = false;
2040   bool N1IsConst = false;
2041   bool N1IsOpaqueConst = false;
2042   bool N0IsOpaqueConst = false;
2043   APInt ConstValue0, ConstValue1;
2044   // fold vector ops
2045   if (VT.isVector()) {
2046     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2047       return FoldedVOp;
2048
2049     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2050     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2051   } else {
2052     N0IsConst = isa<ConstantSDNode>(N0);
2053     if (N0IsConst) {
2054       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2055       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2056     }
2057     N1IsConst = isa<ConstantSDNode>(N1);
2058     if (N1IsConst) {
2059       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2060       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2061     }
2062   }
2063
2064   // fold (mul c1, c2) -> c1*c2
2065   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2066     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2067                                       N0.getNode(), N1.getNode());
2068
2069   // canonicalize constant to RHS (vector doesn't have to splat)
2070   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2071      !isConstantIntBuildVectorOrConstantInt(N1))
2072     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2073   // fold (mul x, 0) -> 0
2074   if (N1IsConst && ConstValue1 == 0)
2075     return N1;
2076   // We require a splat of the entire scalar bit width for non-contiguous
2077   // bit patterns.
2078   bool IsFullSplat =
2079     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2080   // fold (mul x, 1) -> x
2081   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2082     return N0;
2083   // fold (mul x, -1) -> 0-x
2084   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2085     SDLoc DL(N);
2086     return DAG.getNode(ISD::SUB, DL, VT,
2087                        DAG.getConstant(0, DL, VT), N0);
2088   }
2089   // fold (mul x, (1 << c)) -> x << c
2090   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2091       IsFullSplat) {
2092     SDLoc DL(N);
2093     return DAG.getNode(ISD::SHL, DL, VT, N0,
2094                        DAG.getConstant(ConstValue1.logBase2(), DL,
2095                                        getShiftAmountTy(N0.getValueType())));
2096   }
2097   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2098   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2099       IsFullSplat) {
2100     unsigned Log2Val = (-ConstValue1).logBase2();
2101     SDLoc DL(N);
2102     // FIXME: If the input is something that is easily negated (e.g. a
2103     // single-use add), we should put the negate there.
2104     return DAG.getNode(ISD::SUB, DL, VT,
2105                        DAG.getConstant(0, DL, VT),
2106                        DAG.getNode(ISD::SHL, DL, VT, N0,
2107                             DAG.getConstant(Log2Val, DL,
2108                                       getShiftAmountTy(N0.getValueType()))));
2109   }
2110
2111   APInt Val;
2112   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2113   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2114       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2116     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2117                              N1, N0.getOperand(1));
2118     AddToWorklist(C3.getNode());
2119     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2120                        N0.getOperand(0), C3);
2121   }
2122
2123   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2124   // use.
2125   {
2126     SDValue Sh(nullptr,0), Y(nullptr,0);
2127     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2128     if (N0.getOpcode() == ISD::SHL &&
2129         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2130                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2131         N0.getNode()->hasOneUse()) {
2132       Sh = N0; Y = N1;
2133     } else if (N1.getOpcode() == ISD::SHL &&
2134                isa<ConstantSDNode>(N1.getOperand(1)) &&
2135                N1.getNode()->hasOneUse()) {
2136       Sh = N1; Y = N0;
2137     }
2138
2139     if (Sh.getNode()) {
2140       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2141                                 Sh.getOperand(0), Y);
2142       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2143                          Mul, Sh.getOperand(1));
2144     }
2145   }
2146
2147   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2148   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2149       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2150                      isa<ConstantSDNode>(N0.getOperand(1))))
2151     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2152                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2153                                    N0.getOperand(0), N1),
2154                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2155                                    N0.getOperand(1), N1));
2156
2157   // reassociate mul
2158   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2159     return RMUL;
2160
2161   return SDValue();
2162 }
2163
2164 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2165   SDValue N0 = N->getOperand(0);
2166   SDValue N1 = N->getOperand(1);
2167   EVT VT = N->getValueType(0);
2168
2169   // fold vector ops
2170   if (VT.isVector())
2171     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2172       return FoldedVOp;
2173
2174   // fold (sdiv c1, c2) -> c1/c2
2175   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2176   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2177   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2178     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2179   // fold (sdiv X, 1) -> X
2180   if (N1C && N1C->isOne())
2181     return N0;
2182   // fold (sdiv X, -1) -> 0-X
2183   if (N1C && N1C->isAllOnesValue()) {
2184     SDLoc DL(N);
2185     return DAG.getNode(ISD::SUB, DL, VT,
2186                        DAG.getConstant(0, DL, VT), N0);
2187   }
2188   // If we know the sign bits of both operands are zero, strength reduce to a
2189   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2190   if (!VT.isVector()) {
2191     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2192       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2193                          N0, N1);
2194   }
2195
2196   // fold (sdiv X, pow2) -> simple ops after legalize
2197   // FIXME: We check for the exact bit here because the generic lowering gives
2198   // better results in that case. The target-specific lowering should learn how
2199   // to handle exact sdivs efficiently.
2200   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2201       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2202       (N1C->getAPIntValue().isPowerOf2() ||
2203        (-N1C->getAPIntValue()).isPowerOf2())) {
2204     // Target-specific implementation of sdiv x, pow2.
2205     if (SDValue Res = BuildSDIVPow2(N))
2206       return Res;
2207
2208     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2209     SDLoc DL(N);
2210
2211     // Splat the sign bit into the register
2212     SDValue SGN =
2213         DAG.getNode(ISD::SRA, DL, VT, N0,
2214                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2215                                     getShiftAmountTy(N0.getValueType())));
2216     AddToWorklist(SGN.getNode());
2217
2218     // Add (N0 < 0) ? abs2 - 1 : 0;
2219     SDValue SRL =
2220         DAG.getNode(ISD::SRL, DL, VT, SGN,
2221                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2222                                     getShiftAmountTy(SGN.getValueType())));
2223     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2224     AddToWorklist(SRL.getNode());
2225     AddToWorklist(ADD.getNode());    // Divide by pow2
2226     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2227                   DAG.getConstant(lg2, DL,
2228                                   getShiftAmountTy(ADD.getValueType())));
2229
2230     // If we're dividing by a positive value, we're done.  Otherwise, we must
2231     // negate the result.
2232     if (N1C->getAPIntValue().isNonNegative())
2233       return SRA;
2234
2235     AddToWorklist(SRA.getNode());
2236     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2237   }
2238
2239   // If integer divide is expensive and we satisfy the requirements, emit an
2240   // alternate sequence.  Targets may check function attributes for size/speed
2241   // trade-offs.
2242   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2243   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2244     if (SDValue Op = BuildSDIV(N))
2245       return Op;
2246
2247   // undef / X -> 0
2248   if (N0.getOpcode() == ISD::UNDEF)
2249     return DAG.getConstant(0, SDLoc(N), VT);
2250   // X / undef -> undef
2251   if (N1.getOpcode() == ISD::UNDEF)
2252     return N1;
2253
2254   return SDValue();
2255 }
2256
2257 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2258   SDValue N0 = N->getOperand(0);
2259   SDValue N1 = N->getOperand(1);
2260   EVT VT = N->getValueType(0);
2261
2262   // fold vector ops
2263   if (VT.isVector())
2264     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2265       return FoldedVOp;
2266
2267   // fold (udiv c1, c2) -> c1/c2
2268   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2269   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2270   if (N0C && N1C)
2271     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2272                                                     N0C, N1C))
2273       return Folded;
2274   // fold (udiv x, (1 << c)) -> x >>u c
2275   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2276     SDLoc DL(N);
2277     return DAG.getNode(ISD::SRL, DL, VT, N0,
2278                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2279                                        getShiftAmountTy(N0.getValueType())));
2280   }
2281   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2282   if (N1.getOpcode() == ISD::SHL) {
2283     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2284       if (SHC->getAPIntValue().isPowerOf2()) {
2285         EVT ADDVT = N1.getOperand(1).getValueType();
2286         SDLoc DL(N);
2287         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2288                                   N1.getOperand(1),
2289                                   DAG.getConstant(SHC->getAPIntValue()
2290                                                                   .logBase2(),
2291                                                   DL, ADDVT));
2292         AddToWorklist(Add.getNode());
2293         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2294       }
2295     }
2296   }
2297
2298   // fold (udiv x, c) -> alternate
2299   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2300   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2301     if (SDValue Op = BuildUDIV(N))
2302       return Op;
2303
2304   // undef / X -> 0
2305   if (N0.getOpcode() == ISD::UNDEF)
2306     return DAG.getConstant(0, SDLoc(N), VT);
2307   // X / undef -> undef
2308   if (N1.getOpcode() == ISD::UNDEF)
2309     return N1;
2310
2311   return SDValue();
2312 }
2313
2314 SDValue DAGCombiner::visitSREM(SDNode *N) {
2315   SDValue N0 = N->getOperand(0);
2316   SDValue N1 = N->getOperand(1);
2317   EVT VT = N->getValueType(0);
2318
2319   // fold (srem c1, c2) -> c1%c2
2320   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2321   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2322   if (N0C && N1C)
2323     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2324                                                     N0C, N1C))
2325       return Folded;
2326   // If we know the sign bits of both operands are zero, strength reduce to a
2327   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2328   if (!VT.isVector()) {
2329     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2330       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2331   }
2332
2333   // If X/C can be simplified by the division-by-constant logic, lower
2334   // X%C to the equivalent of X-X/C*C.
2335   if (N1C && !N1C->isNullValue()) {
2336     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2337     AddToWorklist(Div.getNode());
2338     SDValue OptimizedDiv = combine(Div.getNode());
2339     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2340       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2341                                 OptimizedDiv, N1);
2342       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2343       AddToWorklist(Mul.getNode());
2344       return Sub;
2345     }
2346   }
2347
2348   // undef % X -> 0
2349   if (N0.getOpcode() == ISD::UNDEF)
2350     return DAG.getConstant(0, SDLoc(N), VT);
2351   // X % undef -> undef
2352   if (N1.getOpcode() == ISD::UNDEF)
2353     return N1;
2354
2355   return SDValue();
2356 }
2357
2358 SDValue DAGCombiner::visitUREM(SDNode *N) {
2359   SDValue N0 = N->getOperand(0);
2360   SDValue N1 = N->getOperand(1);
2361   EVT VT = N->getValueType(0);
2362
2363   // fold (urem c1, c2) -> c1%c2
2364   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2365   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2366   if (N0C && N1C)
2367     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2368                                                     N0C, N1C))
2369       return Folded;
2370   // fold (urem x, pow2) -> (and x, pow2-1)
2371   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2372       N1C->getAPIntValue().isPowerOf2()) {
2373     SDLoc DL(N);
2374     return DAG.getNode(ISD::AND, DL, VT, N0,
2375                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2376   }
2377   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2378   if (N1.getOpcode() == ISD::SHL) {
2379     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2380       if (SHC->getAPIntValue().isPowerOf2()) {
2381         SDLoc DL(N);
2382         SDValue Add =
2383           DAG.getNode(ISD::ADD, DL, VT, N1,
2384                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2385                                  VT));
2386         AddToWorklist(Add.getNode());
2387         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2388       }
2389     }
2390   }
2391
2392   // If X/C can be simplified by the division-by-constant logic, lower
2393   // X%C to the equivalent of X-X/C*C.
2394   if (N1C && !N1C->isNullValue()) {
2395     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2396     AddToWorklist(Div.getNode());
2397     SDValue OptimizedDiv = combine(Div.getNode());
2398     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2399       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2400                                 OptimizedDiv, N1);
2401       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2402       AddToWorklist(Mul.getNode());
2403       return Sub;
2404     }
2405   }
2406
2407   // undef % X -> 0
2408   if (N0.getOpcode() == ISD::UNDEF)
2409     return DAG.getConstant(0, SDLoc(N), VT);
2410   // X % undef -> undef
2411   if (N1.getOpcode() == ISD::UNDEF)
2412     return N1;
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2418   SDValue N0 = N->getOperand(0);
2419   SDValue N1 = N->getOperand(1);
2420   EVT VT = N->getValueType(0);
2421   SDLoc DL(N);
2422
2423   // fold (mulhs x, 0) -> 0
2424   if (isNullConstant(N1))
2425     return N1;
2426   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2427   if (isOneConstant(N1)) {
2428     SDLoc DL(N);
2429     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2430                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2431                                        DL,
2432                                        getShiftAmountTy(N0.getValueType())));
2433   }
2434   // fold (mulhs x, undef) -> 0
2435   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2436     return DAG.getConstant(0, SDLoc(N), VT);
2437
2438   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2439   // plus a shift.
2440   if (VT.isSimple() && !VT.isVector()) {
2441     MVT Simple = VT.getSimpleVT();
2442     unsigned SimpleSize = Simple.getSizeInBits();
2443     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2444     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2445       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2446       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2447       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2448       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2449             DAG.getConstant(SimpleSize, DL,
2450                             getShiftAmountTy(N1.getValueType())));
2451       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2452     }
2453   }
2454
2455   return SDValue();
2456 }
2457
2458 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2459   SDValue N0 = N->getOperand(0);
2460   SDValue N1 = N->getOperand(1);
2461   EVT VT = N->getValueType(0);
2462   SDLoc DL(N);
2463
2464   // fold (mulhu x, 0) -> 0
2465   if (isNullConstant(N1))
2466     return N1;
2467   // fold (mulhu x, 1) -> 0
2468   if (isOneConstant(N1))
2469     return DAG.getConstant(0, DL, N0.getValueType());
2470   // fold (mulhu x, undef) -> 0
2471   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2472     return DAG.getConstant(0, DL, VT);
2473
2474   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2475   // plus a shift.
2476   if (VT.isSimple() && !VT.isVector()) {
2477     MVT Simple = VT.getSimpleVT();
2478     unsigned SimpleSize = Simple.getSizeInBits();
2479     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2480     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2481       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2482       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2483       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2484       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2485             DAG.getConstant(SimpleSize, DL,
2486                             getShiftAmountTy(N1.getValueType())));
2487       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2488     }
2489   }
2490
2491   return SDValue();
2492 }
2493
2494 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2495 /// give the opcodes for the two computations that are being performed. Return
2496 /// true if a simplification was made.
2497 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2498                                                 unsigned HiOp) {
2499   // If the high half is not needed, just compute the low half.
2500   bool HiExists = N->hasAnyUseOfValue(1);
2501   if (!HiExists &&
2502       (!LegalOperations ||
2503        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2504     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2505     return CombineTo(N, Res, Res);
2506   }
2507
2508   // If the low half is not needed, just compute the high half.
2509   bool LoExists = N->hasAnyUseOfValue(0);
2510   if (!LoExists &&
2511       (!LegalOperations ||
2512        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2513     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2514     return CombineTo(N, Res, Res);
2515   }
2516
2517   // If both halves are used, return as it is.
2518   if (LoExists && HiExists)
2519     return SDValue();
2520
2521   // If the two computed results can be simplified separately, separate them.
2522   if (LoExists) {
2523     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2524     AddToWorklist(Lo.getNode());
2525     SDValue LoOpt = combine(Lo.getNode());
2526     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2527         (!LegalOperations ||
2528          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2529       return CombineTo(N, LoOpt, LoOpt);
2530   }
2531
2532   if (HiExists) {
2533     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2534     AddToWorklist(Hi.getNode());
2535     SDValue HiOpt = combine(Hi.getNode());
2536     if (HiOpt.getNode() && HiOpt != Hi &&
2537         (!LegalOperations ||
2538          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2539       return CombineTo(N, HiOpt, HiOpt);
2540   }
2541
2542   return SDValue();
2543 }
2544
2545 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2546   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2547     return Res;
2548
2549   EVT VT = N->getValueType(0);
2550   SDLoc DL(N);
2551
2552   // If the type is twice as wide is legal, transform the mulhu to a wider
2553   // multiply plus a shift.
2554   if (VT.isSimple() && !VT.isVector()) {
2555     MVT Simple = VT.getSimpleVT();
2556     unsigned SimpleSize = Simple.getSizeInBits();
2557     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2558     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2559       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2560       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2561       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2562       // Compute the high part as N1.
2563       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2564             DAG.getConstant(SimpleSize, DL,
2565                             getShiftAmountTy(Lo.getValueType())));
2566       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2567       // Compute the low part as N0.
2568       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2569       return CombineTo(N, Lo, Hi);
2570     }
2571   }
2572
2573   return SDValue();
2574 }
2575
2576 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2577   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2578     return Res;
2579
2580   EVT VT = N->getValueType(0);
2581   SDLoc DL(N);
2582
2583   // If the type is twice as wide is legal, transform the mulhu to a wider
2584   // multiply plus a shift.
2585   if (VT.isSimple() && !VT.isVector()) {
2586     MVT Simple = VT.getSimpleVT();
2587     unsigned SimpleSize = Simple.getSizeInBits();
2588     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2589     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2590       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2591       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2592       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2593       // Compute the high part as N1.
2594       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2595             DAG.getConstant(SimpleSize, DL,
2596                             getShiftAmountTy(Lo.getValueType())));
2597       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2598       // Compute the low part as N0.
2599       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2600       return CombineTo(N, Lo, Hi);
2601     }
2602   }
2603
2604   return SDValue();
2605 }
2606
2607 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2608   // (smulo x, 2) -> (saddo x, x)
2609   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2610     if (C2->getAPIntValue() == 2)
2611       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2612                          N->getOperand(0), N->getOperand(0));
2613
2614   return SDValue();
2615 }
2616
2617 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2618   // (umulo x, 2) -> (uaddo x, x)
2619   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2620     if (C2->getAPIntValue() == 2)
2621       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2622                          N->getOperand(0), N->getOperand(0));
2623
2624   return SDValue();
2625 }
2626
2627 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2628   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2629     return Res;
2630
2631   return SDValue();
2632 }
2633
2634 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2635   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2636     return Res;
2637
2638   return SDValue();
2639 }
2640
2641 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2642   SDValue N0 = N->getOperand(0);
2643   SDValue N1 = N->getOperand(1);
2644   EVT VT = N0.getValueType();
2645
2646   // fold vector ops
2647   if (VT.isVector())
2648     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2649       return FoldedVOp;
2650
2651   // fold (add c1, c2) -> c1+c2
2652   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2653   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2654   if (N0C && N1C)
2655     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2656
2657   // canonicalize constant to RHS
2658   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2659      !isConstantIntBuildVectorOrConstantInt(N1))
2660     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2661
2662   return SDValue();
2663 }
2664
2665 /// If this is a binary operator with two operands of the same opcode, try to
2666 /// simplify it.
2667 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2668   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2669   EVT VT = N0.getValueType();
2670   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2671
2672   // Bail early if none of these transforms apply.
2673   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2674
2675   // For each of OP in AND/OR/XOR:
2676   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2677   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2678   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2679   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2680   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2681   //
2682   // do not sink logical op inside of a vector extend, since it may combine
2683   // into a vsetcc.
2684   EVT Op0VT = N0.getOperand(0).getValueType();
2685   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2686        N0.getOpcode() == ISD::SIGN_EXTEND ||
2687        N0.getOpcode() == ISD::BSWAP ||
2688        // Avoid infinite looping with PromoteIntBinOp.
2689        (N0.getOpcode() == ISD::ANY_EXTEND &&
2690         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2691        (N0.getOpcode() == ISD::TRUNCATE &&
2692         (!TLI.isZExtFree(VT, Op0VT) ||
2693          !TLI.isTruncateFree(Op0VT, VT)) &&
2694         TLI.isTypeLegal(Op0VT))) &&
2695       !VT.isVector() &&
2696       Op0VT == N1.getOperand(0).getValueType() &&
2697       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2698     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2699                                  N0.getOperand(0).getValueType(),
2700                                  N0.getOperand(0), N1.getOperand(0));
2701     AddToWorklist(ORNode.getNode());
2702     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2703   }
2704
2705   // For each of OP in SHL/SRL/SRA/AND...
2706   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2707   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2708   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2709   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2710        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2711       N0.getOperand(1) == N1.getOperand(1)) {
2712     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2713                                  N0.getOperand(0).getValueType(),
2714                                  N0.getOperand(0), N1.getOperand(0));
2715     AddToWorklist(ORNode.getNode());
2716     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2717                        ORNode, N0.getOperand(1));
2718   }
2719
2720   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2721   // Only perform this optimization after type legalization and before
2722   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2723   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2724   // we don't want to undo this promotion.
2725   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2726   // on scalars.
2727   if ((N0.getOpcode() == ISD::BITCAST ||
2728        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2729       Level == AfterLegalizeTypes) {
2730     SDValue In0 = N0.getOperand(0);
2731     SDValue In1 = N1.getOperand(0);
2732     EVT In0Ty = In0.getValueType();
2733     EVT In1Ty = In1.getValueType();
2734     SDLoc DL(N);
2735     // If both incoming values are integers, and the original types are the
2736     // same.
2737     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2738       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2739       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2740       AddToWorklist(Op.getNode());
2741       return BC;
2742     }
2743   }
2744
2745   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2746   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2747   // If both shuffles use the same mask, and both shuffle within a single
2748   // vector, then it is worthwhile to move the swizzle after the operation.
2749   // The type-legalizer generates this pattern when loading illegal
2750   // vector types from memory. In many cases this allows additional shuffle
2751   // optimizations.
2752   // There are other cases where moving the shuffle after the xor/and/or
2753   // is profitable even if shuffles don't perform a swizzle.
2754   // If both shuffles use the same mask, and both shuffles have the same first
2755   // or second operand, then it might still be profitable to move the shuffle
2756   // after the xor/and/or operation.
2757   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2758     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2759     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2760
2761     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2762            "Inputs to shuffles are not the same type");
2763
2764     // Check that both shuffles use the same mask. The masks are known to be of
2765     // the same length because the result vector type is the same.
2766     // Check also that shuffles have only one use to avoid introducing extra
2767     // instructions.
2768     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2769         SVN0->getMask().equals(SVN1->getMask())) {
2770       SDValue ShOp = N0->getOperand(1);
2771
2772       // Don't try to fold this node if it requires introducing a
2773       // build vector of all zeros that might be illegal at this stage.
2774       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2775         if (!LegalTypes)
2776           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2777         else
2778           ShOp = SDValue();
2779       }
2780
2781       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2782       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2783       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2784       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2785         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2786                                       N0->getOperand(0), N1->getOperand(0));
2787         AddToWorklist(NewNode.getNode());
2788         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2789                                     &SVN0->getMask()[0]);
2790       }
2791
2792       // Don't try to fold this node if it requires introducing a
2793       // build vector of all zeros that might be illegal at this stage.
2794       ShOp = N0->getOperand(0);
2795       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2796         if (!LegalTypes)
2797           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2798         else
2799           ShOp = SDValue();
2800       }
2801
2802       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2803       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2804       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2805       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2806         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2807                                       N0->getOperand(1), N1->getOperand(1));
2808         AddToWorklist(NewNode.getNode());
2809         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2810                                     &SVN0->getMask()[0]);
2811       }
2812     }
2813   }
2814
2815   return SDValue();
2816 }
2817
2818 /// This contains all DAGCombine rules which reduce two values combined by
2819 /// an And operation to a single value. This makes them reusable in the context
2820 /// of visitSELECT(). Rules involving constants are not included as
2821 /// visitSELECT() already handles those cases.
2822 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2823                                   SDNode *LocReference) {
2824   EVT VT = N1.getValueType();
2825
2826   // fold (and x, undef) -> 0
2827   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2828     return DAG.getConstant(0, SDLoc(LocReference), VT);
2829   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2830   SDValue LL, LR, RL, RR, CC0, CC1;
2831   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2832     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2833     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2834
2835     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2836         LL.getValueType().isInteger()) {
2837       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2838       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2839         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2840                                      LR.getValueType(), LL, RL);
2841         AddToWorklist(ORNode.getNode());
2842         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2843       }
2844       if (isAllOnesConstant(LR)) {
2845         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2846         if (Op1 == ISD::SETEQ) {
2847           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2848                                         LR.getValueType(), LL, RL);
2849           AddToWorklist(ANDNode.getNode());
2850           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2851         }
2852         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2853         if (Op1 == ISD::SETGT) {
2854           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2855                                        LR.getValueType(), LL, RL);
2856           AddToWorklist(ORNode.getNode());
2857           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2858         }
2859       }
2860     }
2861     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2862     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2863         Op0 == Op1 && LL.getValueType().isInteger() &&
2864       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2865                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2866       SDLoc DL(N0);
2867       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2868                                     LL, DAG.getConstant(1, DL,
2869                                                         LL.getValueType()));
2870       AddToWorklist(ADDNode.getNode());
2871       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2872                           DAG.getConstant(2, DL, LL.getValueType()),
2873                           ISD::SETUGE);
2874     }
2875     // canonicalize equivalent to ll == rl
2876     if (LL == RR && LR == RL) {
2877       Op1 = ISD::getSetCCSwappedOperands(Op1);
2878       std::swap(RL, RR);
2879     }
2880     if (LL == RL && LR == RR) {
2881       bool isInteger = LL.getValueType().isInteger();
2882       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2883       if (Result != ISD::SETCC_INVALID &&
2884           (!LegalOperations ||
2885            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2886             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2887         EVT CCVT = getSetCCResultType(LL.getValueType());
2888         if (N0.getValueType() == CCVT ||
2889             (!LegalOperations && N0.getValueType() == MVT::i1))
2890           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2891                               LL, LR, Result);
2892       }
2893     }
2894   }
2895
2896   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2897       VT.getSizeInBits() <= 64) {
2898     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2899       APInt ADDC = ADDI->getAPIntValue();
2900       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2901         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2902         // immediate for an add, but it is legal if its top c2 bits are set,
2903         // transform the ADD so the immediate doesn't need to be materialized
2904         // in a register.
2905         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2906           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2907                                              SRLI->getZExtValue());
2908           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2909             ADDC |= Mask;
2910             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2911               SDLoc DL(N0);
2912               SDValue NewAdd =
2913                 DAG.getNode(ISD::ADD, DL, VT,
2914                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2915               CombineTo(N0.getNode(), NewAdd);
2916               // Return N so it doesn't get rechecked!
2917               return SDValue(LocReference, 0);
2918             }
2919           }
2920         }
2921       }
2922     }
2923   }
2924
2925   return SDValue();
2926 }
2927
2928 SDValue DAGCombiner::visitAND(SDNode *N) {
2929   SDValue N0 = N->getOperand(0);
2930   SDValue N1 = N->getOperand(1);
2931   EVT VT = N1.getValueType();
2932
2933   // fold vector ops
2934   if (VT.isVector()) {
2935     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2936       return FoldedVOp;
2937
2938     // fold (and x, 0) -> 0, vector edition
2939     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2940       // do not return N0, because undef node may exist in N0
2941       return DAG.getConstant(
2942           APInt::getNullValue(
2943               N0.getValueType().getScalarType().getSizeInBits()),
2944           SDLoc(N), N0.getValueType());
2945     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2946       // do not return N1, because undef node may exist in N1
2947       return DAG.getConstant(
2948           APInt::getNullValue(
2949               N1.getValueType().getScalarType().getSizeInBits()),
2950           SDLoc(N), N1.getValueType());
2951
2952     // fold (and x, -1) -> x, vector edition
2953     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2954       return N1;
2955     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2956       return N0;
2957   }
2958
2959   // fold (and c1, c2) -> c1&c2
2960   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2961   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2962   if (N0C && N1C && !N1C->isOpaque())
2963     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2964   // canonicalize constant to RHS
2965   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2966      !isConstantIntBuildVectorOrConstantInt(N1))
2967     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2968   // fold (and x, -1) -> x
2969   if (isAllOnesConstant(N1))
2970     return N0;
2971   // if (and x, c) is known to be zero, return 0
2972   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2973   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2974                                    APInt::getAllOnesValue(BitWidth)))
2975     return DAG.getConstant(0, SDLoc(N), VT);
2976   // reassociate and
2977   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2978     return RAND;
2979   // fold (and (or x, C), D) -> D if (C & D) == D
2980   if (N1C && N0.getOpcode() == ISD::OR)
2981     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2982       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2983         return N1;
2984   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2985   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2986     SDValue N0Op0 = N0.getOperand(0);
2987     APInt Mask = ~N1C->getAPIntValue();
2988     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2989     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2990       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2991                                  N0.getValueType(), N0Op0);
2992
2993       // Replace uses of the AND with uses of the Zero extend node.
2994       CombineTo(N, Zext);
2995
2996       // We actually want to replace all uses of the any_extend with the
2997       // zero_extend, to avoid duplicating things.  This will later cause this
2998       // AND to be folded.
2999       CombineTo(N0.getNode(), Zext);
3000       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3001     }
3002   }
3003   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3004   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3005   // already be zero by virtue of the width of the base type of the load.
3006   //
3007   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3008   // more cases.
3009   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3010        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3011       N0.getOpcode() == ISD::LOAD) {
3012     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3013                                          N0 : N0.getOperand(0) );
3014
3015     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3016     // This can be a pure constant or a vector splat, in which case we treat the
3017     // vector as a scalar and use the splat value.
3018     APInt Constant = APInt::getNullValue(1);
3019     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3020       Constant = C->getAPIntValue();
3021     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3022       APInt SplatValue, SplatUndef;
3023       unsigned SplatBitSize;
3024       bool HasAnyUndefs;
3025       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3026                                              SplatBitSize, HasAnyUndefs);
3027       if (IsSplat) {
3028         // Undef bits can contribute to a possible optimisation if set, so
3029         // set them.
3030         SplatValue |= SplatUndef;
3031
3032         // The splat value may be something like "0x00FFFFFF", which means 0 for
3033         // the first vector value and FF for the rest, repeating. We need a mask
3034         // that will apply equally to all members of the vector, so AND all the
3035         // lanes of the constant together.
3036         EVT VT = Vector->getValueType(0);
3037         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3038
3039         // If the splat value has been compressed to a bitlength lower
3040         // than the size of the vector lane, we need to re-expand it to
3041         // the lane size.
3042         if (BitWidth > SplatBitSize)
3043           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3044                SplatBitSize < BitWidth;
3045                SplatBitSize = SplatBitSize * 2)
3046             SplatValue |= SplatValue.shl(SplatBitSize);
3047
3048         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3049         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3050         if (SplatBitSize % BitWidth == 0) {
3051           Constant = APInt::getAllOnesValue(BitWidth);
3052           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3053             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3054         }
3055       }
3056     }
3057
3058     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3059     // actually legal and isn't going to get expanded, else this is a false
3060     // optimisation.
3061     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3062                                                     Load->getValueType(0),
3063                                                     Load->getMemoryVT());
3064
3065     // Resize the constant to the same size as the original memory access before
3066     // extension. If it is still the AllOnesValue then this AND is completely
3067     // unneeded.
3068     Constant =
3069       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3070
3071     bool B;
3072     switch (Load->getExtensionType()) {
3073     default: B = false; break;
3074     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3075     case ISD::ZEXTLOAD:
3076     case ISD::NON_EXTLOAD: B = true; break;
3077     }
3078
3079     if (B && Constant.isAllOnesValue()) {
3080       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3081       // preserve semantics once we get rid of the AND.
3082       SDValue NewLoad(Load, 0);
3083       if (Load->getExtensionType() == ISD::EXTLOAD) {
3084         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3085                               Load->getValueType(0), SDLoc(Load),
3086                               Load->getChain(), Load->getBasePtr(),
3087                               Load->getOffset(), Load->getMemoryVT(),
3088                               Load->getMemOperand());
3089         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3090         if (Load->getNumValues() == 3) {
3091           // PRE/POST_INC loads have 3 values.
3092           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3093                            NewLoad.getValue(2) };
3094           CombineTo(Load, To, 3, true);
3095         } else {
3096           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3097         }
3098       }
3099
3100       // Fold the AND away, taking care not to fold to the old load node if we
3101       // replaced it.
3102       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3103
3104       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3105     }
3106   }
3107
3108   // fold (and (load x), 255) -> (zextload x, i8)
3109   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3110   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3111   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3112               (N0.getOpcode() == ISD::ANY_EXTEND &&
3113                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3114     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3115     LoadSDNode *LN0 = HasAnyExt
3116       ? cast<LoadSDNode>(N0.getOperand(0))
3117       : cast<LoadSDNode>(N0);
3118     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3119         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3120       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3121       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3122         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3123         EVT LoadedVT = LN0->getMemoryVT();
3124         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3125
3126         if (ExtVT == LoadedVT &&
3127             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3128                                                     ExtVT))) {
3129
3130           SDValue NewLoad =
3131             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3132                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3133                            LN0->getMemOperand());
3134           AddToWorklist(N);
3135           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3136           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3137         }
3138
3139         // Do not change the width of a volatile load.
3140         // Do not generate loads of non-round integer types since these can
3141         // be expensive (and would be wrong if the type is not byte sized).
3142         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3143             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3144                                                     ExtVT))) {
3145           EVT PtrType = LN0->getOperand(1).getValueType();
3146
3147           unsigned Alignment = LN0->getAlignment();
3148           SDValue NewPtr = LN0->getBasePtr();
3149
3150           // For big endian targets, we need to add an offset to the pointer
3151           // to load the correct bytes.  For little endian systems, we merely
3152           // need to read fewer bytes from the same pointer.
3153           if (DAG.getDataLayout().isBigEndian()) {
3154             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3155             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3156             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3157             SDLoc DL(LN0);
3158             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3159                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3160             Alignment = MinAlign(Alignment, PtrOff);
3161           }
3162
3163           AddToWorklist(NewPtr.getNode());
3164
3165           SDValue Load =
3166             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3167                            LN0->getChain(), NewPtr,
3168                            LN0->getPointerInfo(),
3169                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3170                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3171           AddToWorklist(N);
3172           CombineTo(LN0, Load, Load.getValue(1));
3173           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3174         }
3175       }
3176     }
3177   }
3178
3179   if (SDValue Combined = visitANDLike(N0, N1, N))
3180     return Combined;
3181
3182   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3183   if (N0.getOpcode() == N1.getOpcode())
3184     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3185       return Tmp;
3186
3187   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3188   // fold (and (sra)) -> (and (srl)) when possible.
3189   if (!VT.isVector() &&
3190       SimplifyDemandedBits(SDValue(N, 0)))
3191     return SDValue(N, 0);
3192
3193   // fold (zext_inreg (extload x)) -> (zextload x)
3194   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3195     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3196     EVT MemVT = LN0->getMemoryVT();
3197     // If we zero all the possible extended bits, then we can turn this into
3198     // a zextload if we are running before legalize or the operation is legal.
3199     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3200     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3201                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3202         ((!LegalOperations && !LN0->isVolatile()) ||
3203          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3204       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3205                                        LN0->getChain(), LN0->getBasePtr(),
3206                                        MemVT, LN0->getMemOperand());
3207       AddToWorklist(N);
3208       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3209       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3210     }
3211   }
3212   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3213   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3214       N0.hasOneUse()) {
3215     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3216     EVT MemVT = LN0->getMemoryVT();
3217     // If we zero all the possible extended bits, then we can turn this into
3218     // a zextload if we are running before legalize or the operation is legal.
3219     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3220     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3221                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3222         ((!LegalOperations && !LN0->isVolatile()) ||
3223          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3224       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3225                                        LN0->getChain(), LN0->getBasePtr(),
3226                                        MemVT, LN0->getMemOperand());
3227       AddToWorklist(N);
3228       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3229       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3230     }
3231   }
3232   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3233   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3234     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3235                                        N0.getOperand(1), false);
3236     if (BSwap.getNode())
3237       return BSwap;
3238   }
3239
3240   return SDValue();
3241 }
3242
3243 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3244 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3245                                         bool DemandHighBits) {
3246   if (!LegalOperations)
3247     return SDValue();
3248
3249   EVT VT = N->getValueType(0);
3250   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3251     return SDValue();
3252   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3253     return SDValue();
3254
3255   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3256   bool LookPassAnd0 = false;
3257   bool LookPassAnd1 = false;
3258   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3259       std::swap(N0, N1);
3260   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3261       std::swap(N0, N1);
3262   if (N0.getOpcode() == ISD::AND) {
3263     if (!N0.getNode()->hasOneUse())
3264       return SDValue();
3265     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3266     if (!N01C || N01C->getZExtValue() != 0xFF00)
3267       return SDValue();
3268     N0 = N0.getOperand(0);
3269     LookPassAnd0 = true;
3270   }
3271
3272   if (N1.getOpcode() == ISD::AND) {
3273     if (!N1.getNode()->hasOneUse())
3274       return SDValue();
3275     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3276     if (!N11C || N11C->getZExtValue() != 0xFF)
3277       return SDValue();
3278     N1 = N1.getOperand(0);
3279     LookPassAnd1 = true;
3280   }
3281
3282   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3283     std::swap(N0, N1);
3284   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3285     return SDValue();
3286   if (!N0.getNode()->hasOneUse() ||
3287       !N1.getNode()->hasOneUse())
3288     return SDValue();
3289
3290   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3291   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3292   if (!N01C || !N11C)
3293     return SDValue();
3294   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3295     return SDValue();
3296
3297   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3298   SDValue N00 = N0->getOperand(0);
3299   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3300     if (!N00.getNode()->hasOneUse())
3301       return SDValue();
3302     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3303     if (!N001C || N001C->getZExtValue() != 0xFF)
3304       return SDValue();
3305     N00 = N00.getOperand(0);
3306     LookPassAnd0 = true;
3307   }
3308
3309   SDValue N10 = N1->getOperand(0);
3310   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3311     if (!N10.getNode()->hasOneUse())
3312       return SDValue();
3313     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3314     if (!N101C || N101C->getZExtValue() != 0xFF00)
3315       return SDValue();
3316     N10 = N10.getOperand(0);
3317     LookPassAnd1 = true;
3318   }
3319
3320   if (N00 != N10)
3321     return SDValue();
3322
3323   // Make sure everything beyond the low halfword gets set to zero since the SRL
3324   // 16 will clear the top bits.
3325   unsigned OpSizeInBits = VT.getSizeInBits();
3326   if (DemandHighBits && OpSizeInBits > 16) {
3327     // If the left-shift isn't masked out then the only way this is a bswap is
3328     // if all bits beyond the low 8 are 0. In that case the entire pattern
3329     // reduces to a left shift anyway: leave it for other parts of the combiner.
3330     if (!LookPassAnd0)
3331       return SDValue();
3332
3333     // However, if the right shift isn't masked out then it might be because
3334     // it's not needed. See if we can spot that too.
3335     if (!LookPassAnd1 &&
3336         !DAG.MaskedValueIsZero(
3337             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3338       return SDValue();
3339   }
3340
3341   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3342   if (OpSizeInBits > 16) {
3343     SDLoc DL(N);
3344     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3345                       DAG.getConstant(OpSizeInBits - 16, DL,
3346                                       getShiftAmountTy(VT)));
3347   }
3348   return Res;
3349 }
3350
3351 /// Return true if the specified node is an element that makes up a 32-bit
3352 /// packed halfword byteswap.
3353 /// ((x & 0x000000ff) << 8) |
3354 /// ((x & 0x0000ff00) >> 8) |
3355 /// ((x & 0x00ff0000) << 8) |
3356 /// ((x & 0xff000000) >> 8)
3357 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3358   if (!N.getNode()->hasOneUse())
3359     return false;
3360
3361   unsigned Opc = N.getOpcode();
3362   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3363     return false;
3364
3365   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3366   if (!N1C)
3367     return false;
3368
3369   unsigned Num;
3370   switch (N1C->getZExtValue()) {
3371   default:
3372     return false;
3373   case 0xFF:       Num = 0; break;
3374   case 0xFF00:     Num = 1; break;
3375   case 0xFF0000:   Num = 2; break;
3376   case 0xFF000000: Num = 3; break;
3377   }
3378
3379   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3380   SDValue N0 = N.getOperand(0);
3381   if (Opc == ISD::AND) {
3382     if (Num == 0 || Num == 2) {
3383       // (x >> 8) & 0xff
3384       // (x >> 8) & 0xff0000
3385       if (N0.getOpcode() != ISD::SRL)
3386         return false;
3387       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3388       if (!C || C->getZExtValue() != 8)
3389         return false;
3390     } else {
3391       // (x << 8) & 0xff00
3392       // (x << 8) & 0xff000000
3393       if (N0.getOpcode() != ISD::SHL)
3394         return false;
3395       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3396       if (!C || C->getZExtValue() != 8)
3397         return false;
3398     }
3399   } else if (Opc == ISD::SHL) {
3400     // (x & 0xff) << 8
3401     // (x & 0xff0000) << 8
3402     if (Num != 0 && Num != 2)
3403       return false;
3404     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3405     if (!C || C->getZExtValue() != 8)
3406       return false;
3407   } else { // Opc == ISD::SRL
3408     // (x & 0xff00) >> 8
3409     // (x & 0xff000000) >> 8
3410     if (Num != 1 && Num != 3)
3411       return false;
3412     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3413     if (!C || C->getZExtValue() != 8)
3414       return false;
3415   }
3416
3417   if (Parts[Num])
3418     return false;
3419
3420   Parts[Num] = N0.getOperand(0).getNode();
3421   return true;
3422 }
3423
3424 /// Match a 32-bit packed halfword bswap. That is
3425 /// ((x & 0x000000ff) << 8) |
3426 /// ((x & 0x0000ff00) >> 8) |
3427 /// ((x & 0x00ff0000) << 8) |
3428 /// ((x & 0xff000000) >> 8)
3429 /// => (rotl (bswap x), 16)
3430 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3431   if (!LegalOperations)
3432     return SDValue();
3433
3434   EVT VT = N->getValueType(0);
3435   if (VT != MVT::i32)
3436     return SDValue();
3437   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3438     return SDValue();
3439
3440   // Look for either
3441   // (or (or (and), (and)), (or (and), (and)))
3442   // (or (or (or (and), (and)), (and)), (and))
3443   if (N0.getOpcode() != ISD::OR)
3444     return SDValue();
3445   SDValue N00 = N0.getOperand(0);
3446   SDValue N01 = N0.getOperand(1);
3447   SDNode *Parts[4] = {};
3448
3449   if (N1.getOpcode() == ISD::OR &&
3450       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3451     // (or (or (and), (and)), (or (and), (and)))
3452     SDValue N000 = N00.getOperand(0);
3453     if (!isBSwapHWordElement(N000, Parts))
3454       return SDValue();
3455
3456     SDValue N001 = N00.getOperand(1);
3457     if (!isBSwapHWordElement(N001, Parts))
3458       return SDValue();
3459     SDValue N010 = N01.getOperand(0);
3460     if (!isBSwapHWordElement(N010, Parts))
3461       return SDValue();
3462     SDValue N011 = N01.getOperand(1);
3463     if (!isBSwapHWordElement(N011, Parts))
3464       return SDValue();
3465   } else {
3466     // (or (or (or (and), (and)), (and)), (and))
3467     if (!isBSwapHWordElement(N1, Parts))
3468       return SDValue();
3469     if (!isBSwapHWordElement(N01, Parts))
3470       return SDValue();
3471     if (N00.getOpcode() != ISD::OR)
3472       return SDValue();
3473     SDValue N000 = N00.getOperand(0);
3474     if (!isBSwapHWordElement(N000, Parts))
3475       return SDValue();
3476     SDValue N001 = N00.getOperand(1);
3477     if (!isBSwapHWordElement(N001, Parts))
3478       return SDValue();
3479   }
3480
3481   // Make sure the parts are all coming from the same node.
3482   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3483     return SDValue();
3484
3485   SDLoc DL(N);
3486   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3487                               SDValue(Parts[0], 0));
3488
3489   // Result of the bswap should be rotated by 16. If it's not legal, then
3490   // do  (x << 16) | (x >> 16).
3491   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3492   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3493     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3494   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3495     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3496   return DAG.getNode(ISD::OR, DL, VT,
3497                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3498                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3499 }
3500
3501 /// This contains all DAGCombine rules which reduce two values combined by
3502 /// an Or operation to a single value \see visitANDLike().
3503 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3504   EVT VT = N1.getValueType();
3505   // fold (or x, undef) -> -1
3506   if (!LegalOperations &&
3507       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3508     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3509     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3510                            SDLoc(LocReference), VT);
3511   }
3512   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3513   SDValue LL, LR, RL, RR, CC0, CC1;
3514   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3515     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3516     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3517
3518     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3519       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3520       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3521       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3522         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3523                                      LR.getValueType(), LL, RL);
3524         AddToWorklist(ORNode.getNode());
3525         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3526       }
3527       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3528       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3529       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3530         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3531                                       LR.getValueType(), LL, RL);
3532         AddToWorklist(ANDNode.getNode());
3533         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3534       }
3535     }
3536     // canonicalize equivalent to ll == rl
3537     if (LL == RR && LR == RL) {
3538       Op1 = ISD::getSetCCSwappedOperands(Op1);
3539       std::swap(RL, RR);
3540     }
3541     if (LL == RL && LR == RR) {
3542       bool isInteger = LL.getValueType().isInteger();
3543       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3544       if (Result != ISD::SETCC_INVALID &&
3545           (!LegalOperations ||
3546            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3547             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3548         EVT CCVT = getSetCCResultType(LL.getValueType());
3549         if (N0.getValueType() == CCVT ||
3550             (!LegalOperations && N0.getValueType() == MVT::i1))
3551           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3552                               LL, LR, Result);
3553       }
3554     }
3555   }
3556
3557   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3558   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3559       // Don't increase # computations.
3560       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3561     // We can only do this xform if we know that bits from X that are set in C2
3562     // but not in C1 are already zero.  Likewise for Y.
3563     if (const ConstantSDNode *N0O1C =
3564         getAsNonOpaqueConstant(N0.getOperand(1))) {
3565       if (const ConstantSDNode *N1O1C =
3566           getAsNonOpaqueConstant(N1.getOperand(1))) {
3567         // We can only do this xform if we know that bits from X that are set in
3568         // C2 but not in C1 are already zero.  Likewise for Y.
3569         const APInt &LHSMask = N0O1C->getAPIntValue();
3570         const APInt &RHSMask = N1O1C->getAPIntValue();
3571
3572         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3573             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3574           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3575                                   N0.getOperand(0), N1.getOperand(0));
3576           SDLoc DL(LocReference);
3577           return DAG.getNode(ISD::AND, DL, VT, X,
3578                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3579         }
3580       }
3581     }
3582   }
3583
3584   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3585   if (N0.getOpcode() == ISD::AND &&
3586       N1.getOpcode() == ISD::AND &&
3587       N0.getOperand(0) == N1.getOperand(0) &&
3588       // Don't increase # computations.
3589       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3590     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3591                             N0.getOperand(1), N1.getOperand(1));
3592     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3593   }
3594
3595   return SDValue();
3596 }
3597
3598 SDValue DAGCombiner::visitOR(SDNode *N) {
3599   SDValue N0 = N->getOperand(0);
3600   SDValue N1 = N->getOperand(1);
3601   EVT VT = N1.getValueType();
3602
3603   // fold vector ops
3604   if (VT.isVector()) {
3605     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3606       return FoldedVOp;
3607
3608     // fold (or x, 0) -> x, vector edition
3609     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3610       return N1;
3611     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3612       return N0;
3613
3614     // fold (or x, -1) -> -1, vector edition
3615     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3616       // do not return N0, because undef node may exist in N0
3617       return DAG.getConstant(
3618           APInt::getAllOnesValue(
3619               N0.getValueType().getScalarType().getSizeInBits()),
3620           SDLoc(N), N0.getValueType());
3621     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3622       // do not return N1, because undef node may exist in N1
3623       return DAG.getConstant(
3624           APInt::getAllOnesValue(
3625               N1.getValueType().getScalarType().getSizeInBits()),
3626           SDLoc(N), N1.getValueType());
3627
3628     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3629     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3630     // Do this only if the resulting shuffle is legal.
3631     if (isa<ShuffleVectorSDNode>(N0) &&
3632         isa<ShuffleVectorSDNode>(N1) &&
3633         // Avoid folding a node with illegal type.
3634         TLI.isTypeLegal(VT) &&
3635         N0->getOperand(1) == N1->getOperand(1) &&
3636         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3637       bool CanFold = true;
3638       unsigned NumElts = VT.getVectorNumElements();
3639       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3640       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3641       // We construct two shuffle masks:
3642       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3643       // and N1 as the second operand.
3644       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3645       // and N0 as the second operand.
3646       // We do this because OR is commutable and therefore there might be
3647       // two ways to fold this node into a shuffle.
3648       SmallVector<int,4> Mask1;
3649       SmallVector<int,4> Mask2;
3650
3651       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3652         int M0 = SV0->getMaskElt(i);
3653         int M1 = SV1->getMaskElt(i);
3654
3655         // Both shuffle indexes are undef. Propagate Undef.
3656         if (M0 < 0 && M1 < 0) {
3657           Mask1.push_back(M0);
3658           Mask2.push_back(M0);
3659           continue;
3660         }
3661
3662         if (M0 < 0 || M1 < 0 ||
3663             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3664             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3665           CanFold = false;
3666           break;
3667         }
3668
3669         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3670         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3671       }
3672
3673       if (CanFold) {
3674         // Fold this sequence only if the resulting shuffle is 'legal'.
3675         if (TLI.isShuffleMaskLegal(Mask1, VT))
3676           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3677                                       N1->getOperand(0), &Mask1[0]);
3678         if (TLI.isShuffleMaskLegal(Mask2, VT))
3679           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3680                                       N0->getOperand(0), &Mask2[0]);
3681       }
3682     }
3683   }
3684
3685   // fold (or c1, c2) -> c1|c2
3686   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3687   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3688   if (N0C && N1C && !N1C->isOpaque())
3689     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3690   // canonicalize constant to RHS
3691   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3692      !isConstantIntBuildVectorOrConstantInt(N1))
3693     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3694   // fold (or x, 0) -> x
3695   if (isNullConstant(N1))
3696     return N0;
3697   // fold (or x, -1) -> -1
3698   if (isAllOnesConstant(N1))
3699     return N1;
3700   // fold (or x, c) -> c iff (x & ~c) == 0
3701   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3702     return N1;
3703
3704   if (SDValue Combined = visitORLike(N0, N1, N))
3705     return Combined;
3706
3707   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3708   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3709     return BSwap;
3710   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3711     return BSwap;
3712
3713   // reassociate or
3714   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3715     return ROR;
3716   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3717   // iff (c1 & c2) == 0.
3718   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3719              isa<ConstantSDNode>(N0.getOperand(1))) {
3720     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3721     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3722       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3723                                                    N1C, C1))
3724         return DAG.getNode(
3725             ISD::AND, SDLoc(N), VT,
3726             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3727       return SDValue();
3728     }
3729   }
3730   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3731   if (N0.getOpcode() == N1.getOpcode())
3732     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3733       return Tmp;
3734
3735   // See if this is some rotate idiom.
3736   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3737     return SDValue(Rot, 0);
3738
3739   // Simplify the operands using demanded-bits information.
3740   if (!VT.isVector() &&
3741       SimplifyDemandedBits(SDValue(N, 0)))
3742     return SDValue(N, 0);
3743
3744   return SDValue();
3745 }
3746
3747 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3748 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3749   if (Op.getOpcode() == ISD::AND) {
3750     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3751       Mask = Op.getOperand(1);
3752       Op = Op.getOperand(0);
3753     } else {
3754       return false;
3755     }
3756   }
3757
3758   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3759     Shift = Op;
3760     return true;
3761   }
3762
3763   return false;
3764 }
3765
3766 // Return true if we can prove that, whenever Neg and Pos are both in the
3767 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3768 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3769 //
3770 //     (or (shift1 X, Neg), (shift2 X, Pos))
3771 //
3772 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3773 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3774 // to consider shift amounts with defined behavior.
3775 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3776   // If OpSize is a power of 2 then:
3777   //
3778   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3779   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3780   //
3781   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3782   // for the stronger condition:
3783   //
3784   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3785   //
3786   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3787   // we can just replace Neg with Neg' for the rest of the function.
3788   //
3789   // In other cases we check for the even stronger condition:
3790   //
3791   //     Neg == OpSize - Pos                                    [B]
3792   //
3793   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3794   // behavior if Pos == 0 (and consequently Neg == OpSize).
3795   //
3796   // We could actually use [A] whenever OpSize is a power of 2, but the
3797   // only extra cases that it would match are those uninteresting ones
3798   // where Neg and Pos are never in range at the same time.  E.g. for
3799   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3800   // as well as (sub 32, Pos), but:
3801   //
3802   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3803   //
3804   // always invokes undefined behavior for 32-bit X.
3805   //
3806   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3807   unsigned MaskLoBits = 0;
3808   if (Neg.getOpcode() == ISD::AND &&
3809       isPowerOf2_64(OpSize) &&
3810       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3811       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3812     Neg = Neg.getOperand(0);
3813     MaskLoBits = Log2_64(OpSize);
3814   }
3815
3816   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3817   if (Neg.getOpcode() != ISD::SUB)
3818     return 0;
3819   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3820   if (!NegC)
3821     return 0;
3822   SDValue NegOp1 = Neg.getOperand(1);
3823
3824   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3825   // Pos'.  The truncation is redundant for the purpose of the equality.
3826   if (MaskLoBits &&
3827       Pos.getOpcode() == ISD::AND &&
3828       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3829       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3830     Pos = Pos.getOperand(0);
3831
3832   // The condition we need is now:
3833   //
3834   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3835   //
3836   // If NegOp1 == Pos then we need:
3837   //
3838   //              OpSize & Mask == NegC & Mask
3839   //
3840   // (because "x & Mask" is a truncation and distributes through subtraction).
3841   APInt Width;
3842   if (Pos == NegOp1)
3843     Width = NegC->getAPIntValue();
3844   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3845   // Then the condition we want to prove becomes:
3846   //
3847   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3848   //
3849   // which, again because "x & Mask" is a truncation, becomes:
3850   //
3851   //                NegC & Mask == (OpSize - PosC) & Mask
3852   //              OpSize & Mask == (NegC + PosC) & Mask
3853   else if (Pos.getOpcode() == ISD::ADD &&
3854            Pos.getOperand(0) == NegOp1 &&
3855            Pos.getOperand(1).getOpcode() == ISD::Constant)
3856     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3857              NegC->getAPIntValue());
3858   else
3859     return false;
3860
3861   // Now we just need to check that OpSize & Mask == Width & Mask.
3862   if (MaskLoBits)
3863     // Opsize & Mask is 0 since Mask is Opsize - 1.
3864     return Width.getLoBits(MaskLoBits) == 0;
3865   return Width == OpSize;
3866 }
3867
3868 // A subroutine of MatchRotate used once we have found an OR of two opposite
3869 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3870 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3871 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3872 // Neg with outer conversions stripped away.
3873 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3874                                        SDValue Neg, SDValue InnerPos,
3875                                        SDValue InnerNeg, unsigned PosOpcode,
3876                                        unsigned NegOpcode, SDLoc DL) {
3877   // fold (or (shl x, (*ext y)),
3878   //          (srl x, (*ext (sub 32, y)))) ->
3879   //   (rotl x, y) or (rotr x, (sub 32, y))
3880   //
3881   // fold (or (shl x, (*ext (sub 32, y))),
3882   //          (srl x, (*ext y))) ->
3883   //   (rotr x, y) or (rotl x, (sub 32, y))
3884   EVT VT = Shifted.getValueType();
3885   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3886     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3887     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3888                        HasPos ? Pos : Neg).getNode();
3889   }
3890
3891   return nullptr;
3892 }
3893
3894 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3895 // idioms for rotate, and if the target supports rotation instructions, generate
3896 // a rot[lr].
3897 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3898   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3899   EVT VT = LHS.getValueType();
3900   if (!TLI.isTypeLegal(VT)) return nullptr;
3901
3902   // The target must have at least one rotate flavor.
3903   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3904   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3905   if (!HasROTL && !HasROTR) return nullptr;
3906
3907   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3908   SDValue LHSShift;   // The shift.
3909   SDValue LHSMask;    // AND value if any.
3910   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3911     return nullptr; // Not part of a rotate.
3912
3913   SDValue RHSShift;   // The shift.
3914   SDValue RHSMask;    // AND value if any.
3915   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3916     return nullptr; // Not part of a rotate.
3917
3918   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3919     return nullptr;   // Not shifting the same value.
3920
3921   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3922     return nullptr;   // Shifts must disagree.
3923
3924   // Canonicalize shl to left side in a shl/srl pair.
3925   if (RHSShift.getOpcode() == ISD::SHL) {
3926     std::swap(LHS, RHS);
3927     std::swap(LHSShift, RHSShift);
3928     std::swap(LHSMask , RHSMask );
3929   }
3930
3931   unsigned OpSizeInBits = VT.getSizeInBits();
3932   SDValue LHSShiftArg = LHSShift.getOperand(0);
3933   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3934   SDValue RHSShiftArg = RHSShift.getOperand(0);
3935   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3936
3937   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3938   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3939   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3940       RHSShiftAmt.getOpcode() == ISD::Constant) {
3941     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3942     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3943     if ((LShVal + RShVal) != OpSizeInBits)
3944       return nullptr;
3945
3946     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3947                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3948
3949     // If there is an AND of either shifted operand, apply it to the result.
3950     if (LHSMask.getNode() || RHSMask.getNode()) {
3951       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3952
3953       if (LHSMask.getNode()) {
3954         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3955         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3956       }
3957       if (RHSMask.getNode()) {
3958         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3959         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3960       }
3961
3962       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3963     }
3964
3965     return Rot.getNode();
3966   }
3967
3968   // If there is a mask here, and we have a variable shift, we can't be sure
3969   // that we're masking out the right stuff.
3970   if (LHSMask.getNode() || RHSMask.getNode())
3971     return nullptr;
3972
3973   // If the shift amount is sign/zext/any-extended just peel it off.
3974   SDValue LExtOp0 = LHSShiftAmt;
3975   SDValue RExtOp0 = RHSShiftAmt;
3976   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3977        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3978        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3979        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3980       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3981        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3982        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3983        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3984     LExtOp0 = LHSShiftAmt.getOperand(0);
3985     RExtOp0 = RHSShiftAmt.getOperand(0);
3986   }
3987
3988   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3989                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3990   if (TryL)
3991     return TryL;
3992
3993   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3994                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3995   if (TryR)
3996     return TryR;
3997
3998   return nullptr;
3999 }
4000
4001 SDValue DAGCombiner::visitXOR(SDNode *N) {
4002   SDValue N0 = N->getOperand(0);
4003   SDValue N1 = N->getOperand(1);
4004   EVT VT = N0.getValueType();
4005
4006   // fold vector ops
4007   if (VT.isVector()) {
4008     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4009       return FoldedVOp;
4010
4011     // fold (xor x, 0) -> x, vector edition
4012     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4013       return N1;
4014     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4015       return N0;
4016   }
4017
4018   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4019   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4020     return DAG.getConstant(0, SDLoc(N), VT);
4021   // fold (xor x, undef) -> undef
4022   if (N0.getOpcode() == ISD::UNDEF)
4023     return N0;
4024   if (N1.getOpcode() == ISD::UNDEF)
4025     return N1;
4026   // fold (xor c1, c2) -> c1^c2
4027   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4028   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4029   if (N0C && N1C)
4030     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4031   // canonicalize constant to RHS
4032   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4033      !isConstantIntBuildVectorOrConstantInt(N1))
4034     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4035   // fold (xor x, 0) -> x
4036   if (isNullConstant(N1))
4037     return N0;
4038   // reassociate xor
4039   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4040     return RXOR;
4041
4042   // fold !(x cc y) -> (x !cc y)
4043   SDValue LHS, RHS, CC;
4044   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4045     bool isInt = LHS.getValueType().isInteger();
4046     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4047                                                isInt);
4048
4049     if (!LegalOperations ||
4050         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4051       switch (N0.getOpcode()) {
4052       default:
4053         llvm_unreachable("Unhandled SetCC Equivalent!");
4054       case ISD::SETCC:
4055         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4056       case ISD::SELECT_CC:
4057         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4058                                N0.getOperand(3), NotCC);
4059       }
4060     }
4061   }
4062
4063   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4064   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4065       N0.getNode()->hasOneUse() &&
4066       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4067     SDValue V = N0.getOperand(0);
4068     SDLoc DL(N0);
4069     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4070                     DAG.getConstant(1, DL, V.getValueType()));
4071     AddToWorklist(V.getNode());
4072     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4073   }
4074
4075   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4076   if (isOneConstant(N1) && VT == MVT::i1 &&
4077       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4078     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4079     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4080       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4081       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4082       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4083       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4084       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4085     }
4086   }
4087   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4088   if (isAllOnesConstant(N1) &&
4089       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4090     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4091     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4092       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4093       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4094       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4095       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4096       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4097     }
4098   }
4099   // fold (xor (and x, y), y) -> (and (not x), y)
4100   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4101       N0->getOperand(1) == N1) {
4102     SDValue X = N0->getOperand(0);
4103     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4104     AddToWorklist(NotX.getNode());
4105     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4106   }
4107   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4108   if (N1C && N0.getOpcode() == ISD::XOR) {
4109     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4110       SDLoc DL(N);
4111       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4112                          DAG.getConstant(N1C->getAPIntValue() ^
4113                                          N00C->getAPIntValue(), DL, VT));
4114     }
4115     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4116       SDLoc DL(N);
4117       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4118                          DAG.getConstant(N1C->getAPIntValue() ^
4119                                          N01C->getAPIntValue(), DL, VT));
4120     }
4121   }
4122   // fold (xor x, x) -> 0
4123   if (N0 == N1)
4124     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4125
4126   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4127   // Here is a concrete example of this equivalence:
4128   // i16   x ==  14
4129   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4130   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4131   //
4132   // =>
4133   //
4134   // i16     ~1      == 0b1111111111111110
4135   // i16 rol(~1, 14) == 0b1011111111111111
4136   //
4137   // Some additional tips to help conceptualize this transform:
4138   // - Try to see the operation as placing a single zero in a value of all ones.
4139   // - There exists no value for x which would allow the result to contain zero.
4140   // - Values of x larger than the bitwidth are undefined and do not require a
4141   //   consistent result.
4142   // - Pushing the zero left requires shifting one bits in from the right.
4143   // A rotate left of ~1 is a nice way of achieving the desired result.
4144   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4145       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4146     SDLoc DL(N);
4147     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4148                        N0.getOperand(1));
4149   }
4150
4151   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4152   if (N0.getOpcode() == N1.getOpcode())
4153     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4154       return Tmp;
4155
4156   // Simplify the expression using non-local knowledge.
4157   if (!VT.isVector() &&
4158       SimplifyDemandedBits(SDValue(N, 0)))
4159     return SDValue(N, 0);
4160
4161   return SDValue();
4162 }
4163
4164 /// Handle transforms common to the three shifts, when the shift amount is a
4165 /// constant.
4166 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4167   SDNode *LHS = N->getOperand(0).getNode();
4168   if (!LHS->hasOneUse()) return SDValue();
4169
4170   // We want to pull some binops through shifts, so that we have (and (shift))
4171   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4172   // thing happens with address calculations, so it's important to canonicalize
4173   // it.
4174   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4175
4176   switch (LHS->getOpcode()) {
4177   default: return SDValue();
4178   case ISD::OR:
4179   case ISD::XOR:
4180     HighBitSet = false; // We can only transform sra if the high bit is clear.
4181     break;
4182   case ISD::AND:
4183     HighBitSet = true;  // We can only transform sra if the high bit is set.
4184     break;
4185   case ISD::ADD:
4186     if (N->getOpcode() != ISD::SHL)
4187       return SDValue(); // only shl(add) not sr[al](add).
4188     HighBitSet = false; // We can only transform sra if the high bit is clear.
4189     break;
4190   }
4191
4192   // We require the RHS of the binop to be a constant and not opaque as well.
4193   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4194   if (!BinOpCst) return SDValue();
4195
4196   // FIXME: disable this unless the input to the binop is a shift by a constant.
4197   // If it is not a shift, it pessimizes some common cases like:
4198   //
4199   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4200   //    int bar(int *X, int i) { return X[i & 255]; }
4201   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4202   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4203        BinOpLHSVal->getOpcode() != ISD::SRA &&
4204        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4205       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4206     return SDValue();
4207
4208   EVT VT = N->getValueType(0);
4209
4210   // If this is a signed shift right, and the high bit is modified by the
4211   // logical operation, do not perform the transformation. The highBitSet
4212   // boolean indicates the value of the high bit of the constant which would
4213   // cause it to be modified for this operation.
4214   if (N->getOpcode() == ISD::SRA) {
4215     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4216     if (BinOpRHSSignSet != HighBitSet)
4217       return SDValue();
4218   }
4219
4220   if (!TLI.isDesirableToCommuteWithShift(LHS))
4221     return SDValue();
4222
4223   // Fold the constants, shifting the binop RHS by the shift amount.
4224   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4225                                N->getValueType(0),
4226                                LHS->getOperand(1), N->getOperand(1));
4227   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4228
4229   // Create the new shift.
4230   SDValue NewShift = DAG.getNode(N->getOpcode(),
4231                                  SDLoc(LHS->getOperand(0)),
4232                                  VT, LHS->getOperand(0), N->getOperand(1));
4233
4234   // Create the new binop.
4235   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4236 }
4237
4238 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4239   assert(N->getOpcode() == ISD::TRUNCATE);
4240   assert(N->getOperand(0).getOpcode() == ISD::AND);
4241
4242   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4243   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4244     SDValue N01 = N->getOperand(0).getOperand(1);
4245
4246     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4247       if (!N01C->isOpaque()) {
4248         EVT TruncVT = N->getValueType(0);
4249         SDValue N00 = N->getOperand(0).getOperand(0);
4250         APInt TruncC = N01C->getAPIntValue();
4251         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4252         SDLoc DL(N);
4253
4254         return DAG.getNode(ISD::AND, DL, TruncVT,
4255                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4256                            DAG.getConstant(TruncC, DL, TruncVT));
4257       }
4258     }
4259   }
4260
4261   return SDValue();
4262 }
4263
4264 SDValue DAGCombiner::visitRotate(SDNode *N) {
4265   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4266   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4267       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4268     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4269     if (NewOp1.getNode())
4270       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4271                          N->getOperand(0), NewOp1);
4272   }
4273   return SDValue();
4274 }
4275
4276 SDValue DAGCombiner::visitSHL(SDNode *N) {
4277   SDValue N0 = N->getOperand(0);
4278   SDValue N1 = N->getOperand(1);
4279   EVT VT = N0.getValueType();
4280   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4281
4282   // fold vector ops
4283   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4284   if (VT.isVector()) {
4285     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4286       return FoldedVOp;
4287
4288     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4289     // If setcc produces all-one true value then:
4290     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4291     if (N1CV && N1CV->isConstant()) {
4292       if (N0.getOpcode() == ISD::AND) {
4293         SDValue N00 = N0->getOperand(0);
4294         SDValue N01 = N0->getOperand(1);
4295         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4296
4297         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4298             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4299                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4300           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4301                                                      N01CV, N1CV))
4302             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4303         }
4304       } else {
4305         N1C = isConstOrConstSplat(N1);
4306       }
4307     }
4308   }
4309
4310   // fold (shl c1, c2) -> c1<<c2
4311   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4312   if (N0C && N1C && !N1C->isOpaque())
4313     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4314   // fold (shl 0, x) -> 0
4315   if (isNullConstant(N0))
4316     return N0;
4317   // fold (shl x, c >= size(x)) -> undef
4318   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4319     return DAG.getUNDEF(VT);
4320   // fold (shl x, 0) -> x
4321   if (N1C && N1C->isNullValue())
4322     return N0;
4323   // fold (shl undef, x) -> 0
4324   if (N0.getOpcode() == ISD::UNDEF)
4325     return DAG.getConstant(0, SDLoc(N), VT);
4326   // if (shl x, c) is known to be zero, return 0
4327   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4328                             APInt::getAllOnesValue(OpSizeInBits)))
4329     return DAG.getConstant(0, SDLoc(N), VT);
4330   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4331   if (N1.getOpcode() == ISD::TRUNCATE &&
4332       N1.getOperand(0).getOpcode() == ISD::AND) {
4333     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4334     if (NewOp1.getNode())
4335       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4336   }
4337
4338   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4339     return SDValue(N, 0);
4340
4341   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4342   if (N1C && N0.getOpcode() == ISD::SHL) {
4343     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4344       uint64_t c1 = N0C1->getZExtValue();
4345       uint64_t c2 = N1C->getZExtValue();
4346       SDLoc DL(N);
4347       if (c1 + c2 >= OpSizeInBits)
4348         return DAG.getConstant(0, DL, VT);
4349       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4350                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4351     }
4352   }
4353
4354   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4355   // For this to be valid, the second form must not preserve any of the bits
4356   // that are shifted out by the inner shift in the first form.  This means
4357   // the outer shift size must be >= the number of bits added by the ext.
4358   // As a corollary, we don't care what kind of ext it is.
4359   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4360               N0.getOpcode() == ISD::ANY_EXTEND ||
4361               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4362       N0.getOperand(0).getOpcode() == ISD::SHL) {
4363     SDValue N0Op0 = N0.getOperand(0);
4364     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4365       uint64_t c1 = N0Op0C1->getZExtValue();
4366       uint64_t c2 = N1C->getZExtValue();
4367       EVT InnerShiftVT = N0Op0.getValueType();
4368       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4369       if (c2 >= OpSizeInBits - InnerShiftSize) {
4370         SDLoc DL(N0);
4371         if (c1 + c2 >= OpSizeInBits)
4372           return DAG.getConstant(0, DL, VT);
4373         return DAG.getNode(ISD::SHL, DL, VT,
4374                            DAG.getNode(N0.getOpcode(), DL, VT,
4375                                        N0Op0->getOperand(0)),
4376                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4377       }
4378     }
4379   }
4380
4381   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4382   // Only fold this if the inner zext has no other uses to avoid increasing
4383   // the total number of instructions.
4384   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4385       N0.getOperand(0).getOpcode() == ISD::SRL) {
4386     SDValue N0Op0 = N0.getOperand(0);
4387     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4388       uint64_t c1 = N0Op0C1->getZExtValue();
4389       if (c1 < VT.getScalarSizeInBits()) {
4390         uint64_t c2 = N1C->getZExtValue();
4391         if (c1 == c2) {
4392           SDValue NewOp0 = N0.getOperand(0);
4393           EVT CountVT = NewOp0.getOperand(1).getValueType();
4394           SDLoc DL(N);
4395           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4396                                        NewOp0,
4397                                        DAG.getConstant(c2, DL, CountVT));
4398           AddToWorklist(NewSHL.getNode());
4399           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4400         }
4401       }
4402     }
4403   }
4404
4405   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4406   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4407   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4408       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4409     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4410       uint64_t C1 = N0C1->getZExtValue();
4411       uint64_t C2 = N1C->getZExtValue();
4412       SDLoc DL(N);
4413       if (C1 <= C2)
4414         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4415                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4416       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4417                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4418     }
4419   }
4420
4421   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4422   //                               (and (srl x, (sub c1, c2), MASK)
4423   // Only fold this if the inner shift has no other uses -- if it does, folding
4424   // this will increase the total number of instructions.
4425   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4426     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4427       uint64_t c1 = N0C1->getZExtValue();
4428       if (c1 < OpSizeInBits) {
4429         uint64_t c2 = N1C->getZExtValue();
4430         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4431         SDValue Shift;
4432         if (c2 > c1) {
4433           Mask = Mask.shl(c2 - c1);
4434           SDLoc DL(N);
4435           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4436                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4437         } else {
4438           Mask = Mask.lshr(c1 - c2);
4439           SDLoc DL(N);
4440           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4441                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4442         }
4443         SDLoc DL(N0);
4444         return DAG.getNode(ISD::AND, DL, VT, Shift,
4445                            DAG.getConstant(Mask, DL, VT));
4446       }
4447     }
4448   }
4449   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4450   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4451     unsigned BitSize = VT.getScalarSizeInBits();
4452     SDLoc DL(N);
4453     SDValue HiBitsMask =
4454       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4455                                             BitSize - N1C->getZExtValue()),
4456                       DL, VT);
4457     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4458                        HiBitsMask);
4459   }
4460
4461   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4462   // Variant of version done on multiply, except mul by a power of 2 is turned
4463   // into a shift.
4464   APInt Val;
4465   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4466       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4467        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4468     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4469     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4470     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4471   }
4472
4473   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4474   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4475     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4476       if (SDValue Folded =
4477               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4478         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4479     }
4480   }
4481
4482   if (N1C && !N1C->isOpaque())
4483     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4484       return NewSHL;
4485
4486   return SDValue();
4487 }
4488
4489 SDValue DAGCombiner::visitSRA(SDNode *N) {
4490   SDValue N0 = N->getOperand(0);
4491   SDValue N1 = N->getOperand(1);
4492   EVT VT = N0.getValueType();
4493   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4494
4495   // fold vector ops
4496   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4497   if (VT.isVector()) {
4498     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4499       return FoldedVOp;
4500
4501     N1C = isConstOrConstSplat(N1);
4502   }
4503
4504   // fold (sra c1, c2) -> (sra c1, c2)
4505   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4506   if (N0C && N1C && !N1C->isOpaque())
4507     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4508   // fold (sra 0, x) -> 0
4509   if (isNullConstant(N0))
4510     return N0;
4511   // fold (sra -1, x) -> -1
4512   if (isAllOnesConstant(N0))
4513     return N0;
4514   // fold (sra x, (setge c, size(x))) -> undef
4515   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4516     return DAG.getUNDEF(VT);
4517   // fold (sra x, 0) -> x
4518   if (N1C && N1C->isNullValue())
4519     return N0;
4520   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4521   // sext_inreg.
4522   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4523     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4524     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4525     if (VT.isVector())
4526       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4527                                ExtVT, VT.getVectorNumElements());
4528     if ((!LegalOperations ||
4529          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4530       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4531                          N0.getOperand(0), DAG.getValueType(ExtVT));
4532   }
4533
4534   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4535   if (N1C && N0.getOpcode() == ISD::SRA) {
4536     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4537       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4538       if (Sum >= OpSizeInBits)
4539         Sum = OpSizeInBits - 1;
4540       SDLoc DL(N);
4541       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4542                          DAG.getConstant(Sum, DL, N1.getValueType()));
4543     }
4544   }
4545
4546   // fold (sra (shl X, m), (sub result_size, n))
4547   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4548   // result_size - n != m.
4549   // If truncate is free for the target sext(shl) is likely to result in better
4550   // code.
4551   if (N0.getOpcode() == ISD::SHL && N1C) {
4552     // Get the two constanst of the shifts, CN0 = m, CN = n.
4553     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4554     if (N01C) {
4555       LLVMContext &Ctx = *DAG.getContext();
4556       // Determine what the truncate's result bitsize and type would be.
4557       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4558
4559       if (VT.isVector())
4560         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4561
4562       // Determine the residual right-shift amount.
4563       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4564
4565       // If the shift is not a no-op (in which case this should be just a sign
4566       // extend already), the truncated to type is legal, sign_extend is legal
4567       // on that type, and the truncate to that type is both legal and free,
4568       // perform the transform.
4569       if ((ShiftAmt > 0) &&
4570           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4571           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4572           TLI.isTruncateFree(VT, TruncVT)) {
4573
4574         SDLoc DL(N);
4575         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4576             getShiftAmountTy(N0.getOperand(0).getValueType()));
4577         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4578                                     N0.getOperand(0), Amt);
4579         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4580                                     Shift);
4581         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4582                            N->getValueType(0), Trunc);
4583       }
4584     }
4585   }
4586
4587   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4588   if (N1.getOpcode() == ISD::TRUNCATE &&
4589       N1.getOperand(0).getOpcode() == ISD::AND) {
4590     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4591     if (NewOp1.getNode())
4592       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4593   }
4594
4595   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4596   //      if c1 is equal to the number of bits the trunc removes
4597   if (N0.getOpcode() == ISD::TRUNCATE &&
4598       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4599        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4600       N0.getOperand(0).hasOneUse() &&
4601       N0.getOperand(0).getOperand(1).hasOneUse() &&
4602       N1C) {
4603     SDValue N0Op0 = N0.getOperand(0);
4604     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4605       unsigned LargeShiftVal = LargeShift->getZExtValue();
4606       EVT LargeVT = N0Op0.getValueType();
4607
4608       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4609         SDLoc DL(N);
4610         SDValue Amt =
4611           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4612                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4613         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4614                                   N0Op0.getOperand(0), Amt);
4615         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4616       }
4617     }
4618   }
4619
4620   // Simplify, based on bits shifted out of the LHS.
4621   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4622     return SDValue(N, 0);
4623
4624
4625   // If the sign bit is known to be zero, switch this to a SRL.
4626   if (DAG.SignBitIsZero(N0))
4627     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4628
4629   if (N1C && !N1C->isOpaque())
4630     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4631       return NewSRA;
4632
4633   return SDValue();
4634 }
4635
4636 SDValue DAGCombiner::visitSRL(SDNode *N) {
4637   SDValue N0 = N->getOperand(0);
4638   SDValue N1 = N->getOperand(1);
4639   EVT VT = N0.getValueType();
4640   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4641
4642   // fold vector ops
4643   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4644   if (VT.isVector()) {
4645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4646       return FoldedVOp;
4647
4648     N1C = isConstOrConstSplat(N1);
4649   }
4650
4651   // fold (srl c1, c2) -> c1 >>u c2
4652   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4653   if (N0C && N1C && !N1C->isOpaque())
4654     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4655   // fold (srl 0, x) -> 0
4656   if (isNullConstant(N0))
4657     return N0;
4658   // fold (srl x, c >= size(x)) -> undef
4659   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4660     return DAG.getUNDEF(VT);
4661   // fold (srl x, 0) -> x
4662   if (N1C && N1C->isNullValue())
4663     return N0;
4664   // if (srl x, c) is known to be zero, return 0
4665   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4666                                    APInt::getAllOnesValue(OpSizeInBits)))
4667     return DAG.getConstant(0, SDLoc(N), VT);
4668
4669   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4670   if (N1C && N0.getOpcode() == ISD::SRL) {
4671     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4672       uint64_t c1 = N01C->getZExtValue();
4673       uint64_t c2 = N1C->getZExtValue();
4674       SDLoc DL(N);
4675       if (c1 + c2 >= OpSizeInBits)
4676         return DAG.getConstant(0, DL, VT);
4677       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4678                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4679     }
4680   }
4681
4682   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4683   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4684       N0.getOperand(0).getOpcode() == ISD::SRL &&
4685       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4686     uint64_t c1 =
4687       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4688     uint64_t c2 = N1C->getZExtValue();
4689     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4690     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4691     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4692     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4693     if (c1 + OpSizeInBits == InnerShiftSize) {
4694       SDLoc DL(N0);
4695       if (c1 + c2 >= InnerShiftSize)
4696         return DAG.getConstant(0, DL, VT);
4697       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4698                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4699                                      N0.getOperand(0)->getOperand(0),
4700                                      DAG.getConstant(c1 + c2, DL,
4701                                                      ShiftCountVT)));
4702     }
4703   }
4704
4705   // fold (srl (shl x, c), c) -> (and x, cst2)
4706   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4707     unsigned BitSize = N0.getScalarValueSizeInBits();
4708     if (BitSize <= 64) {
4709       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4710       SDLoc DL(N);
4711       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4712                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4713     }
4714   }
4715
4716   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4717   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4718     // Shifting in all undef bits?
4719     EVT SmallVT = N0.getOperand(0).getValueType();
4720     unsigned BitSize = SmallVT.getScalarSizeInBits();
4721     if (N1C->getZExtValue() >= BitSize)
4722       return DAG.getUNDEF(VT);
4723
4724     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4725       uint64_t ShiftAmt = N1C->getZExtValue();
4726       SDLoc DL0(N0);
4727       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4728                                        N0.getOperand(0),
4729                           DAG.getConstant(ShiftAmt, DL0,
4730                                           getShiftAmountTy(SmallVT)));
4731       AddToWorklist(SmallShift.getNode());
4732       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4733       SDLoc DL(N);
4734       return DAG.getNode(ISD::AND, DL, VT,
4735                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4736                          DAG.getConstant(Mask, DL, VT));
4737     }
4738   }
4739
4740   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4741   // bit, which is unmodified by sra.
4742   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4743     if (N0.getOpcode() == ISD::SRA)
4744       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4745   }
4746
4747   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4748   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4749       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4750     APInt KnownZero, KnownOne;
4751     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4752
4753     // If any of the input bits are KnownOne, then the input couldn't be all
4754     // zeros, thus the result of the srl will always be zero.
4755     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4756
4757     // If all of the bits input the to ctlz node are known to be zero, then
4758     // the result of the ctlz is "32" and the result of the shift is one.
4759     APInt UnknownBits = ~KnownZero;
4760     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4761
4762     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4763     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4764       // Okay, we know that only that the single bit specified by UnknownBits
4765       // could be set on input to the CTLZ node. If this bit is set, the SRL
4766       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4767       // to an SRL/XOR pair, which is likely to simplify more.
4768       unsigned ShAmt = UnknownBits.countTrailingZeros();
4769       SDValue Op = N0.getOperand(0);
4770
4771       if (ShAmt) {
4772         SDLoc DL(N0);
4773         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4774                   DAG.getConstant(ShAmt, DL,
4775                                   getShiftAmountTy(Op.getValueType())));
4776         AddToWorklist(Op.getNode());
4777       }
4778
4779       SDLoc DL(N);
4780       return DAG.getNode(ISD::XOR, DL, VT,
4781                          Op, DAG.getConstant(1, DL, VT));
4782     }
4783   }
4784
4785   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4786   if (N1.getOpcode() == ISD::TRUNCATE &&
4787       N1.getOperand(0).getOpcode() == ISD::AND) {
4788     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4789       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4790   }
4791
4792   // fold operands of srl based on knowledge that the low bits are not
4793   // demanded.
4794   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4795     return SDValue(N, 0);
4796
4797   if (N1C && !N1C->isOpaque())
4798     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4799       return NewSRL;
4800
4801   // Attempt to convert a srl of a load into a narrower zero-extending load.
4802   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4803     return NarrowLoad;
4804
4805   // Here is a common situation. We want to optimize:
4806   //
4807   //   %a = ...
4808   //   %b = and i32 %a, 2
4809   //   %c = srl i32 %b, 1
4810   //   brcond i32 %c ...
4811   //
4812   // into
4813   //
4814   //   %a = ...
4815   //   %b = and %a, 2
4816   //   %c = setcc eq %b, 0
4817   //   brcond %c ...
4818   //
4819   // However when after the source operand of SRL is optimized into AND, the SRL
4820   // itself may not be optimized further. Look for it and add the BRCOND into
4821   // the worklist.
4822   if (N->hasOneUse()) {
4823     SDNode *Use = *N->use_begin();
4824     if (Use->getOpcode() == ISD::BRCOND)
4825       AddToWorklist(Use);
4826     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4827       // Also look pass the truncate.
4828       Use = *Use->use_begin();
4829       if (Use->getOpcode() == ISD::BRCOND)
4830         AddToWorklist(Use);
4831     }
4832   }
4833
4834   return SDValue();
4835 }
4836
4837 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4838   SDValue N0 = N->getOperand(0);
4839   EVT VT = N->getValueType(0);
4840
4841   // fold (bswap c1) -> c2
4842   if (isConstantIntBuildVectorOrConstantInt(N0))
4843     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4844   // fold (bswap (bswap x)) -> x
4845   if (N0.getOpcode() == ISD::BSWAP)
4846     return N0->getOperand(0);
4847   return SDValue();
4848 }
4849
4850 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4851   SDValue N0 = N->getOperand(0);
4852   EVT VT = N->getValueType(0);
4853
4854   // fold (ctlz c1) -> c2
4855   if (isConstantIntBuildVectorOrConstantInt(N0))
4856     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4857   return SDValue();
4858 }
4859
4860 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4861   SDValue N0 = N->getOperand(0);
4862   EVT VT = N->getValueType(0);
4863
4864   // fold (ctlz_zero_undef c1) -> c2
4865   if (isConstantIntBuildVectorOrConstantInt(N0))
4866     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4867   return SDValue();
4868 }
4869
4870 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4871   SDValue N0 = N->getOperand(0);
4872   EVT VT = N->getValueType(0);
4873
4874   // fold (cttz c1) -> c2
4875   if (isConstantIntBuildVectorOrConstantInt(N0))
4876     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4877   return SDValue();
4878 }
4879
4880 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4881   SDValue N0 = N->getOperand(0);
4882   EVT VT = N->getValueType(0);
4883
4884   // fold (cttz_zero_undef c1) -> c2
4885   if (isConstantIntBuildVectorOrConstantInt(N0))
4886     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4887   return SDValue();
4888 }
4889
4890 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4891   SDValue N0 = N->getOperand(0);
4892   EVT VT = N->getValueType(0);
4893
4894   // fold (ctpop c1) -> c2
4895   if (isConstantIntBuildVectorOrConstantInt(N0))
4896     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4897   return SDValue();
4898 }
4899
4900
4901 /// \brief Generate Min/Max node
4902 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4903                                    SDValue True, SDValue False,
4904                                    ISD::CondCode CC, const TargetLowering &TLI,
4905                                    SelectionDAG &DAG) {
4906   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4907     return SDValue();
4908
4909   switch (CC) {
4910   case ISD::SETOLT:
4911   case ISD::SETOLE:
4912   case ISD::SETLT:
4913   case ISD::SETLE:
4914   case ISD::SETULT:
4915   case ISD::SETULE: {
4916     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4917     if (TLI.isOperationLegal(Opcode, VT))
4918       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4919     return SDValue();
4920   }
4921   case ISD::SETOGT:
4922   case ISD::SETOGE:
4923   case ISD::SETGT:
4924   case ISD::SETGE:
4925   case ISD::SETUGT:
4926   case ISD::SETUGE: {
4927     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4928     if (TLI.isOperationLegal(Opcode, VT))
4929       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4930     return SDValue();
4931   }
4932   default:
4933     return SDValue();
4934   }
4935 }
4936
4937 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4938   SDValue N0 = N->getOperand(0);
4939   SDValue N1 = N->getOperand(1);
4940   SDValue N2 = N->getOperand(2);
4941   EVT VT = N->getValueType(0);
4942   EVT VT0 = N0.getValueType();
4943
4944   // fold (select C, X, X) -> X
4945   if (N1 == N2)
4946     return N1;
4947   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4948     // fold (select true, X, Y) -> X
4949     // fold (select false, X, Y) -> Y
4950     return !N0C->isNullValue() ? N1 : N2;
4951   }
4952   // fold (select C, 1, X) -> (or C, X)
4953   if (VT == MVT::i1 && isOneConstant(N1))
4954     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4955   // fold (select C, 0, 1) -> (xor C, 1)
4956   // We can't do this reliably if integer based booleans have different contents
4957   // to floating point based booleans. This is because we can't tell whether we
4958   // have an integer-based boolean or a floating-point-based boolean unless we
4959   // can find the SETCC that produced it and inspect its operands. This is
4960   // fairly easy if C is the SETCC node, but it can potentially be
4961   // undiscoverable (or not reasonably discoverable). For example, it could be
4962   // in another basic block or it could require searching a complicated
4963   // expression.
4964   if (VT.isInteger() &&
4965       (VT0 == MVT::i1 || (VT0.isInteger() &&
4966                           TLI.getBooleanContents(false, false) ==
4967                               TLI.getBooleanContents(false, true) &&
4968                           TLI.getBooleanContents(false, false) ==
4969                               TargetLowering::ZeroOrOneBooleanContent)) &&
4970       isNullConstant(N1) && isOneConstant(N2)) {
4971     SDValue XORNode;
4972     if (VT == VT0) {
4973       SDLoc DL(N);
4974       return DAG.getNode(ISD::XOR, DL, VT0,
4975                          N0, DAG.getConstant(1, DL, VT0));
4976     }
4977     SDLoc DL0(N0);
4978     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4979                           N0, DAG.getConstant(1, DL0, VT0));
4980     AddToWorklist(XORNode.getNode());
4981     if (VT.bitsGT(VT0))
4982       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4983     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4984   }
4985   // fold (select C, 0, X) -> (and (not C), X)
4986   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4987     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4988     AddToWorklist(NOTNode.getNode());
4989     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4990   }
4991   // fold (select C, X, 1) -> (or (not C), X)
4992   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4993     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4994     AddToWorklist(NOTNode.getNode());
4995     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4996   }
4997   // fold (select C, X, 0) -> (and C, X)
4998   if (VT == MVT::i1 && isNullConstant(N2))
4999     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5000   // fold (select X, X, Y) -> (or X, Y)
5001   // fold (select X, 1, Y) -> (or X, Y)
5002   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5003     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5004   // fold (select X, Y, X) -> (and X, Y)
5005   // fold (select X, Y, 0) -> (and X, Y)
5006   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5007     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5008
5009   // If we can fold this based on the true/false value, do so.
5010   if (SimplifySelectOps(N, N1, N2))
5011     return SDValue(N, 0);  // Don't revisit N.
5012
5013   if (VT0 == MVT::i1) {
5014     // The code in this block deals with the following 2 equivalences:
5015     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5016     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5017     // The target can specify its prefered form with the
5018     // shouldNormalizeToSelectSequence() callback. However we always transform
5019     // to the right anyway if we find the inner select exists in the DAG anyway
5020     // and we always transform to the left side if we know that we can further
5021     // optimize the combination of the conditions.
5022     bool normalizeToSequence
5023       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5024     // select (and Cond0, Cond1), X, Y
5025     //   -> select Cond0, (select Cond1, X, Y), Y
5026     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5027       SDValue Cond0 = N0->getOperand(0);
5028       SDValue Cond1 = N0->getOperand(1);
5029       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5030                                         N1.getValueType(), Cond1, N1, N2);
5031       if (normalizeToSequence || !InnerSelect.use_empty())
5032         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5033                            InnerSelect, N2);
5034     }
5035     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5036     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5037       SDValue Cond0 = N0->getOperand(0);
5038       SDValue Cond1 = N0->getOperand(1);
5039       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5040                                         N1.getValueType(), Cond1, N1, N2);
5041       if (normalizeToSequence || !InnerSelect.use_empty())
5042         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5043                            InnerSelect);
5044     }
5045
5046     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5047     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5048       SDValue N1_0 = N1->getOperand(0);
5049       SDValue N1_1 = N1->getOperand(1);
5050       SDValue N1_2 = N1->getOperand(2);
5051       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5052         // Create the actual and node if we can generate good code for it.
5053         if (!normalizeToSequence) {
5054           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5055                                     N0, N1_0);
5056           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5057                              N1_1, N2);
5058         }
5059         // Otherwise see if we can optimize the "and" to a better pattern.
5060         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5061           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5062                              N1_1, N2);
5063       }
5064     }
5065     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5066     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5067       SDValue N2_0 = N2->getOperand(0);
5068       SDValue N2_1 = N2->getOperand(1);
5069       SDValue N2_2 = N2->getOperand(2);
5070       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5071         // Create the actual or node if we can generate good code for it.
5072         if (!normalizeToSequence) {
5073           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5074                                    N0, N2_0);
5075           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5076                              N1, N2_2);
5077         }
5078         // Otherwise see if we can optimize to a better pattern.
5079         if (SDValue Combined = visitORLike(N0, N2_0, N))
5080           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5081                              N1, N2_2);
5082       }
5083     }
5084   }
5085
5086   // fold selects based on a setcc into other things, such as min/max/abs
5087   if (N0.getOpcode() == ISD::SETCC) {
5088     // select x, y (fcmp lt x, y) -> fminnum x, y
5089     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5090     //
5091     // This is OK if we don't care about what happens if either operand is a
5092     // NaN.
5093     //
5094
5095     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5096     // no signed zeros as well as no nans.
5097     const TargetOptions &Options = DAG.getTarget().Options;
5098     if (Options.UnsafeFPMath &&
5099         VT.isFloatingPoint() && N0.hasOneUse() &&
5100         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5101       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5102
5103       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5104                                                 N0.getOperand(1), N1, N2, CC,
5105                                                 TLI, DAG))
5106         return FMinMax;
5107     }
5108
5109     if ((!LegalOperations &&
5110          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5111         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5112       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5113                          N0.getOperand(0), N0.getOperand(1),
5114                          N1, N2, N0.getOperand(2));
5115     return SimplifySelect(SDLoc(N), N0, N1, N2);
5116   }
5117
5118   return SDValue();
5119 }
5120
5121 static
5122 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5123   SDLoc DL(N);
5124   EVT LoVT, HiVT;
5125   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5126
5127   // Split the inputs.
5128   SDValue Lo, Hi, LL, LH, RL, RH;
5129   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5130   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5131
5132   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5133   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5134
5135   return std::make_pair(Lo, Hi);
5136 }
5137
5138 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5139 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5140 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5141   SDLoc dl(N);
5142   SDValue Cond = N->getOperand(0);
5143   SDValue LHS = N->getOperand(1);
5144   SDValue RHS = N->getOperand(2);
5145   EVT VT = N->getValueType(0);
5146   int NumElems = VT.getVectorNumElements();
5147   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5148          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5149          Cond.getOpcode() == ISD::BUILD_VECTOR);
5150
5151   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5152   // binary ones here.
5153   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5154     return SDValue();
5155
5156   // We're sure we have an even number of elements due to the
5157   // concat_vectors we have as arguments to vselect.
5158   // Skip BV elements until we find one that's not an UNDEF
5159   // After we find an UNDEF element, keep looping until we get to half the
5160   // length of the BV and see if all the non-undef nodes are the same.
5161   ConstantSDNode *BottomHalf = nullptr;
5162   for (int i = 0; i < NumElems / 2; ++i) {
5163     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5164       continue;
5165
5166     if (BottomHalf == nullptr)
5167       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5168     else if (Cond->getOperand(i).getNode() != BottomHalf)
5169       return SDValue();
5170   }
5171
5172   // Do the same for the second half of the BuildVector
5173   ConstantSDNode *TopHalf = nullptr;
5174   for (int i = NumElems / 2; i < NumElems; ++i) {
5175     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5176       continue;
5177
5178     if (TopHalf == nullptr)
5179       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5180     else if (Cond->getOperand(i).getNode() != TopHalf)
5181       return SDValue();
5182   }
5183
5184   assert(TopHalf && BottomHalf &&
5185          "One half of the selector was all UNDEFs and the other was all the "
5186          "same value. This should have been addressed before this function.");
5187   return DAG.getNode(
5188       ISD::CONCAT_VECTORS, dl, VT,
5189       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5190       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5191 }
5192
5193 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5194
5195   if (Level >= AfterLegalizeTypes)
5196     return SDValue();
5197
5198   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5199   SDValue Mask = MSC->getMask();
5200   SDValue Data  = MSC->getValue();
5201   SDLoc DL(N);
5202
5203   // If the MSCATTER data type requires splitting and the mask is provided by a
5204   // SETCC, then split both nodes and its operands before legalization. This
5205   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5206   // and enables future optimizations (e.g. min/max pattern matching on X86).
5207   if (Mask.getOpcode() != ISD::SETCC)
5208     return SDValue();
5209
5210   // Check if any splitting is required.
5211   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5212       TargetLowering::TypeSplitVector)
5213     return SDValue();
5214   SDValue MaskLo, MaskHi, Lo, Hi;
5215   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5216
5217   EVT LoVT, HiVT;
5218   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5219
5220   SDValue Chain = MSC->getChain();
5221
5222   EVT MemoryVT = MSC->getMemoryVT();
5223   unsigned Alignment = MSC->getOriginalAlignment();
5224
5225   EVT LoMemVT, HiMemVT;
5226   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5227
5228   SDValue DataLo, DataHi;
5229   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5230
5231   SDValue BasePtr = MSC->getBasePtr();
5232   SDValue IndexLo, IndexHi;
5233   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5234
5235   MachineMemOperand *MMO = DAG.getMachineFunction().
5236     getMachineMemOperand(MSC->getPointerInfo(),
5237                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5238                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5239
5240   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5241   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5242                             DL, OpsLo, MMO);
5243
5244   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5245   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5246                             DL, OpsHi, MMO);
5247
5248   AddToWorklist(Lo.getNode());
5249   AddToWorklist(Hi.getNode());
5250
5251   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5252 }
5253
5254 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5255
5256   if (Level >= AfterLegalizeTypes)
5257     return SDValue();
5258
5259   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5260   SDValue Mask = MST->getMask();
5261   SDValue Data  = MST->getValue();
5262   SDLoc DL(N);
5263
5264   // If the MSTORE data type requires splitting and the mask is provided by a
5265   // SETCC, then split both nodes and its operands before legalization. This
5266   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5267   // and enables future optimizations (e.g. min/max pattern matching on X86).
5268   if (Mask.getOpcode() == ISD::SETCC) {
5269
5270     // Check if any splitting is required.
5271     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5272         TargetLowering::TypeSplitVector)
5273       return SDValue();
5274
5275     SDValue MaskLo, MaskHi, Lo, Hi;
5276     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5277
5278     EVT LoVT, HiVT;
5279     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5280
5281     SDValue Chain = MST->getChain();
5282     SDValue Ptr   = MST->getBasePtr();
5283
5284     EVT MemoryVT = MST->getMemoryVT();
5285     unsigned Alignment = MST->getOriginalAlignment();
5286
5287     // if Alignment is equal to the vector size,
5288     // take the half of it for the second part
5289     unsigned SecondHalfAlignment =
5290       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5291          Alignment/2 : Alignment;
5292
5293     EVT LoMemVT, HiMemVT;
5294     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5295
5296     SDValue DataLo, DataHi;
5297     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5298
5299     MachineMemOperand *MMO = DAG.getMachineFunction().
5300       getMachineMemOperand(MST->getPointerInfo(),
5301                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5302                            Alignment, MST->getAAInfo(), MST->getRanges());
5303
5304     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5305                             MST->isTruncatingStore());
5306
5307     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5308     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5309                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5310
5311     MMO = DAG.getMachineFunction().
5312       getMachineMemOperand(MST->getPointerInfo(),
5313                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5314                            SecondHalfAlignment, MST->getAAInfo(),
5315                            MST->getRanges());
5316
5317     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5318                             MST->isTruncatingStore());
5319
5320     AddToWorklist(Lo.getNode());
5321     AddToWorklist(Hi.getNode());
5322
5323     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5324   }
5325   return SDValue();
5326 }
5327
5328 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5329
5330   if (Level >= AfterLegalizeTypes)
5331     return SDValue();
5332
5333   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5334   SDValue Mask = MGT->getMask();
5335   SDLoc DL(N);
5336
5337   // If the MGATHER result requires splitting and the mask is provided by a
5338   // SETCC, then split both nodes and its operands before legalization. This
5339   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5340   // and enables future optimizations (e.g. min/max pattern matching on X86).
5341
5342   if (Mask.getOpcode() != ISD::SETCC)
5343     return SDValue();
5344
5345   EVT VT = N->getValueType(0);
5346
5347   // Check if any splitting is required.
5348   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5349       TargetLowering::TypeSplitVector)
5350     return SDValue();
5351
5352   SDValue MaskLo, MaskHi, Lo, Hi;
5353   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5354
5355   SDValue Src0 = MGT->getValue();
5356   SDValue Src0Lo, Src0Hi;
5357   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5358
5359   EVT LoVT, HiVT;
5360   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5361
5362   SDValue Chain = MGT->getChain();
5363   EVT MemoryVT = MGT->getMemoryVT();
5364   unsigned Alignment = MGT->getOriginalAlignment();
5365
5366   EVT LoMemVT, HiMemVT;
5367   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5368
5369   SDValue BasePtr = MGT->getBasePtr();
5370   SDValue Index = MGT->getIndex();
5371   SDValue IndexLo, IndexHi;
5372   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5373
5374   MachineMemOperand *MMO = DAG.getMachineFunction().
5375     getMachineMemOperand(MGT->getPointerInfo(),
5376                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5377                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5378
5379   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5380   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5381                             MMO);
5382
5383   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5384   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5385                             MMO);
5386
5387   AddToWorklist(Lo.getNode());
5388   AddToWorklist(Hi.getNode());
5389
5390   // Build a factor node to remember that this load is independent of the
5391   // other one.
5392   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5393                       Hi.getValue(1));
5394
5395   // Legalized the chain result - switch anything that used the old chain to
5396   // use the new one.
5397   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5398
5399   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5400
5401   SDValue RetOps[] = { GatherRes, Chain };
5402   return DAG.getMergeValues(RetOps, DL);
5403 }
5404
5405 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5406
5407   if (Level >= AfterLegalizeTypes)
5408     return SDValue();
5409
5410   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5411   SDValue Mask = MLD->getMask();
5412   SDLoc DL(N);
5413
5414   // If the MLOAD result requires splitting and the mask is provided by a
5415   // SETCC, then split both nodes and its operands before legalization. This
5416   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5417   // and enables future optimizations (e.g. min/max pattern matching on X86).
5418
5419   if (Mask.getOpcode() == ISD::SETCC) {
5420     EVT VT = N->getValueType(0);
5421
5422     // Check if any splitting is required.
5423     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5424         TargetLowering::TypeSplitVector)
5425       return SDValue();
5426
5427     SDValue MaskLo, MaskHi, Lo, Hi;
5428     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5429
5430     SDValue Src0 = MLD->getSrc0();
5431     SDValue Src0Lo, Src0Hi;
5432     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5433
5434     EVT LoVT, HiVT;
5435     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5436
5437     SDValue Chain = MLD->getChain();
5438     SDValue Ptr   = MLD->getBasePtr();
5439     EVT MemoryVT = MLD->getMemoryVT();
5440     unsigned Alignment = MLD->getOriginalAlignment();
5441
5442     // if Alignment is equal to the vector size,
5443     // take the half of it for the second part
5444     unsigned SecondHalfAlignment =
5445       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5446          Alignment/2 : Alignment;
5447
5448     EVT LoMemVT, HiMemVT;
5449     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5450
5451     MachineMemOperand *MMO = DAG.getMachineFunction().
5452     getMachineMemOperand(MLD->getPointerInfo(),
5453                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5454                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5455
5456     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5457                            ISD::NON_EXTLOAD);
5458
5459     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5460     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5461                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5462
5463     MMO = DAG.getMachineFunction().
5464     getMachineMemOperand(MLD->getPointerInfo(),
5465                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5466                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5467
5468     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5469                            ISD::NON_EXTLOAD);
5470
5471     AddToWorklist(Lo.getNode());
5472     AddToWorklist(Hi.getNode());
5473
5474     // Build a factor node to remember that this load is independent of the
5475     // other one.
5476     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5477                         Hi.getValue(1));
5478
5479     // Legalized the chain result - switch anything that used the old chain to
5480     // use the new one.
5481     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5482
5483     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5484
5485     SDValue RetOps[] = { LoadRes, Chain };
5486     return DAG.getMergeValues(RetOps, DL);
5487   }
5488   return SDValue();
5489 }
5490
5491 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5492   SDValue N0 = N->getOperand(0);
5493   SDValue N1 = N->getOperand(1);
5494   SDValue N2 = N->getOperand(2);
5495   SDLoc DL(N);
5496
5497   // Canonicalize integer abs.
5498   // vselect (setg[te] X,  0),  X, -X ->
5499   // vselect (setgt    X, -1),  X, -X ->
5500   // vselect (setl[te] X,  0), -X,  X ->
5501   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5502   if (N0.getOpcode() == ISD::SETCC) {
5503     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5504     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5505     bool isAbs = false;
5506     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5507
5508     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5509          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5510         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5511       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5512     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5513              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5514       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5515
5516     if (isAbs) {
5517       EVT VT = LHS.getValueType();
5518       SDValue Shift = DAG.getNode(
5519           ISD::SRA, DL, VT, LHS,
5520           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5521       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5522       AddToWorklist(Shift.getNode());
5523       AddToWorklist(Add.getNode());
5524       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5525     }
5526   }
5527
5528   if (SimplifySelectOps(N, N1, N2))
5529     return SDValue(N, 0);  // Don't revisit N.
5530
5531   // If the VSELECT result requires splitting and the mask is provided by a
5532   // SETCC, then split both nodes and its operands before legalization. This
5533   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5534   // and enables future optimizations (e.g. min/max pattern matching on X86).
5535   if (N0.getOpcode() == ISD::SETCC) {
5536     EVT VT = N->getValueType(0);
5537
5538     // Check if any splitting is required.
5539     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5540         TargetLowering::TypeSplitVector)
5541       return SDValue();
5542
5543     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5544     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5545     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5546     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5547
5548     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5549     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5550
5551     // Add the new VSELECT nodes to the work list in case they need to be split
5552     // again.
5553     AddToWorklist(Lo.getNode());
5554     AddToWorklist(Hi.getNode());
5555
5556     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5557   }
5558
5559   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5560   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5561     return N1;
5562   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5563   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5564     return N2;
5565
5566   // The ConvertSelectToConcatVector function is assuming both the above
5567   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5568   // and addressed.
5569   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5570       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5571       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5572     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5573       return CV;
5574   }
5575
5576   return SDValue();
5577 }
5578
5579 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5580   SDValue N0 = N->getOperand(0);
5581   SDValue N1 = N->getOperand(1);
5582   SDValue N2 = N->getOperand(2);
5583   SDValue N3 = N->getOperand(3);
5584   SDValue N4 = N->getOperand(4);
5585   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5586
5587   // fold select_cc lhs, rhs, x, x, cc -> x
5588   if (N2 == N3)
5589     return N2;
5590
5591   // Determine if the condition we're dealing with is constant
5592   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5593                               N0, N1, CC, SDLoc(N), false);
5594   if (SCC.getNode()) {
5595     AddToWorklist(SCC.getNode());
5596
5597     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5598       if (!SCCC->isNullValue())
5599         return N2;    // cond always true -> true val
5600       else
5601         return N3;    // cond always false -> false val
5602     } else if (SCC->getOpcode() == ISD::UNDEF) {
5603       // When the condition is UNDEF, just return the first operand. This is
5604       // coherent the DAG creation, no setcc node is created in this case
5605       return N2;
5606     } else if (SCC.getOpcode() == ISD::SETCC) {
5607       // Fold to a simpler select_cc
5608       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5609                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5610                          SCC.getOperand(2));
5611     }
5612   }
5613
5614   // If we can fold this based on the true/false value, do so.
5615   if (SimplifySelectOps(N, N2, N3))
5616     return SDValue(N, 0);  // Don't revisit N.
5617
5618   // fold select_cc into other things, such as min/max/abs
5619   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5620 }
5621
5622 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5623   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5624                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5625                        SDLoc(N));
5626 }
5627
5628 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5629 /// a build_vector of constants.
5630 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5631 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5632 /// Vector extends are not folded if operations are legal; this is to
5633 /// avoid introducing illegal build_vector dag nodes.
5634 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5635                                          SelectionDAG &DAG, bool LegalTypes,
5636                                          bool LegalOperations) {
5637   unsigned Opcode = N->getOpcode();
5638   SDValue N0 = N->getOperand(0);
5639   EVT VT = N->getValueType(0);
5640
5641   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5642          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5643          && "Expected EXTEND dag node in input!");
5644
5645   // fold (sext c1) -> c1
5646   // fold (zext c1) -> c1
5647   // fold (aext c1) -> c1
5648   if (isa<ConstantSDNode>(N0))
5649     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5650
5651   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5652   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5653   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5654   EVT SVT = VT.getScalarType();
5655   if (!(VT.isVector() &&
5656       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5657       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5658     return nullptr;
5659
5660   // We can fold this node into a build_vector.
5661   unsigned VTBits = SVT.getSizeInBits();
5662   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5663   SmallVector<SDValue, 8> Elts;
5664   unsigned NumElts = VT.getVectorNumElements();
5665   SDLoc DL(N);
5666
5667   for (unsigned i=0; i != NumElts; ++i) {
5668     SDValue Op = N0->getOperand(i);
5669     if (Op->getOpcode() == ISD::UNDEF) {
5670       Elts.push_back(DAG.getUNDEF(SVT));
5671       continue;
5672     }
5673
5674     SDLoc DL(Op);
5675     // Get the constant value and if needed trunc it to the size of the type.
5676     // Nodes like build_vector might have constants wider than the scalar type.
5677     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5678     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5679       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5680     else
5681       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5682   }
5683
5684   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5685 }
5686
5687 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5688 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5689 // transformation. Returns true if extension are possible and the above
5690 // mentioned transformation is profitable.
5691 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5692                                     unsigned ExtOpc,
5693                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5694                                     const TargetLowering &TLI) {
5695   bool HasCopyToRegUses = false;
5696   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5697   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5698                             UE = N0.getNode()->use_end();
5699        UI != UE; ++UI) {
5700     SDNode *User = *UI;
5701     if (User == N)
5702       continue;
5703     if (UI.getUse().getResNo() != N0.getResNo())
5704       continue;
5705     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5706     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5707       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5708       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5709         // Sign bits will be lost after a zext.
5710         return false;
5711       bool Add = false;
5712       for (unsigned i = 0; i != 2; ++i) {
5713         SDValue UseOp = User->getOperand(i);
5714         if (UseOp == N0)
5715           continue;
5716         if (!isa<ConstantSDNode>(UseOp))
5717           return false;
5718         Add = true;
5719       }
5720       if (Add)
5721         ExtendNodes.push_back(User);
5722       continue;
5723     }
5724     // If truncates aren't free and there are users we can't
5725     // extend, it isn't worthwhile.
5726     if (!isTruncFree)
5727       return false;
5728     // Remember if this value is live-out.
5729     if (User->getOpcode() == ISD::CopyToReg)
5730       HasCopyToRegUses = true;
5731   }
5732
5733   if (HasCopyToRegUses) {
5734     bool BothLiveOut = false;
5735     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5736          UI != UE; ++UI) {
5737       SDUse &Use = UI.getUse();
5738       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5739         BothLiveOut = true;
5740         break;
5741       }
5742     }
5743     if (BothLiveOut)
5744       // Both unextended and extended values are live out. There had better be
5745       // a good reason for the transformation.
5746       return ExtendNodes.size();
5747   }
5748   return true;
5749 }
5750
5751 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5752                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5753                                   ISD::NodeType ExtType) {
5754   // Extend SetCC uses if necessary.
5755   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5756     SDNode *SetCC = SetCCs[i];
5757     SmallVector<SDValue, 4> Ops;
5758
5759     for (unsigned j = 0; j != 2; ++j) {
5760       SDValue SOp = SetCC->getOperand(j);
5761       if (SOp == Trunc)
5762         Ops.push_back(ExtLoad);
5763       else
5764         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5765     }
5766
5767     Ops.push_back(SetCC->getOperand(2));
5768     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5769   }
5770 }
5771
5772 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5773 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5774   SDValue N0 = N->getOperand(0);
5775   EVT DstVT = N->getValueType(0);
5776   EVT SrcVT = N0.getValueType();
5777
5778   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5779           N->getOpcode() == ISD::ZERO_EXTEND) &&
5780          "Unexpected node type (not an extend)!");
5781
5782   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5783   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5784   //   (v8i32 (sext (v8i16 (load x))))
5785   // into:
5786   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5787   //                          (v4i32 (sextload (x + 16)))))
5788   // Where uses of the original load, i.e.:
5789   //   (v8i16 (load x))
5790   // are replaced with:
5791   //   (v8i16 (truncate
5792   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5793   //                            (v4i32 (sextload (x + 16)))))))
5794   //
5795   // This combine is only applicable to illegal, but splittable, vectors.
5796   // All legal types, and illegal non-vector types, are handled elsewhere.
5797   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5798   //
5799   if (N0->getOpcode() != ISD::LOAD)
5800     return SDValue();
5801
5802   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5803
5804   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5805       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5806       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5807     return SDValue();
5808
5809   SmallVector<SDNode *, 4> SetCCs;
5810   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5811     return SDValue();
5812
5813   ISD::LoadExtType ExtType =
5814       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5815
5816   // Try to split the vector types to get down to legal types.
5817   EVT SplitSrcVT = SrcVT;
5818   EVT SplitDstVT = DstVT;
5819   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5820          SplitSrcVT.getVectorNumElements() > 1) {
5821     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5822     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5823   }
5824
5825   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5826     return SDValue();
5827
5828   SDLoc DL(N);
5829   const unsigned NumSplits =
5830       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5831   const unsigned Stride = SplitSrcVT.getStoreSize();
5832   SmallVector<SDValue, 4> Loads;
5833   SmallVector<SDValue, 4> Chains;
5834
5835   SDValue BasePtr = LN0->getBasePtr();
5836   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5837     const unsigned Offset = Idx * Stride;
5838     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5839
5840     SDValue SplitLoad = DAG.getExtLoad(
5841         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5842         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5843         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5844         Align, LN0->getAAInfo());
5845
5846     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5847                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5848
5849     Loads.push_back(SplitLoad.getValue(0));
5850     Chains.push_back(SplitLoad.getValue(1));
5851   }
5852
5853   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5854   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5855
5856   CombineTo(N, NewValue);
5857
5858   // Replace uses of the original load (before extension)
5859   // with a truncate of the concatenated sextloaded vectors.
5860   SDValue Trunc =
5861       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5862   CombineTo(N0.getNode(), Trunc, NewChain);
5863   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5864                   (ISD::NodeType)N->getOpcode());
5865   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5866 }
5867
5868 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5869   SDValue N0 = N->getOperand(0);
5870   EVT VT = N->getValueType(0);
5871
5872   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5873                                               LegalOperations))
5874     return SDValue(Res, 0);
5875
5876   // fold (sext (sext x)) -> (sext x)
5877   // fold (sext (aext x)) -> (sext x)
5878   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5879     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5880                        N0.getOperand(0));
5881
5882   if (N0.getOpcode() == ISD::TRUNCATE) {
5883     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5884     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5885     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5886       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5887       if (NarrowLoad.getNode() != N0.getNode()) {
5888         CombineTo(N0.getNode(), NarrowLoad);
5889         // CombineTo deleted the truncate, if needed, but not what's under it.
5890         AddToWorklist(oye);
5891       }
5892       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5893     }
5894
5895     // See if the value being truncated is already sign extended.  If so, just
5896     // eliminate the trunc/sext pair.
5897     SDValue Op = N0.getOperand(0);
5898     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5899     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5900     unsigned DestBits = VT.getScalarType().getSizeInBits();
5901     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5902
5903     if (OpBits == DestBits) {
5904       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5905       // bits, it is already ready.
5906       if (NumSignBits > DestBits-MidBits)
5907         return Op;
5908     } else if (OpBits < DestBits) {
5909       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5910       // bits, just sext from i32.
5911       if (NumSignBits > OpBits-MidBits)
5912         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5913     } else {
5914       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5915       // bits, just truncate to i32.
5916       if (NumSignBits > OpBits-MidBits)
5917         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5918     }
5919
5920     // fold (sext (truncate x)) -> (sextinreg x).
5921     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5922                                                  N0.getValueType())) {
5923       if (OpBits < DestBits)
5924         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5925       else if (OpBits > DestBits)
5926         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5927       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5928                          DAG.getValueType(N0.getValueType()));
5929     }
5930   }
5931
5932   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5933   // Only generate vector extloads when 1) they're legal, and 2) they are
5934   // deemed desirable by the target.
5935   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5936       ((!LegalOperations && !VT.isVector() &&
5937         !cast<LoadSDNode>(N0)->isVolatile()) ||
5938        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5939     bool DoXform = true;
5940     SmallVector<SDNode*, 4> SetCCs;
5941     if (!N0.hasOneUse())
5942       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5943     if (VT.isVector())
5944       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5945     if (DoXform) {
5946       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5947       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5948                                        LN0->getChain(),
5949                                        LN0->getBasePtr(), N0.getValueType(),
5950                                        LN0->getMemOperand());
5951       CombineTo(N, ExtLoad);
5952       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5953                                   N0.getValueType(), ExtLoad);
5954       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5955       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5956                       ISD::SIGN_EXTEND);
5957       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5958     }
5959   }
5960
5961   // fold (sext (load x)) to multiple smaller sextloads.
5962   // Only on illegal but splittable vectors.
5963   if (SDValue ExtLoad = CombineExtLoad(N))
5964     return ExtLoad;
5965
5966   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5967   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5968   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5969       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5970     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5971     EVT MemVT = LN0->getMemoryVT();
5972     if ((!LegalOperations && !LN0->isVolatile()) ||
5973         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5974       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5975                                        LN0->getChain(),
5976                                        LN0->getBasePtr(), MemVT,
5977                                        LN0->getMemOperand());
5978       CombineTo(N, ExtLoad);
5979       CombineTo(N0.getNode(),
5980                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5981                             N0.getValueType(), ExtLoad),
5982                 ExtLoad.getValue(1));
5983       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5984     }
5985   }
5986
5987   // fold (sext (and/or/xor (load x), cst)) ->
5988   //      (and/or/xor (sextload x), (sext cst))
5989   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5990        N0.getOpcode() == ISD::XOR) &&
5991       isa<LoadSDNode>(N0.getOperand(0)) &&
5992       N0.getOperand(1).getOpcode() == ISD::Constant &&
5993       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5994       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5995     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5996     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5997       bool DoXform = true;
5998       SmallVector<SDNode*, 4> SetCCs;
5999       if (!N0.hasOneUse())
6000         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6001                                           SetCCs, TLI);
6002       if (DoXform) {
6003         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6004                                          LN0->getChain(), LN0->getBasePtr(),
6005                                          LN0->getMemoryVT(),
6006                                          LN0->getMemOperand());
6007         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6008         Mask = Mask.sext(VT.getSizeInBits());
6009         SDLoc DL(N);
6010         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6011                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6012         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6013                                     SDLoc(N0.getOperand(0)),
6014                                     N0.getOperand(0).getValueType(), ExtLoad);
6015         CombineTo(N, And);
6016         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6017         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6018                         ISD::SIGN_EXTEND);
6019         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6020       }
6021     }
6022   }
6023
6024   if (N0.getOpcode() == ISD::SETCC) {
6025     EVT N0VT = N0.getOperand(0).getValueType();
6026     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6027     // Only do this before legalize for now.
6028     if (VT.isVector() && !LegalOperations &&
6029         TLI.getBooleanContents(N0VT) ==
6030             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6031       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6032       // of the same size as the compared operands. Only optimize sext(setcc())
6033       // if this is the case.
6034       EVT SVT = getSetCCResultType(N0VT);
6035
6036       // We know that the # elements of the results is the same as the
6037       // # elements of the compare (and the # elements of the compare result
6038       // for that matter).  Check to see that they are the same size.  If so,
6039       // we know that the element size of the sext'd result matches the
6040       // element size of the compare operands.
6041       if (VT.getSizeInBits() == SVT.getSizeInBits())
6042         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6043                              N0.getOperand(1),
6044                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6045
6046       // If the desired elements are smaller or larger than the source
6047       // elements we can use a matching integer vector type and then
6048       // truncate/sign extend
6049       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6050       if (SVT == MatchingVectorType) {
6051         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6052                                N0.getOperand(0), N0.getOperand(1),
6053                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6054         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6055       }
6056     }
6057
6058     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6059     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6060     SDLoc DL(N);
6061     SDValue NegOne =
6062       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6063     SDValue SCC =
6064       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6065                        NegOne, DAG.getConstant(0, DL, VT),
6066                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6067     if (SCC.getNode()) return SCC;
6068
6069     if (!VT.isVector()) {
6070       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6071       if (!LegalOperations ||
6072           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6073         SDLoc DL(N);
6074         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6075         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6076                                      N0.getOperand(0), N0.getOperand(1), CC);
6077         return DAG.getSelect(DL, VT, SetCC,
6078                              NegOne, DAG.getConstant(0, DL, VT));
6079       }
6080     }
6081   }
6082
6083   // fold (sext x) -> (zext x) if the sign bit is known zero.
6084   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6085       DAG.SignBitIsZero(N0))
6086     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6087
6088   return SDValue();
6089 }
6090
6091 // isTruncateOf - If N is a truncate of some other value, return true, record
6092 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6093 // This function computes KnownZero to avoid a duplicated call to
6094 // computeKnownBits in the caller.
6095 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6096                          APInt &KnownZero) {
6097   APInt KnownOne;
6098   if (N->getOpcode() == ISD::TRUNCATE) {
6099     Op = N->getOperand(0);
6100     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6101     return true;
6102   }
6103
6104   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6105       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6106     return false;
6107
6108   SDValue Op0 = N->getOperand(0);
6109   SDValue Op1 = N->getOperand(1);
6110   assert(Op0.getValueType() == Op1.getValueType());
6111
6112   if (isNullConstant(Op0))
6113     Op = Op1;
6114   else if (isNullConstant(Op1))
6115     Op = Op0;
6116   else
6117     return false;
6118
6119   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6120
6121   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6122     return false;
6123
6124   return true;
6125 }
6126
6127 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6128   SDValue N0 = N->getOperand(0);
6129   EVT VT = N->getValueType(0);
6130
6131   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6132                                               LegalOperations))
6133     return SDValue(Res, 0);
6134
6135   // fold (zext (zext x)) -> (zext x)
6136   // fold (zext (aext x)) -> (zext x)
6137   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6138     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6139                        N0.getOperand(0));
6140
6141   // fold (zext (truncate x)) -> (zext x) or
6142   //      (zext (truncate x)) -> (truncate x)
6143   // This is valid when the truncated bits of x are already zero.
6144   // FIXME: We should extend this to work for vectors too.
6145   SDValue Op;
6146   APInt KnownZero;
6147   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6148     APInt TruncatedBits =
6149       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6150       APInt(Op.getValueSizeInBits(), 0) :
6151       APInt::getBitsSet(Op.getValueSizeInBits(),
6152                         N0.getValueSizeInBits(),
6153                         std::min(Op.getValueSizeInBits(),
6154                                  VT.getSizeInBits()));
6155     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6156       if (VT.bitsGT(Op.getValueType()))
6157         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6158       if (VT.bitsLT(Op.getValueType()))
6159         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6160
6161       return Op;
6162     }
6163   }
6164
6165   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6166   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6167   if (N0.getOpcode() == ISD::TRUNCATE) {
6168     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6169       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6170       if (NarrowLoad.getNode() != N0.getNode()) {
6171         CombineTo(N0.getNode(), NarrowLoad);
6172         // CombineTo deleted the truncate, if needed, but not what's under it.
6173         AddToWorklist(oye);
6174       }
6175       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6176     }
6177   }
6178
6179   // fold (zext (truncate x)) -> (and x, mask)
6180   if (N0.getOpcode() == ISD::TRUNCATE) {
6181     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6182     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6183     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6184       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6185       if (NarrowLoad.getNode() != N0.getNode()) {
6186         CombineTo(N0.getNode(), NarrowLoad);
6187         // CombineTo deleted the truncate, if needed, but not what's under it.
6188         AddToWorklist(oye);
6189       }
6190       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6191     }
6192
6193     EVT SrcVT = N0.getOperand(0).getValueType();
6194     EVT MinVT = N0.getValueType();
6195
6196     // Try to mask before the extension to avoid having to generate a larger mask,
6197     // possibly over several sub-vectors.
6198     if (SrcVT.bitsLT(VT)) {
6199       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6200                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6201         SDValue Op = N0.getOperand(0);
6202         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6203         AddToWorklist(Op.getNode());
6204         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6205       }
6206     }
6207
6208     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6209       SDValue Op = N0.getOperand(0);
6210       if (SrcVT.bitsLT(VT)) {
6211         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6212         AddToWorklist(Op.getNode());
6213       } else if (SrcVT.bitsGT(VT)) {
6214         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6215         AddToWorklist(Op.getNode());
6216       }
6217       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6218     }
6219   }
6220
6221   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6222   // if either of the casts is not free.
6223   if (N0.getOpcode() == ISD::AND &&
6224       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6225       N0.getOperand(1).getOpcode() == ISD::Constant &&
6226       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6227                            N0.getValueType()) ||
6228        !TLI.isZExtFree(N0.getValueType(), VT))) {
6229     SDValue X = N0.getOperand(0).getOperand(0);
6230     if (X.getValueType().bitsLT(VT)) {
6231       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6232     } else if (X.getValueType().bitsGT(VT)) {
6233       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6234     }
6235     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6236     Mask = Mask.zext(VT.getSizeInBits());
6237     SDLoc DL(N);
6238     return DAG.getNode(ISD::AND, DL, VT,
6239                        X, DAG.getConstant(Mask, DL, VT));
6240   }
6241
6242   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6243   // Only generate vector extloads when 1) they're legal, and 2) they are
6244   // deemed desirable by the target.
6245   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6246       ((!LegalOperations && !VT.isVector() &&
6247         !cast<LoadSDNode>(N0)->isVolatile()) ||
6248        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6249     bool DoXform = true;
6250     SmallVector<SDNode*, 4> SetCCs;
6251     if (!N0.hasOneUse())
6252       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6253     if (VT.isVector())
6254       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6255     if (DoXform) {
6256       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6257       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6258                                        LN0->getChain(),
6259                                        LN0->getBasePtr(), N0.getValueType(),
6260                                        LN0->getMemOperand());
6261       CombineTo(N, ExtLoad);
6262       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6263                                   N0.getValueType(), ExtLoad);
6264       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6265
6266       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6267                       ISD::ZERO_EXTEND);
6268       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6269     }
6270   }
6271
6272   // fold (zext (load x)) to multiple smaller zextloads.
6273   // Only on illegal but splittable vectors.
6274   if (SDValue ExtLoad = CombineExtLoad(N))
6275     return ExtLoad;
6276
6277   // fold (zext (and/or/xor (load x), cst)) ->
6278   //      (and/or/xor (zextload x), (zext cst))
6279   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6280        N0.getOpcode() == ISD::XOR) &&
6281       isa<LoadSDNode>(N0.getOperand(0)) &&
6282       N0.getOperand(1).getOpcode() == ISD::Constant &&
6283       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6284       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6285     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6286     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6287       bool DoXform = true;
6288       SmallVector<SDNode*, 4> SetCCs;
6289       if (!N0.hasOneUse())
6290         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6291                                           SetCCs, TLI);
6292       if (DoXform) {
6293         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6294                                          LN0->getChain(), LN0->getBasePtr(),
6295                                          LN0->getMemoryVT(),
6296                                          LN0->getMemOperand());
6297         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6298         Mask = Mask.zext(VT.getSizeInBits());
6299         SDLoc DL(N);
6300         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6301                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6302         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6303                                     SDLoc(N0.getOperand(0)),
6304                                     N0.getOperand(0).getValueType(), ExtLoad);
6305         CombineTo(N, And);
6306         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6307         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6308                         ISD::ZERO_EXTEND);
6309         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6310       }
6311     }
6312   }
6313
6314   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6315   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6316   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6317       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6318     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6319     EVT MemVT = LN0->getMemoryVT();
6320     if ((!LegalOperations && !LN0->isVolatile()) ||
6321         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6322       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6323                                        LN0->getChain(),
6324                                        LN0->getBasePtr(), MemVT,
6325                                        LN0->getMemOperand());
6326       CombineTo(N, ExtLoad);
6327       CombineTo(N0.getNode(),
6328                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6329                             ExtLoad),
6330                 ExtLoad.getValue(1));
6331       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6332     }
6333   }
6334
6335   if (N0.getOpcode() == ISD::SETCC) {
6336     if (!LegalOperations && VT.isVector() &&
6337         N0.getValueType().getVectorElementType() == MVT::i1) {
6338       EVT N0VT = N0.getOperand(0).getValueType();
6339       if (getSetCCResultType(N0VT) == N0.getValueType())
6340         return SDValue();
6341
6342       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6343       // Only do this before legalize for now.
6344       EVT EltVT = VT.getVectorElementType();
6345       SDLoc DL(N);
6346       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6347                                     DAG.getConstant(1, DL, EltVT));
6348       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6349         // We know that the # elements of the results is the same as the
6350         // # elements of the compare (and the # elements of the compare result
6351         // for that matter).  Check to see that they are the same size.  If so,
6352         // we know that the element size of the sext'd result matches the
6353         // element size of the compare operands.
6354         return DAG.getNode(ISD::AND, DL, VT,
6355                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6356                                          N0.getOperand(1),
6357                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6358                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6359                                        OneOps));
6360
6361       // If the desired elements are smaller or larger than the source
6362       // elements we can use a matching integer vector type and then
6363       // truncate/sign extend
6364       EVT MatchingElementType =
6365         EVT::getIntegerVT(*DAG.getContext(),
6366                           N0VT.getScalarType().getSizeInBits());
6367       EVT MatchingVectorType =
6368         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6369                          N0VT.getVectorNumElements());
6370       SDValue VsetCC =
6371         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6372                       N0.getOperand(1),
6373                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6374       return DAG.getNode(ISD::AND, DL, VT,
6375                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6376                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6377     }
6378
6379     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6380     SDLoc DL(N);
6381     SDValue SCC =
6382       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6383                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6384                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6385     if (SCC.getNode()) return SCC;
6386   }
6387
6388   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6389   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6390       isa<ConstantSDNode>(N0.getOperand(1)) &&
6391       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6392       N0.hasOneUse()) {
6393     SDValue ShAmt = N0.getOperand(1);
6394     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6395     if (N0.getOpcode() == ISD::SHL) {
6396       SDValue InnerZExt = N0.getOperand(0);
6397       // If the original shl may be shifting out bits, do not perform this
6398       // transformation.
6399       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6400         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6401       if (ShAmtVal > KnownZeroBits)
6402         return SDValue();
6403     }
6404
6405     SDLoc DL(N);
6406
6407     // Ensure that the shift amount is wide enough for the shifted value.
6408     if (VT.getSizeInBits() >= 256)
6409       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6410
6411     return DAG.getNode(N0.getOpcode(), DL, VT,
6412                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6413                        ShAmt);
6414   }
6415
6416   return SDValue();
6417 }
6418
6419 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6420   SDValue N0 = N->getOperand(0);
6421   EVT VT = N->getValueType(0);
6422
6423   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6424                                               LegalOperations))
6425     return SDValue(Res, 0);
6426
6427   // fold (aext (aext x)) -> (aext x)
6428   // fold (aext (zext x)) -> (zext x)
6429   // fold (aext (sext x)) -> (sext x)
6430   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6431       N0.getOpcode() == ISD::ZERO_EXTEND ||
6432       N0.getOpcode() == ISD::SIGN_EXTEND)
6433     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6434
6435   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6436   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6437   if (N0.getOpcode() == ISD::TRUNCATE) {
6438     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6439       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6440       if (NarrowLoad.getNode() != N0.getNode()) {
6441         CombineTo(N0.getNode(), NarrowLoad);
6442         // CombineTo deleted the truncate, if needed, but not what's under it.
6443         AddToWorklist(oye);
6444       }
6445       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6446     }
6447   }
6448
6449   // fold (aext (truncate x))
6450   if (N0.getOpcode() == ISD::TRUNCATE) {
6451     SDValue TruncOp = N0.getOperand(0);
6452     if (TruncOp.getValueType() == VT)
6453       return TruncOp; // x iff x size == zext size.
6454     if (TruncOp.getValueType().bitsGT(VT))
6455       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6456     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6457   }
6458
6459   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6460   // if the trunc is not free.
6461   if (N0.getOpcode() == ISD::AND &&
6462       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6463       N0.getOperand(1).getOpcode() == ISD::Constant &&
6464       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6465                           N0.getValueType())) {
6466     SDValue X = N0.getOperand(0).getOperand(0);
6467     if (X.getValueType().bitsLT(VT)) {
6468       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6469     } else if (X.getValueType().bitsGT(VT)) {
6470       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6471     }
6472     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6473     Mask = Mask.zext(VT.getSizeInBits());
6474     SDLoc DL(N);
6475     return DAG.getNode(ISD::AND, DL, VT,
6476                        X, DAG.getConstant(Mask, DL, VT));
6477   }
6478
6479   // fold (aext (load x)) -> (aext (truncate (extload x)))
6480   // None of the supported targets knows how to perform load and any_ext
6481   // on vectors in one instruction.  We only perform this transformation on
6482   // scalars.
6483   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6484       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6485       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6486     bool DoXform = true;
6487     SmallVector<SDNode*, 4> SetCCs;
6488     if (!N0.hasOneUse())
6489       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6490     if (DoXform) {
6491       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6492       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6493                                        LN0->getChain(),
6494                                        LN0->getBasePtr(), N0.getValueType(),
6495                                        LN0->getMemOperand());
6496       CombineTo(N, ExtLoad);
6497       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6498                                   N0.getValueType(), ExtLoad);
6499       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6500       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6501                       ISD::ANY_EXTEND);
6502       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6503     }
6504   }
6505
6506   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6507   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6508   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6509   if (N0.getOpcode() == ISD::LOAD &&
6510       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6511       N0.hasOneUse()) {
6512     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6513     ISD::LoadExtType ExtType = LN0->getExtensionType();
6514     EVT MemVT = LN0->getMemoryVT();
6515     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6516       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6517                                        VT, LN0->getChain(), LN0->getBasePtr(),
6518                                        MemVT, LN0->getMemOperand());
6519       CombineTo(N, ExtLoad);
6520       CombineTo(N0.getNode(),
6521                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6522                             N0.getValueType(), ExtLoad),
6523                 ExtLoad.getValue(1));
6524       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6525     }
6526   }
6527
6528   if (N0.getOpcode() == ISD::SETCC) {
6529     // For vectors:
6530     // aext(setcc) -> vsetcc
6531     // aext(setcc) -> truncate(vsetcc)
6532     // aext(setcc) -> aext(vsetcc)
6533     // Only do this before legalize for now.
6534     if (VT.isVector() && !LegalOperations) {
6535       EVT N0VT = N0.getOperand(0).getValueType();
6536         // We know that the # elements of the results is the same as the
6537         // # elements of the compare (and the # elements of the compare result
6538         // for that matter).  Check to see that they are the same size.  If so,
6539         // we know that the element size of the sext'd result matches the
6540         // element size of the compare operands.
6541       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6542         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6543                              N0.getOperand(1),
6544                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6545       // If the desired elements are smaller or larger than the source
6546       // elements we can use a matching integer vector type and then
6547       // truncate/any extend
6548       else {
6549         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6550         SDValue VsetCC =
6551           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6552                         N0.getOperand(1),
6553                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6554         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6555       }
6556     }
6557
6558     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6559     SDLoc DL(N);
6560     SDValue SCC =
6561       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6562                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6563                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6564     if (SCC.getNode())
6565       return SCC;
6566   }
6567
6568   return SDValue();
6569 }
6570
6571 /// See if the specified operand can be simplified with the knowledge that only
6572 /// the bits specified by Mask are used.  If so, return the simpler operand,
6573 /// otherwise return a null SDValue.
6574 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6575   switch (V.getOpcode()) {
6576   default: break;
6577   case ISD::Constant: {
6578     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6579     assert(CV && "Const value should be ConstSDNode.");
6580     const APInt &CVal = CV->getAPIntValue();
6581     APInt NewVal = CVal & Mask;
6582     if (NewVal != CVal)
6583       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6584     break;
6585   }
6586   case ISD::OR:
6587   case ISD::XOR:
6588     // If the LHS or RHS don't contribute bits to the or, drop them.
6589     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6590       return V.getOperand(1);
6591     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6592       return V.getOperand(0);
6593     break;
6594   case ISD::SRL:
6595     // Only look at single-use SRLs.
6596     if (!V.getNode()->hasOneUse())
6597       break;
6598     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6599       // See if we can recursively simplify the LHS.
6600       unsigned Amt = RHSC->getZExtValue();
6601
6602       // Watch out for shift count overflow though.
6603       if (Amt >= Mask.getBitWidth()) break;
6604       APInt NewMask = Mask << Amt;
6605       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6606         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6607                            SimplifyLHS, V.getOperand(1));
6608     }
6609   }
6610   return SDValue();
6611 }
6612
6613 /// If the result of a wider load is shifted to right of N  bits and then
6614 /// truncated to a narrower type and where N is a multiple of number of bits of
6615 /// the narrower type, transform it to a narrower load from address + N / num of
6616 /// bits of new type. If the result is to be extended, also fold the extension
6617 /// to form a extending load.
6618 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6619   unsigned Opc = N->getOpcode();
6620
6621   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6622   SDValue N0 = N->getOperand(0);
6623   EVT VT = N->getValueType(0);
6624   EVT ExtVT = VT;
6625
6626   // This transformation isn't valid for vector loads.
6627   if (VT.isVector())
6628     return SDValue();
6629
6630   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6631   // extended to VT.
6632   if (Opc == ISD::SIGN_EXTEND_INREG) {
6633     ExtType = ISD::SEXTLOAD;
6634     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6635   } else if (Opc == ISD::SRL) {
6636     // Another special-case: SRL is basically zero-extending a narrower value.
6637     ExtType = ISD::ZEXTLOAD;
6638     N0 = SDValue(N, 0);
6639     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6640     if (!N01) return SDValue();
6641     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6642                               VT.getSizeInBits() - N01->getZExtValue());
6643   }
6644   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6645     return SDValue();
6646
6647   unsigned EVTBits = ExtVT.getSizeInBits();
6648
6649   // Do not generate loads of non-round integer types since these can
6650   // be expensive (and would be wrong if the type is not byte sized).
6651   if (!ExtVT.isRound())
6652     return SDValue();
6653
6654   unsigned ShAmt = 0;
6655   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6656     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6657       ShAmt = N01->getZExtValue();
6658       // Is the shift amount a multiple of size of VT?
6659       if ((ShAmt & (EVTBits-1)) == 0) {
6660         N0 = N0.getOperand(0);
6661         // Is the load width a multiple of size of VT?
6662         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6663           return SDValue();
6664       }
6665
6666       // At this point, we must have a load or else we can't do the transform.
6667       if (!isa<LoadSDNode>(N0)) return SDValue();
6668
6669       // Because a SRL must be assumed to *need* to zero-extend the high bits
6670       // (as opposed to anyext the high bits), we can't combine the zextload
6671       // lowering of SRL and an sextload.
6672       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6673         return SDValue();
6674
6675       // If the shift amount is larger than the input type then we're not
6676       // accessing any of the loaded bytes.  If the load was a zextload/extload
6677       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6678       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6679         return SDValue();
6680     }
6681   }
6682
6683   // If the load is shifted left (and the result isn't shifted back right),
6684   // we can fold the truncate through the shift.
6685   unsigned ShLeftAmt = 0;
6686   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6687       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6688     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6689       ShLeftAmt = N01->getZExtValue();
6690       N0 = N0.getOperand(0);
6691     }
6692   }
6693
6694   // If we haven't found a load, we can't narrow it.  Don't transform one with
6695   // multiple uses, this would require adding a new load.
6696   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6697     return SDValue();
6698
6699   // Don't change the width of a volatile load.
6700   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6701   if (LN0->isVolatile())
6702     return SDValue();
6703
6704   // Verify that we are actually reducing a load width here.
6705   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6706     return SDValue();
6707
6708   // For the transform to be legal, the load must produce only two values
6709   // (the value loaded and the chain).  Don't transform a pre-increment
6710   // load, for example, which produces an extra value.  Otherwise the
6711   // transformation is not equivalent, and the downstream logic to replace
6712   // uses gets things wrong.
6713   if (LN0->getNumValues() > 2)
6714     return SDValue();
6715
6716   // If the load that we're shrinking is an extload and we're not just
6717   // discarding the extension we can't simply shrink the load. Bail.
6718   // TODO: It would be possible to merge the extensions in some cases.
6719   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6720       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6721     return SDValue();
6722
6723   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6724     return SDValue();
6725
6726   EVT PtrType = N0.getOperand(1).getValueType();
6727
6728   if (PtrType == MVT::Untyped || PtrType.isExtended())
6729     // It's not possible to generate a constant of extended or untyped type.
6730     return SDValue();
6731
6732   // For big endian targets, we need to adjust the offset to the pointer to
6733   // load the correct bytes.
6734   if (DAG.getDataLayout().isBigEndian()) {
6735     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6736     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6737     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6738   }
6739
6740   uint64_t PtrOff = ShAmt / 8;
6741   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6742   SDLoc DL(LN0);
6743   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6744                                PtrType, LN0->getBasePtr(),
6745                                DAG.getConstant(PtrOff, DL, PtrType));
6746   AddToWorklist(NewPtr.getNode());
6747
6748   SDValue Load;
6749   if (ExtType == ISD::NON_EXTLOAD)
6750     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6751                         LN0->getPointerInfo().getWithOffset(PtrOff),
6752                         LN0->isVolatile(), LN0->isNonTemporal(),
6753                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6754   else
6755     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6756                           LN0->getPointerInfo().getWithOffset(PtrOff),
6757                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6758                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6759
6760   // Replace the old load's chain with the new load's chain.
6761   WorklistRemover DeadNodes(*this);
6762   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6763
6764   // Shift the result left, if we've swallowed a left shift.
6765   SDValue Result = Load;
6766   if (ShLeftAmt != 0) {
6767     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6768     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6769       ShImmTy = VT;
6770     // If the shift amount is as large as the result size (but, presumably,
6771     // no larger than the source) then the useful bits of the result are
6772     // zero; we can't simply return the shortened shift, because the result
6773     // of that operation is undefined.
6774     SDLoc DL(N0);
6775     if (ShLeftAmt >= VT.getSizeInBits())
6776       Result = DAG.getConstant(0, DL, VT);
6777     else
6778       Result = DAG.getNode(ISD::SHL, DL, VT,
6779                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6780   }
6781
6782   // Return the new loaded value.
6783   return Result;
6784 }
6785
6786 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6787   SDValue N0 = N->getOperand(0);
6788   SDValue N1 = N->getOperand(1);
6789   EVT VT = N->getValueType(0);
6790   EVT EVT = cast<VTSDNode>(N1)->getVT();
6791   unsigned VTBits = VT.getScalarType().getSizeInBits();
6792   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6793
6794   // fold (sext_in_reg c1) -> c1
6795   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6796     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6797
6798   // If the input is already sign extended, just drop the extension.
6799   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6800     return N0;
6801
6802   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6803   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6804       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6805     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6806                        N0.getOperand(0), N1);
6807
6808   // fold (sext_in_reg (sext x)) -> (sext x)
6809   // fold (sext_in_reg (aext x)) -> (sext x)
6810   // if x is small enough.
6811   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6812     SDValue N00 = N0.getOperand(0);
6813     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6814         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6815       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6816   }
6817
6818   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6819   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6820     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6821
6822   // fold operands of sext_in_reg based on knowledge that the top bits are not
6823   // demanded.
6824   if (SimplifyDemandedBits(SDValue(N, 0)))
6825     return SDValue(N, 0);
6826
6827   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6828   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6829   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6830     return NarrowLoad;
6831
6832   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6833   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6834   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6835   if (N0.getOpcode() == ISD::SRL) {
6836     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6837       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6838         // We can turn this into an SRA iff the input to the SRL is already sign
6839         // extended enough.
6840         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6841         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6842           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6843                              N0.getOperand(0), N0.getOperand(1));
6844       }
6845   }
6846
6847   // fold (sext_inreg (extload x)) -> (sextload x)
6848   if (ISD::isEXTLoad(N0.getNode()) &&
6849       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6850       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6851       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6852        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6853     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6854     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6855                                      LN0->getChain(),
6856                                      LN0->getBasePtr(), EVT,
6857                                      LN0->getMemOperand());
6858     CombineTo(N, ExtLoad);
6859     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6860     AddToWorklist(ExtLoad.getNode());
6861     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6862   }
6863   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6864   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6865       N0.hasOneUse() &&
6866       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6867       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6868        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6869     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6870     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6871                                      LN0->getChain(),
6872                                      LN0->getBasePtr(), EVT,
6873                                      LN0->getMemOperand());
6874     CombineTo(N, ExtLoad);
6875     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6876     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6877   }
6878
6879   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6880   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6881     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6882                                        N0.getOperand(1), false);
6883     if (BSwap.getNode())
6884       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6885                          BSwap, N1);
6886   }
6887
6888   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6889   // into a build_vector.
6890   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6891     SmallVector<SDValue, 8> Elts;
6892     unsigned NumElts = N0->getNumOperands();
6893     unsigned ShAmt = VTBits - EVTBits;
6894
6895     for (unsigned i = 0; i != NumElts; ++i) {
6896       SDValue Op = N0->getOperand(i);
6897       if (Op->getOpcode() == ISD::UNDEF) {
6898         Elts.push_back(Op);
6899         continue;
6900       }
6901
6902       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6903       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6904       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6905                                      SDLoc(Op), Op.getValueType()));
6906     }
6907
6908     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6909   }
6910
6911   return SDValue();
6912 }
6913
6914 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6915   SDValue N0 = N->getOperand(0);
6916   EVT VT = N->getValueType(0);
6917
6918   if (N0.getOpcode() == ISD::UNDEF)
6919     return DAG.getUNDEF(VT);
6920
6921   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6922                                               LegalOperations))
6923     return SDValue(Res, 0);
6924
6925   return SDValue();
6926 }
6927
6928 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6929   SDValue N0 = N->getOperand(0);
6930   EVT VT = N->getValueType(0);
6931   bool isLE = DAG.getDataLayout().isLittleEndian();
6932
6933   // noop truncate
6934   if (N0.getValueType() == N->getValueType(0))
6935     return N0;
6936   // fold (truncate c1) -> c1
6937   if (isConstantIntBuildVectorOrConstantInt(N0))
6938     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6939   // fold (truncate (truncate x)) -> (truncate x)
6940   if (N0.getOpcode() == ISD::TRUNCATE)
6941     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6942   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6943   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6944       N0.getOpcode() == ISD::SIGN_EXTEND ||
6945       N0.getOpcode() == ISD::ANY_EXTEND) {
6946     if (N0.getOperand(0).getValueType().bitsLT(VT))
6947       // if the source is smaller than the dest, we still need an extend
6948       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6949                          N0.getOperand(0));
6950     if (N0.getOperand(0).getValueType().bitsGT(VT))
6951       // if the source is larger than the dest, than we just need the truncate
6952       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6953     // if the source and dest are the same type, we can drop both the extend
6954     // and the truncate.
6955     return N0.getOperand(0);
6956   }
6957
6958   // Fold extract-and-trunc into a narrow extract. For example:
6959   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6960   //   i32 y = TRUNCATE(i64 x)
6961   //        -- becomes --
6962   //   v16i8 b = BITCAST (v2i64 val)
6963   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6964   //
6965   // Note: We only run this optimization after type legalization (which often
6966   // creates this pattern) and before operation legalization after which
6967   // we need to be more careful about the vector instructions that we generate.
6968   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6969       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6970
6971     EVT VecTy = N0.getOperand(0).getValueType();
6972     EVT ExTy = N0.getValueType();
6973     EVT TrTy = N->getValueType(0);
6974
6975     unsigned NumElem = VecTy.getVectorNumElements();
6976     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6977
6978     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6979     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6980
6981     SDValue EltNo = N0->getOperand(1);
6982     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6983       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6984       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6985       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6986
6987       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6988                               NVT, N0.getOperand(0));
6989
6990       SDLoc DL(N);
6991       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6992                          DL, TrTy, V,
6993                          DAG.getConstant(Index, DL, IndexTy));
6994     }
6995   }
6996
6997   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6998   if (N0.getOpcode() == ISD::SELECT) {
6999     EVT SrcVT = N0.getValueType();
7000     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7001         TLI.isTruncateFree(SrcVT, VT)) {
7002       SDLoc SL(N0);
7003       SDValue Cond = N0.getOperand(0);
7004       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7005       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7006       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7007     }
7008   }
7009
7010   // Fold a series of buildvector, bitcast, and truncate if possible.
7011   // For example fold
7012   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7013   //   (2xi32 (buildvector x, y)).
7014   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7015       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7016       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7017       N0.getOperand(0).hasOneUse()) {
7018
7019     SDValue BuildVect = N0.getOperand(0);
7020     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7021     EVT TruncVecEltTy = VT.getVectorElementType();
7022
7023     // Check that the element types match.
7024     if (BuildVectEltTy == TruncVecEltTy) {
7025       // Now we only need to compute the offset of the truncated elements.
7026       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7027       unsigned TruncVecNumElts = VT.getVectorNumElements();
7028       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7029
7030       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7031              "Invalid number of elements");
7032
7033       SmallVector<SDValue, 8> Opnds;
7034       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7035         Opnds.push_back(BuildVect.getOperand(i));
7036
7037       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7038     }
7039   }
7040
7041   // See if we can simplify the input to this truncate through knowledge that
7042   // only the low bits are being used.
7043   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7044   // Currently we only perform this optimization on scalars because vectors
7045   // may have different active low bits.
7046   if (!VT.isVector()) {
7047     SDValue Shorter =
7048       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7049                                                VT.getSizeInBits()));
7050     if (Shorter.getNode())
7051       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7052   }
7053   // fold (truncate (load x)) -> (smaller load x)
7054   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7055   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7056     if (SDValue Reduced = ReduceLoadWidth(N))
7057       return Reduced;
7058
7059     // Handle the case where the load remains an extending load even
7060     // after truncation.
7061     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7062       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7063       if (!LN0->isVolatile() &&
7064           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7065         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7066                                          VT, LN0->getChain(), LN0->getBasePtr(),
7067                                          LN0->getMemoryVT(),
7068                                          LN0->getMemOperand());
7069         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7070         return NewLoad;
7071       }
7072     }
7073   }
7074   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7075   // where ... are all 'undef'.
7076   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7077     SmallVector<EVT, 8> VTs;
7078     SDValue V;
7079     unsigned Idx = 0;
7080     unsigned NumDefs = 0;
7081
7082     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7083       SDValue X = N0.getOperand(i);
7084       if (X.getOpcode() != ISD::UNDEF) {
7085         V = X;
7086         Idx = i;
7087         NumDefs++;
7088       }
7089       // Stop if more than one members are non-undef.
7090       if (NumDefs > 1)
7091         break;
7092       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7093                                      VT.getVectorElementType(),
7094                                      X.getValueType().getVectorNumElements()));
7095     }
7096
7097     if (NumDefs == 0)
7098       return DAG.getUNDEF(VT);
7099
7100     if (NumDefs == 1) {
7101       assert(V.getNode() && "The single defined operand is empty!");
7102       SmallVector<SDValue, 8> Opnds;
7103       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7104         if (i != Idx) {
7105           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7106           continue;
7107         }
7108         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7109         AddToWorklist(NV.getNode());
7110         Opnds.push_back(NV);
7111       }
7112       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7113     }
7114   }
7115
7116   // Simplify the operands using demanded-bits information.
7117   if (!VT.isVector() &&
7118       SimplifyDemandedBits(SDValue(N, 0)))
7119     return SDValue(N, 0);
7120
7121   return SDValue();
7122 }
7123
7124 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7125   SDValue Elt = N->getOperand(i);
7126   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7127     return Elt.getNode();
7128   return Elt.getOperand(Elt.getResNo()).getNode();
7129 }
7130
7131 /// build_pair (load, load) -> load
7132 /// if load locations are consecutive.
7133 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7134   assert(N->getOpcode() == ISD::BUILD_PAIR);
7135
7136   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7137   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7138   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7139       LD1->getAddressSpace() != LD2->getAddressSpace())
7140     return SDValue();
7141   EVT LD1VT = LD1->getValueType(0);
7142
7143   if (ISD::isNON_EXTLoad(LD2) &&
7144       LD2->hasOneUse() &&
7145       // If both are volatile this would reduce the number of volatile loads.
7146       // If one is volatile it might be ok, but play conservative and bail out.
7147       !LD1->isVolatile() &&
7148       !LD2->isVolatile() &&
7149       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7150     unsigned Align = LD1->getAlignment();
7151     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7152         VT.getTypeForEVT(*DAG.getContext()));
7153
7154     if (NewAlign <= Align &&
7155         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7156       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7157                          LD1->getBasePtr(), LD1->getPointerInfo(),
7158                          false, false, false, Align);
7159   }
7160
7161   return SDValue();
7162 }
7163
7164 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7165   SDValue N0 = N->getOperand(0);
7166   EVT VT = N->getValueType(0);
7167
7168   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7169   // Only do this before legalize, since afterward the target may be depending
7170   // on the bitconvert.
7171   // First check to see if this is all constant.
7172   if (!LegalTypes &&
7173       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7174       VT.isVector()) {
7175     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7176
7177     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7178     assert(!DestEltVT.isVector() &&
7179            "Element type of vector ValueType must not be vector!");
7180     if (isSimple)
7181       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7182   }
7183
7184   // If the input is a constant, let getNode fold it.
7185   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7186     // If we can't allow illegal operations, we need to check that this is just
7187     // a fp -> int or int -> conversion and that the resulting operation will
7188     // be legal.
7189     if (!LegalOperations ||
7190         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7191          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7192         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7193          TLI.isOperationLegal(ISD::Constant, VT)))
7194       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7195   }
7196
7197   // (conv (conv x, t1), t2) -> (conv x, t2)
7198   if (N0.getOpcode() == ISD::BITCAST)
7199     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7200                        N0.getOperand(0));
7201
7202   // fold (conv (load x)) -> (load (conv*)x)
7203   // If the resultant load doesn't need a higher alignment than the original!
7204   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7205       // Do not change the width of a volatile load.
7206       !cast<LoadSDNode>(N0)->isVolatile() &&
7207       // Do not remove the cast if the types differ in endian layout.
7208       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7209           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7210       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7211       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7212     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7213     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7214         VT.getTypeForEVT(*DAG.getContext()));
7215     unsigned OrigAlign = LN0->getAlignment();
7216
7217     if (Align <= OrigAlign) {
7218       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7219                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7220                                  LN0->isVolatile(), LN0->isNonTemporal(),
7221                                  LN0->isInvariant(), OrigAlign,
7222                                  LN0->getAAInfo());
7223       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7224       return Load;
7225     }
7226   }
7227
7228   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7229   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7230   // This often reduces constant pool loads.
7231   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7232        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7233       N0.getNode()->hasOneUse() && VT.isInteger() &&
7234       !VT.isVector() && !N0.getValueType().isVector()) {
7235     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7236                                   N0.getOperand(0));
7237     AddToWorklist(NewConv.getNode());
7238
7239     SDLoc DL(N);
7240     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7241     if (N0.getOpcode() == ISD::FNEG)
7242       return DAG.getNode(ISD::XOR, DL, VT,
7243                          NewConv, DAG.getConstant(SignBit, DL, VT));
7244     assert(N0.getOpcode() == ISD::FABS);
7245     return DAG.getNode(ISD::AND, DL, VT,
7246                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7247   }
7248
7249   // fold (bitconvert (fcopysign cst, x)) ->
7250   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7251   // Note that we don't handle (copysign x, cst) because this can always be
7252   // folded to an fneg or fabs.
7253   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7254       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7255       VT.isInteger() && !VT.isVector()) {
7256     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7257     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7258     if (isTypeLegal(IntXVT)) {
7259       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7260                               IntXVT, N0.getOperand(1));
7261       AddToWorklist(X.getNode());
7262
7263       // If X has a different width than the result/lhs, sext it or truncate it.
7264       unsigned VTWidth = VT.getSizeInBits();
7265       if (OrigXWidth < VTWidth) {
7266         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7267         AddToWorklist(X.getNode());
7268       } else if (OrigXWidth > VTWidth) {
7269         // To get the sign bit in the right place, we have to shift it right
7270         // before truncating.
7271         SDLoc DL(X);
7272         X = DAG.getNode(ISD::SRL, DL,
7273                         X.getValueType(), X,
7274                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7275                                         X.getValueType()));
7276         AddToWorklist(X.getNode());
7277         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7278         AddToWorklist(X.getNode());
7279       }
7280
7281       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7282       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7283                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7284       AddToWorklist(X.getNode());
7285
7286       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7287                                 VT, N0.getOperand(0));
7288       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7289                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7290       AddToWorklist(Cst.getNode());
7291
7292       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7293     }
7294   }
7295
7296   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7297   if (N0.getOpcode() == ISD::BUILD_PAIR)
7298     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7299       return CombineLD;
7300
7301   // Remove double bitcasts from shuffles - this is often a legacy of
7302   // XformToShuffleWithZero being used to combine bitmaskings (of
7303   // float vectors bitcast to integer vectors) into shuffles.
7304   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7305   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7306       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7307       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7308       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7309     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7310
7311     // If operands are a bitcast, peek through if it casts the original VT.
7312     // If operands are a constant, just bitcast back to original VT.
7313     auto PeekThroughBitcast = [&](SDValue Op) {
7314       if (Op.getOpcode() == ISD::BITCAST &&
7315           Op.getOperand(0).getValueType() == VT)
7316         return SDValue(Op.getOperand(0));
7317       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7318           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7319         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7320       return SDValue();
7321     };
7322
7323     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7324     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7325     if (!(SV0 && SV1))
7326       return SDValue();
7327
7328     int MaskScale =
7329         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7330     SmallVector<int, 8> NewMask;
7331     for (int M : SVN->getMask())
7332       for (int i = 0; i != MaskScale; ++i)
7333         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7334
7335     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7336     if (!LegalMask) {
7337       std::swap(SV0, SV1);
7338       ShuffleVectorSDNode::commuteMask(NewMask);
7339       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7340     }
7341
7342     if (LegalMask)
7343       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7344   }
7345
7346   return SDValue();
7347 }
7348
7349 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7350   EVT VT = N->getValueType(0);
7351   return CombineConsecutiveLoads(N, VT);
7352 }
7353
7354 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7355 /// operands. DstEltVT indicates the destination element value type.
7356 SDValue DAGCombiner::
7357 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7358   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7359
7360   // If this is already the right type, we're done.
7361   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7362
7363   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7364   unsigned DstBitSize = DstEltVT.getSizeInBits();
7365
7366   // If this is a conversion of N elements of one type to N elements of another
7367   // type, convert each element.  This handles FP<->INT cases.
7368   if (SrcBitSize == DstBitSize) {
7369     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7370                               BV->getValueType(0).getVectorNumElements());
7371
7372     // Due to the FP element handling below calling this routine recursively,
7373     // we can end up with a scalar-to-vector node here.
7374     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7375       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7376                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7377                                      DstEltVT, BV->getOperand(0)));
7378
7379     SmallVector<SDValue, 8> Ops;
7380     for (SDValue Op : BV->op_values()) {
7381       // If the vector element type is not legal, the BUILD_VECTOR operands
7382       // are promoted and implicitly truncated.  Make that explicit here.
7383       if (Op.getValueType() != SrcEltVT)
7384         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7385       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7386                                 DstEltVT, Op));
7387       AddToWorklist(Ops.back().getNode());
7388     }
7389     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7390   }
7391
7392   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7393   // handle annoying details of growing/shrinking FP values, we convert them to
7394   // int first.
7395   if (SrcEltVT.isFloatingPoint()) {
7396     // Convert the input float vector to a int vector where the elements are the
7397     // same sizes.
7398     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7399     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7400     SrcEltVT = IntVT;
7401   }
7402
7403   // Now we know the input is an integer vector.  If the output is a FP type,
7404   // convert to integer first, then to FP of the right size.
7405   if (DstEltVT.isFloatingPoint()) {
7406     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7407     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7408
7409     // Next, convert to FP elements of the same size.
7410     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7411   }
7412
7413   SDLoc DL(BV);
7414
7415   // Okay, we know the src/dst types are both integers of differing types.
7416   // Handling growing first.
7417   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7418   if (SrcBitSize < DstBitSize) {
7419     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7420
7421     SmallVector<SDValue, 8> Ops;
7422     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7423          i += NumInputsPerOutput) {
7424       bool isLE = DAG.getDataLayout().isLittleEndian();
7425       APInt NewBits = APInt(DstBitSize, 0);
7426       bool EltIsUndef = true;
7427       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7428         // Shift the previously computed bits over.
7429         NewBits <<= SrcBitSize;
7430         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7431         if (Op.getOpcode() == ISD::UNDEF) continue;
7432         EltIsUndef = false;
7433
7434         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7435                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7436       }
7437
7438       if (EltIsUndef)
7439         Ops.push_back(DAG.getUNDEF(DstEltVT));
7440       else
7441         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7442     }
7443
7444     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7445     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7446   }
7447
7448   // Finally, this must be the case where we are shrinking elements: each input
7449   // turns into multiple outputs.
7450   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7451   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7452                             NumOutputsPerInput*BV->getNumOperands());
7453   SmallVector<SDValue, 8> Ops;
7454
7455   for (const SDValue &Op : BV->op_values()) {
7456     if (Op.getOpcode() == ISD::UNDEF) {
7457       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7458       continue;
7459     }
7460
7461     APInt OpVal = cast<ConstantSDNode>(Op)->
7462                   getAPIntValue().zextOrTrunc(SrcBitSize);
7463
7464     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7465       APInt ThisVal = OpVal.trunc(DstBitSize);
7466       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7467       OpVal = OpVal.lshr(DstBitSize);
7468     }
7469
7470     // For big endian targets, swap the order of the pieces of each element.
7471     if (DAG.getDataLayout().isBigEndian())
7472       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7473   }
7474
7475   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7476 }
7477
7478 /// Try to perform FMA combining on a given FADD node.
7479 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7480   SDValue N0 = N->getOperand(0);
7481   SDValue N1 = N->getOperand(1);
7482   EVT VT = N->getValueType(0);
7483   SDLoc SL(N);
7484
7485   const TargetOptions &Options = DAG.getTarget().Options;
7486   bool AllowFusion =
7487       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7488
7489   // Floating-point multiply-add with intermediate rounding.
7490   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7491
7492   // Floating-point multiply-add without intermediate rounding.
7493   bool HasFMA =
7494       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7495       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7496
7497   // No valid opcode, do not combine.
7498   if (!HasFMAD && !HasFMA)
7499     return SDValue();
7500
7501   // Always prefer FMAD to FMA for precision.
7502   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7503   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7504   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7505
7506   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7507   // prefer to fold the multiply with fewer uses.
7508   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7509       N1.getOpcode() == ISD::FMUL) {
7510     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7511       std::swap(N0, N1);
7512   }
7513
7514   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7515   if (N0.getOpcode() == ISD::FMUL &&
7516       (Aggressive || N0->hasOneUse())) {
7517     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518                        N0.getOperand(0), N0.getOperand(1), N1);
7519   }
7520
7521   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7522   // Note: Commutes FADD operands.
7523   if (N1.getOpcode() == ISD::FMUL &&
7524       (Aggressive || N1->hasOneUse())) {
7525     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7526                        N1.getOperand(0), N1.getOperand(1), N0);
7527   }
7528
7529   // Look through FP_EXTEND nodes to do more combining.
7530   if (AllowFusion && LookThroughFPExt) {
7531     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7532     if (N0.getOpcode() == ISD::FP_EXTEND) {
7533       SDValue N00 = N0.getOperand(0);
7534       if (N00.getOpcode() == ISD::FMUL)
7535         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7536                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7537                                        N00.getOperand(0)),
7538                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7539                                        N00.getOperand(1)), N1);
7540     }
7541
7542     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7543     // Note: Commutes FADD operands.
7544     if (N1.getOpcode() == ISD::FP_EXTEND) {
7545       SDValue N10 = N1.getOperand(0);
7546       if (N10.getOpcode() == ISD::FMUL)
7547         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7548                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7549                                        N10.getOperand(0)),
7550                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7551                                        N10.getOperand(1)), N0);
7552     }
7553   }
7554
7555   // More folding opportunities when target permits.
7556   if ((AllowFusion || HasFMAD)  && Aggressive) {
7557     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7558     if (N0.getOpcode() == PreferredFusedOpcode &&
7559         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7560       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7561                          N0.getOperand(0), N0.getOperand(1),
7562                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7563                                      N0.getOperand(2).getOperand(0),
7564                                      N0.getOperand(2).getOperand(1),
7565                                      N1));
7566     }
7567
7568     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7569     if (N1->getOpcode() == PreferredFusedOpcode &&
7570         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7571       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7572                          N1.getOperand(0), N1.getOperand(1),
7573                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7574                                      N1.getOperand(2).getOperand(0),
7575                                      N1.getOperand(2).getOperand(1),
7576                                      N0));
7577     }
7578
7579     if (AllowFusion && LookThroughFPExt) {
7580       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7581       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7582       auto FoldFAddFMAFPExtFMul = [&] (
7583           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7584         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7585                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7586                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7587                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7588                                        Z));
7589       };
7590       if (N0.getOpcode() == PreferredFusedOpcode) {
7591         SDValue N02 = N0.getOperand(2);
7592         if (N02.getOpcode() == ISD::FP_EXTEND) {
7593           SDValue N020 = N02.getOperand(0);
7594           if (N020.getOpcode() == ISD::FMUL)
7595             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7596                                         N020.getOperand(0), N020.getOperand(1),
7597                                         N1);
7598         }
7599       }
7600
7601       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7602       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7603       // FIXME: This turns two single-precision and one double-precision
7604       // operation into two double-precision operations, which might not be
7605       // interesting for all targets, especially GPUs.
7606       auto FoldFAddFPExtFMAFMul = [&] (
7607           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7608         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7609                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7610                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7611                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7612                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7613                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7614                                        Z));
7615       };
7616       if (N0.getOpcode() == ISD::FP_EXTEND) {
7617         SDValue N00 = N0.getOperand(0);
7618         if (N00.getOpcode() == PreferredFusedOpcode) {
7619           SDValue N002 = N00.getOperand(2);
7620           if (N002.getOpcode() == ISD::FMUL)
7621             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7622                                         N002.getOperand(0), N002.getOperand(1),
7623                                         N1);
7624         }
7625       }
7626
7627       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7628       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7629       if (N1.getOpcode() == PreferredFusedOpcode) {
7630         SDValue N12 = N1.getOperand(2);
7631         if (N12.getOpcode() == ISD::FP_EXTEND) {
7632           SDValue N120 = N12.getOperand(0);
7633           if (N120.getOpcode() == ISD::FMUL)
7634             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7635                                         N120.getOperand(0), N120.getOperand(1),
7636                                         N0);
7637         }
7638       }
7639
7640       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7641       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7642       // FIXME: This turns two single-precision and one double-precision
7643       // operation into two double-precision operations, which might not be
7644       // interesting for all targets, especially GPUs.
7645       if (N1.getOpcode() == ISD::FP_EXTEND) {
7646         SDValue N10 = N1.getOperand(0);
7647         if (N10.getOpcode() == PreferredFusedOpcode) {
7648           SDValue N102 = N10.getOperand(2);
7649           if (N102.getOpcode() == ISD::FMUL)
7650             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7651                                         N102.getOperand(0), N102.getOperand(1),
7652                                         N0);
7653         }
7654       }
7655     }
7656   }
7657
7658   return SDValue();
7659 }
7660
7661 /// Try to perform FMA combining on a given FSUB node.
7662 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7663   SDValue N0 = N->getOperand(0);
7664   SDValue N1 = N->getOperand(1);
7665   EVT VT = N->getValueType(0);
7666   SDLoc SL(N);
7667
7668   const TargetOptions &Options = DAG.getTarget().Options;
7669   bool AllowFusion =
7670       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7671
7672   // Floating-point multiply-add with intermediate rounding.
7673   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7674
7675   // Floating-point multiply-add without intermediate rounding.
7676   bool HasFMA =
7677       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7678       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7679
7680   // No valid opcode, do not combine.
7681   if (!HasFMAD && !HasFMA)
7682     return SDValue();
7683
7684   // Always prefer FMAD to FMA for precision.
7685   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7686   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7687   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7688
7689   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7690   if (N0.getOpcode() == ISD::FMUL &&
7691       (Aggressive || N0->hasOneUse())) {
7692     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7693                        N0.getOperand(0), N0.getOperand(1),
7694                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7695   }
7696
7697   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7698   // Note: Commutes FSUB operands.
7699   if (N1.getOpcode() == ISD::FMUL &&
7700       (Aggressive || N1->hasOneUse()))
7701     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7702                        DAG.getNode(ISD::FNEG, SL, VT,
7703                                    N1.getOperand(0)),
7704                        N1.getOperand(1), N0);
7705
7706   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7707   if (N0.getOpcode() == ISD::FNEG &&
7708       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7709       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7710     SDValue N00 = N0.getOperand(0).getOperand(0);
7711     SDValue N01 = N0.getOperand(0).getOperand(1);
7712     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7713                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7714                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7715   }
7716
7717   // Look through FP_EXTEND nodes to do more combining.
7718   if (AllowFusion && LookThroughFPExt) {
7719     // fold (fsub (fpext (fmul x, y)), z)
7720     //   -> (fma (fpext x), (fpext y), (fneg z))
7721     if (N0.getOpcode() == ISD::FP_EXTEND) {
7722       SDValue N00 = N0.getOperand(0);
7723       if (N00.getOpcode() == ISD::FMUL)
7724         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7725                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                        N00.getOperand(0)),
7727                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                        N00.getOperand(1)),
7729                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7730     }
7731
7732     // fold (fsub x, (fpext (fmul y, z)))
7733     //   -> (fma (fneg (fpext y)), (fpext z), x)
7734     // Note: Commutes FSUB operands.
7735     if (N1.getOpcode() == ISD::FP_EXTEND) {
7736       SDValue N10 = N1.getOperand(0);
7737       if (N10.getOpcode() == ISD::FMUL)
7738         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7739                            DAG.getNode(ISD::FNEG, SL, VT,
7740                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7741                                                    N10.getOperand(0))),
7742                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743                                        N10.getOperand(1)),
7744                            N0);
7745     }
7746
7747     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7748     //   -> (fneg (fma (fpext x), (fpext y), z))
7749     // Note: This could be removed with appropriate canonicalization of the
7750     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7751     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7752     // from implementing the canonicalization in visitFSUB.
7753     if (N0.getOpcode() == ISD::FP_EXTEND) {
7754       SDValue N00 = N0.getOperand(0);
7755       if (N00.getOpcode() == ISD::FNEG) {
7756         SDValue N000 = N00.getOperand(0);
7757         if (N000.getOpcode() == ISD::FMUL) {
7758           return DAG.getNode(ISD::FNEG, SL, VT,
7759                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7760                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7761                                                      N000.getOperand(0)),
7762                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763                                                      N000.getOperand(1)),
7764                                          N1));
7765         }
7766       }
7767     }
7768
7769     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7770     //   -> (fneg (fma (fpext x)), (fpext y), z)
7771     // Note: This could be removed with appropriate canonicalization of the
7772     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7773     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7774     // from implementing the canonicalization in visitFSUB.
7775     if (N0.getOpcode() == ISD::FNEG) {
7776       SDValue N00 = N0.getOperand(0);
7777       if (N00.getOpcode() == ISD::FP_EXTEND) {
7778         SDValue N000 = N00.getOperand(0);
7779         if (N000.getOpcode() == ISD::FMUL) {
7780           return DAG.getNode(ISD::FNEG, SL, VT,
7781                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7782                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7783                                                      N000.getOperand(0)),
7784                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7785                                                      N000.getOperand(1)),
7786                                          N1));
7787         }
7788       }
7789     }
7790
7791   }
7792
7793   // More folding opportunities when target permits.
7794   if ((AllowFusion || HasFMAD) && Aggressive) {
7795     // fold (fsub (fma x, y, (fmul u, v)), z)
7796     //   -> (fma x, y (fma u, v, (fneg z)))
7797     if (N0.getOpcode() == PreferredFusedOpcode &&
7798         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7799       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7800                          N0.getOperand(0), N0.getOperand(1),
7801                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                                      N0.getOperand(2).getOperand(0),
7803                                      N0.getOperand(2).getOperand(1),
7804                                      DAG.getNode(ISD::FNEG, SL, VT,
7805                                                  N1)));
7806     }
7807
7808     // fold (fsub x, (fma y, z, (fmul u, v)))
7809     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7810     if (N1.getOpcode() == PreferredFusedOpcode &&
7811         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7812       SDValue N20 = N1.getOperand(2).getOperand(0);
7813       SDValue N21 = N1.getOperand(2).getOperand(1);
7814       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7815                          DAG.getNode(ISD::FNEG, SL, VT,
7816                                      N1.getOperand(0)),
7817                          N1.getOperand(1),
7818                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7819                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7820
7821                                      N21, N0));
7822     }
7823
7824     if (AllowFusion && LookThroughFPExt) {
7825       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7826       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7827       if (N0.getOpcode() == PreferredFusedOpcode) {
7828         SDValue N02 = N0.getOperand(2);
7829         if (N02.getOpcode() == ISD::FP_EXTEND) {
7830           SDValue N020 = N02.getOperand(0);
7831           if (N020.getOpcode() == ISD::FMUL)
7832             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7833                                N0.getOperand(0), N0.getOperand(1),
7834                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7835                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7836                                                        N020.getOperand(0)),
7837                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7838                                                        N020.getOperand(1)),
7839                                            DAG.getNode(ISD::FNEG, SL, VT,
7840                                                        N1)));
7841         }
7842       }
7843
7844       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7845       //   -> (fma (fpext x), (fpext y),
7846       //           (fma (fpext u), (fpext v), (fneg z)))
7847       // FIXME: This turns two single-precision and one double-precision
7848       // operation into two double-precision operations, which might not be
7849       // interesting for all targets, especially GPUs.
7850       if (N0.getOpcode() == ISD::FP_EXTEND) {
7851         SDValue N00 = N0.getOperand(0);
7852         if (N00.getOpcode() == PreferredFusedOpcode) {
7853           SDValue N002 = N00.getOperand(2);
7854           if (N002.getOpcode() == ISD::FMUL)
7855             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7856                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7857                                            N00.getOperand(0)),
7858                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7859                                            N00.getOperand(1)),
7860                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7861                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7862                                                        N002.getOperand(0)),
7863                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7864                                                        N002.getOperand(1)),
7865                                            DAG.getNode(ISD::FNEG, SL, VT,
7866                                                        N1)));
7867         }
7868       }
7869
7870       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7871       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7872       if (N1.getOpcode() == PreferredFusedOpcode &&
7873         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7874         SDValue N120 = N1.getOperand(2).getOperand(0);
7875         if (N120.getOpcode() == ISD::FMUL) {
7876           SDValue N1200 = N120.getOperand(0);
7877           SDValue N1201 = N120.getOperand(1);
7878           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7879                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7880                              N1.getOperand(1),
7881                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7882                                          DAG.getNode(ISD::FNEG, SL, VT,
7883                                              DAG.getNode(ISD::FP_EXTEND, SL,
7884                                                          VT, N1200)),
7885                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7886                                                      N1201),
7887                                          N0));
7888         }
7889       }
7890
7891       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7892       //   -> (fma (fneg (fpext y)), (fpext z),
7893       //           (fma (fneg (fpext u)), (fpext v), x))
7894       // FIXME: This turns two single-precision and one double-precision
7895       // operation into two double-precision operations, which might not be
7896       // interesting for all targets, especially GPUs.
7897       if (N1.getOpcode() == ISD::FP_EXTEND &&
7898         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7899         SDValue N100 = N1.getOperand(0).getOperand(0);
7900         SDValue N101 = N1.getOperand(0).getOperand(1);
7901         SDValue N102 = N1.getOperand(0).getOperand(2);
7902         if (N102.getOpcode() == ISD::FMUL) {
7903           SDValue N1020 = N102.getOperand(0);
7904           SDValue N1021 = N102.getOperand(1);
7905           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7906                              DAG.getNode(ISD::FNEG, SL, VT,
7907                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7908                                                      N100)),
7909                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7910                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7911                                          DAG.getNode(ISD::FNEG, SL, VT,
7912                                              DAG.getNode(ISD::FP_EXTEND, SL,
7913                                                          VT, N1020)),
7914                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7915                                                      N1021),
7916                                          N0));
7917         }
7918       }
7919     }
7920   }
7921
7922   return SDValue();
7923 }
7924
7925 /// Try to perform FMA combining on a given FMUL node.
7926 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7927   SDValue N0 = N->getOperand(0);
7928   SDValue N1 = N->getOperand(1);
7929   EVT VT = N->getValueType(0);
7930   SDLoc SL(N);
7931
7932   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7933
7934   const TargetOptions &Options = DAG.getTarget().Options;
7935   bool AllowFusion =
7936       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7937
7938   // Floating-point multiply-add with intermediate rounding.
7939   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7940
7941   // Floating-point multiply-add without intermediate rounding.
7942   bool HasFMA =
7943       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7944       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7945
7946   // No valid opcode, do not combine.
7947   if (!HasFMAD && !HasFMA)
7948     return SDValue();
7949
7950   // Always prefer FMAD to FMA for precision.
7951   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7952   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7953
7954   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7955   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7956   auto FuseFADD = [&](SDValue X, SDValue Y) {
7957     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7958       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7959       if (XC1 && XC1->isExactlyValue(+1.0))
7960         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7961       if (XC1 && XC1->isExactlyValue(-1.0))
7962         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7963                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7964     }
7965     return SDValue();
7966   };
7967
7968   if (SDValue FMA = FuseFADD(N0, N1))
7969     return FMA;
7970   if (SDValue FMA = FuseFADD(N1, N0))
7971     return FMA;
7972
7973   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7974   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7975   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7976   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7977   auto FuseFSUB = [&](SDValue X, SDValue Y) {
7978     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7979       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
7980       if (XC0 && XC0->isExactlyValue(+1.0))
7981         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7982                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7983                            Y);
7984       if (XC0 && XC0->isExactlyValue(-1.0))
7985         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7986                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7987                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7988
7989       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7990       if (XC1 && XC1->isExactlyValue(+1.0))
7991         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7992                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7993       if (XC1 && XC1->isExactlyValue(-1.0))
7994         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7995     }
7996     return SDValue();
7997   };
7998
7999   if (SDValue FMA = FuseFSUB(N0, N1))
8000     return FMA;
8001   if (SDValue FMA = FuseFSUB(N1, N0))
8002     return FMA;
8003
8004   return SDValue();
8005 }
8006
8007 SDValue DAGCombiner::visitFADD(SDNode *N) {
8008   SDValue N0 = N->getOperand(0);
8009   SDValue N1 = N->getOperand(1);
8010   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8011   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8012   EVT VT = N->getValueType(0);
8013   SDLoc DL(N);
8014   const TargetOptions &Options = DAG.getTarget().Options;
8015   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8016
8017   // fold vector ops
8018   if (VT.isVector())
8019     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8020       return FoldedVOp;
8021
8022   // fold (fadd c1, c2) -> c1 + c2
8023   if (N0CFP && N1CFP)
8024     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8025
8026   // canonicalize constant to RHS
8027   if (N0CFP && !N1CFP)
8028     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8029
8030   // fold (fadd A, (fneg B)) -> (fsub A, B)
8031   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8032       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8033     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8034                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8035
8036   // fold (fadd (fneg A), B) -> (fsub B, A)
8037   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8038       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8039     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8040                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8041
8042   // If 'unsafe math' is enabled, fold lots of things.
8043   if (Options.UnsafeFPMath) {
8044     // No FP constant should be created after legalization as Instruction
8045     // Selection pass has a hard time dealing with FP constants.
8046     bool AllowNewConst = (Level < AfterLegalizeDAG);
8047
8048     // fold (fadd A, 0) -> A
8049     if (N1CFP && N1CFP->isZero())
8050       return N0;
8051
8052     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8053     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8054         isa<ConstantFPSDNode>(N0.getOperand(1)))
8055       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8056                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8057                                      Flags),
8058                          Flags);
8059
8060     // If allowed, fold (fadd (fneg x), x) -> 0.0
8061     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8062       return DAG.getConstantFP(0.0, DL, VT);
8063
8064     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8065     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8066       return DAG.getConstantFP(0.0, DL, VT);
8067
8068     // We can fold chains of FADD's of the same value into multiplications.
8069     // This transform is not safe in general because we are reducing the number
8070     // of rounding steps.
8071     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8072       if (N0.getOpcode() == ISD::FMUL) {
8073         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8074         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8075
8076         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8077         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8078           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
8079                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8080           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8081         }
8082
8083         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8084         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8085             N1.getOperand(0) == N1.getOperand(1) &&
8086             N0.getOperand(0) == N1.getOperand(0)) {
8087           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
8088                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8089           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8090         }
8091       }
8092
8093       if (N1.getOpcode() == ISD::FMUL) {
8094         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8095         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8096
8097         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8098         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8099           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8100                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8101           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8102         }
8103
8104         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8105         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8106             N0.getOperand(0) == N0.getOperand(1) &&
8107             N1.getOperand(0) == N0.getOperand(0)) {
8108           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8109                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8110           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8111         }
8112       }
8113
8114       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8115         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8116         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8117         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8118             (N0.getOperand(0) == N1)) {
8119           return DAG.getNode(ISD::FMUL, DL, VT,
8120                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8121         }
8122       }
8123
8124       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8125         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8126         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8127         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8128             N1.getOperand(0) == N0) {
8129           return DAG.getNode(ISD::FMUL, DL, VT,
8130                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8131         }
8132       }
8133
8134       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8135       if (AllowNewConst &&
8136           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8137           N0.getOperand(0) == N0.getOperand(1) &&
8138           N1.getOperand(0) == N1.getOperand(1) &&
8139           N0.getOperand(0) == N1.getOperand(0)) {
8140         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8141                            DAG.getConstantFP(4.0, DL, VT), Flags);
8142       }
8143     }
8144   } // enable-unsafe-fp-math
8145
8146   // FADD -> FMA combines:
8147   if (SDValue Fused = visitFADDForFMACombine(N)) {
8148     AddToWorklist(Fused.getNode());
8149     return Fused;
8150   }
8151
8152   return SDValue();
8153 }
8154
8155 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8156   SDValue N0 = N->getOperand(0);
8157   SDValue N1 = N->getOperand(1);
8158   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8159   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8160   EVT VT = N->getValueType(0);
8161   SDLoc dl(N);
8162   const TargetOptions &Options = DAG.getTarget().Options;
8163   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8164
8165   // fold vector ops
8166   if (VT.isVector())
8167     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8168       return FoldedVOp;
8169
8170   // fold (fsub c1, c2) -> c1-c2
8171   if (N0CFP && N1CFP)
8172     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8173
8174   // fold (fsub A, (fneg B)) -> (fadd A, B)
8175   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8176     return DAG.getNode(ISD::FADD, dl, VT, N0,
8177                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8178
8179   // If 'unsafe math' is enabled, fold lots of things.
8180   if (Options.UnsafeFPMath) {
8181     // (fsub A, 0) -> A
8182     if (N1CFP && N1CFP->isZero())
8183       return N0;
8184
8185     // (fsub 0, B) -> -B
8186     if (N0CFP && N0CFP->isZero()) {
8187       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8188         return GetNegatedExpression(N1, DAG, LegalOperations);
8189       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8190         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8191     }
8192
8193     // (fsub x, x) -> 0.0
8194     if (N0 == N1)
8195       return DAG.getConstantFP(0.0f, dl, VT);
8196
8197     // (fsub x, (fadd x, y)) -> (fneg y)
8198     // (fsub x, (fadd y, x)) -> (fneg y)
8199     if (N1.getOpcode() == ISD::FADD) {
8200       SDValue N10 = N1->getOperand(0);
8201       SDValue N11 = N1->getOperand(1);
8202
8203       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8204         return GetNegatedExpression(N11, DAG, LegalOperations);
8205
8206       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8207         return GetNegatedExpression(N10, DAG, LegalOperations);
8208     }
8209   }
8210
8211   // FSUB -> FMA combines:
8212   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8213     AddToWorklist(Fused.getNode());
8214     return Fused;
8215   }
8216
8217   return SDValue();
8218 }
8219
8220 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8221   SDValue N0 = N->getOperand(0);
8222   SDValue N1 = N->getOperand(1);
8223   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8224   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8225   EVT VT = N->getValueType(0);
8226   SDLoc DL(N);
8227   const TargetOptions &Options = DAG.getTarget().Options;
8228   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8229
8230   // fold vector ops
8231   if (VT.isVector()) {
8232     // This just handles C1 * C2 for vectors. Other vector folds are below.
8233     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8234       return FoldedVOp;
8235   }
8236
8237   // fold (fmul c1, c2) -> c1*c2
8238   if (N0CFP && N1CFP)
8239     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8240
8241   // canonicalize constant to RHS
8242   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8243      !isConstantFPBuildVectorOrConstantFP(N1))
8244     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8245
8246   // fold (fmul A, 1.0) -> A
8247   if (N1CFP && N1CFP->isExactlyValue(1.0))
8248     return N0;
8249
8250   if (Options.UnsafeFPMath) {
8251     // fold (fmul A, 0) -> 0
8252     if (N1CFP && N1CFP->isZero())
8253       return N1;
8254
8255     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8256     if (N0.getOpcode() == ISD::FMUL) {
8257       // Fold scalars or any vector constants (not just splats).
8258       // This fold is done in general by InstCombine, but extra fmul insts
8259       // may have been generated during lowering.
8260       SDValue N00 = N0.getOperand(0);
8261       SDValue N01 = N0.getOperand(1);
8262       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8263       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8264       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8265
8266       // Check 1: Make sure that the first operand of the inner multiply is NOT
8267       // a constant. Otherwise, we may induce infinite looping.
8268       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8269         // Check 2: Make sure that the second operand of the inner multiply and
8270         // the second operand of the outer multiply are constants.
8271         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8272             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8273           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8274           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8275         }
8276       }
8277     }
8278
8279     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8280     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8281     // during an early run of DAGCombiner can prevent folding with fmuls
8282     // inserted during lowering.
8283     if (N0.getOpcode() == ISD::FADD &&
8284         (N0.getOperand(0) == N0.getOperand(1)) &&
8285         N0.hasOneUse()) {
8286       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8287       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8288       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8289     }
8290   }
8291
8292   // fold (fmul X, 2.0) -> (fadd X, X)
8293   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8294     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8295
8296   // fold (fmul X, -1.0) -> (fneg X)
8297   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8298     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8299       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8300
8301   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8302   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8303     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8304       // Both can be negated for free, check to see if at least one is cheaper
8305       // negated.
8306       if (LHSNeg == 2 || RHSNeg == 2)
8307         return DAG.getNode(ISD::FMUL, DL, VT,
8308                            GetNegatedExpression(N0, DAG, LegalOperations),
8309                            GetNegatedExpression(N1, DAG, LegalOperations),
8310                            Flags);
8311     }
8312   }
8313
8314   // FMUL -> FMA combines:
8315   if (SDValue Fused = visitFMULForFMACombine(N)) {
8316     AddToWorklist(Fused.getNode());
8317     return Fused;
8318   }
8319
8320   return SDValue();
8321 }
8322
8323 SDValue DAGCombiner::visitFMA(SDNode *N) {
8324   SDValue N0 = N->getOperand(0);
8325   SDValue N1 = N->getOperand(1);
8326   SDValue N2 = N->getOperand(2);
8327   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8328   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8329   EVT VT = N->getValueType(0);
8330   SDLoc dl(N);
8331   const TargetOptions &Options = DAG.getTarget().Options;
8332
8333   // Constant fold FMA.
8334   if (isa<ConstantFPSDNode>(N0) &&
8335       isa<ConstantFPSDNode>(N1) &&
8336       isa<ConstantFPSDNode>(N2)) {
8337     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8338   }
8339
8340   if (Options.UnsafeFPMath) {
8341     if (N0CFP && N0CFP->isZero())
8342       return N2;
8343     if (N1CFP && N1CFP->isZero())
8344       return N2;
8345   }
8346   // TODO: The FMA node should have flags that propagate to these nodes.
8347   if (N0CFP && N0CFP->isExactlyValue(1.0))
8348     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8349   if (N1CFP && N1CFP->isExactlyValue(1.0))
8350     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8351
8352   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8353   if (N0CFP && !N1CFP)
8354     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8355
8356   // TODO: FMA nodes should have flags that propagate to the created nodes.
8357   // For now, create a Flags object for use with all unsafe math transforms.
8358   SDNodeFlags Flags;
8359   Flags.setUnsafeAlgebra(true);
8360
8361   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8362   if (Options.UnsafeFPMath && N1CFP &&
8363       N2.getOpcode() == ISD::FMUL &&
8364       N0 == N2.getOperand(0) &&
8365       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8366     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8367                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8368                                    &Flags), &Flags);
8369   }
8370
8371
8372   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8373   if (Options.UnsafeFPMath &&
8374       N0.getOpcode() == ISD::FMUL && N1CFP &&
8375       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8376     return DAG.getNode(ISD::FMA, dl, VT,
8377                        N0.getOperand(0),
8378                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8379                                    &Flags),
8380                        N2);
8381   }
8382
8383   // (fma x, 1, y) -> (fadd x, y)
8384   // (fma x, -1, y) -> (fadd (fneg x), y)
8385   if (N1CFP) {
8386     if (N1CFP->isExactlyValue(1.0))
8387       // TODO: The FMA node should have flags that propagate to this node.
8388       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8389
8390     if (N1CFP->isExactlyValue(-1.0) &&
8391         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8392       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8393       AddToWorklist(RHSNeg.getNode());
8394       // TODO: The FMA node should have flags that propagate to this node.
8395       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8396     }
8397   }
8398
8399   // (fma x, c, x) -> (fmul x, (c+1))
8400   if (Options.UnsafeFPMath && N1CFP && N0 == N2) {
8401     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8402                        DAG.getNode(ISD::FADD, dl, VT,
8403                                    N1, DAG.getConstantFP(1.0, dl, VT),
8404                                    &Flags), &Flags);
8405   }
8406   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8407   if (Options.UnsafeFPMath && N1CFP &&
8408       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8409     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8410                        DAG.getNode(ISD::FADD, dl, VT,
8411                                    N1, DAG.getConstantFP(-1.0, dl, VT),
8412                                    &Flags), &Flags);
8413   }
8414
8415   return SDValue();
8416 }
8417
8418 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8419 // reciprocal.
8420 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8421 // Notice that this is not always beneficial. One reason is different target
8422 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8423 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8424 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8425 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8426   if (!DAG.getTarget().Options.UnsafeFPMath)
8427     return SDValue();
8428
8429   // Skip if current node is a reciprocal.
8430   SDValue N0 = N->getOperand(0);
8431   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8432   if (N0CFP && N0CFP->isExactlyValue(1.0))
8433     return SDValue();
8434
8435   // Exit early if the target does not want this transform or if there can't
8436   // possibly be enough uses of the divisor to make the transform worthwhile.
8437   SDValue N1 = N->getOperand(1);
8438   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8439   if (!MinUses || N1->use_size() < MinUses)
8440     return SDValue();
8441
8442   // Find all FDIV users of the same divisor.
8443   // Use a set because duplicates may be present in the user list.
8444   SetVector<SDNode *> Users;
8445   for (auto *U : N1->uses())
8446     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8447       Users.insert(U);
8448
8449   // Now that we have the actual number of divisor uses, make sure it meets
8450   // the minimum threshold specified by the target.
8451   if (Users.size() < MinUses)
8452     return SDValue();
8453
8454   EVT VT = N->getValueType(0);
8455   SDLoc DL(N);
8456   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8457   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8458   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8459
8460   // Dividend / Divisor -> Dividend * Reciprocal
8461   for (auto *U : Users) {
8462     SDValue Dividend = U->getOperand(0);
8463     if (Dividend != FPOne) {
8464       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8465                                     Reciprocal, Flags);
8466       CombineTo(U, NewNode);
8467     } else if (U != Reciprocal.getNode()) {
8468       // In the absence of fast-math-flags, this user node is always the
8469       // same node as Reciprocal, but with FMF they may be different nodes.
8470       CombineTo(U, Reciprocal);
8471     }
8472   }
8473   return SDValue(N, 0);  // N was replaced.
8474 }
8475
8476 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8477   SDValue N0 = N->getOperand(0);
8478   SDValue N1 = N->getOperand(1);
8479   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8480   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8481   EVT VT = N->getValueType(0);
8482   SDLoc DL(N);
8483   const TargetOptions &Options = DAG.getTarget().Options;
8484   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8485
8486   // fold vector ops
8487   if (VT.isVector())
8488     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8489       return FoldedVOp;
8490
8491   // fold (fdiv c1, c2) -> c1/c2
8492   if (N0CFP && N1CFP)
8493     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8494
8495   if (Options.UnsafeFPMath) {
8496     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8497     if (N1CFP) {
8498       // Compute the reciprocal 1.0 / c2.
8499       APFloat N1APF = N1CFP->getValueAPF();
8500       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8501       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8502       // Only do the transform if the reciprocal is a legal fp immediate that
8503       // isn't too nasty (eg NaN, denormal, ...).
8504       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8505           (!LegalOperations ||
8506            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8507            // backend)... we should handle this gracefully after Legalize.
8508            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8509            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8510            TLI.isFPImmLegal(Recip, VT)))
8511         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8512                            DAG.getConstantFP(Recip, DL, VT), Flags);
8513     }
8514
8515     // If this FDIV is part of a reciprocal square root, it may be folded
8516     // into a target-specific square root estimate instruction.
8517     if (N1.getOpcode() == ISD::FSQRT) {
8518       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8519         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8520       }
8521     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8522                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8523       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8524                                           Flags)) {
8525         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8526         AddToWorklist(RV.getNode());
8527         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8528       }
8529     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8530                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8531       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8532                                           Flags)) {
8533         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8534         AddToWorklist(RV.getNode());
8535         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8536       }
8537     } else if (N1.getOpcode() == ISD::FMUL) {
8538       // Look through an FMUL. Even though this won't remove the FDIV directly,
8539       // it's still worthwhile to get rid of the FSQRT if possible.
8540       SDValue SqrtOp;
8541       SDValue OtherOp;
8542       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8543         SqrtOp = N1.getOperand(0);
8544         OtherOp = N1.getOperand(1);
8545       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8546         SqrtOp = N1.getOperand(1);
8547         OtherOp = N1.getOperand(0);
8548       }
8549       if (SqrtOp.getNode()) {
8550         // We found a FSQRT, so try to make this fold:
8551         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8552         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8553           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8554           AddToWorklist(RV.getNode());
8555           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8556         }
8557       }
8558     }
8559
8560     // Fold into a reciprocal estimate and multiply instead of a real divide.
8561     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8562       AddToWorklist(RV.getNode());
8563       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8564     }
8565   }
8566
8567   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8568   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8569     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8570       // Both can be negated for free, check to see if at least one is cheaper
8571       // negated.
8572       if (LHSNeg == 2 || RHSNeg == 2)
8573         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8574                            GetNegatedExpression(N0, DAG, LegalOperations),
8575                            GetNegatedExpression(N1, DAG, LegalOperations),
8576                            Flags);
8577     }
8578   }
8579
8580   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8581     return CombineRepeatedDivisors;
8582
8583   return SDValue();
8584 }
8585
8586 SDValue DAGCombiner::visitFREM(SDNode *N) {
8587   SDValue N0 = N->getOperand(0);
8588   SDValue N1 = N->getOperand(1);
8589   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8590   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8591   EVT VT = N->getValueType(0);
8592
8593   // fold (frem c1, c2) -> fmod(c1,c2)
8594   if (N0CFP && N1CFP)
8595     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8596                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8597
8598   return SDValue();
8599 }
8600
8601 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8602   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8603     return SDValue();
8604
8605   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8606   // For now, create a Flags object for use with all unsafe math transforms.
8607   SDNodeFlags Flags;
8608   Flags.setUnsafeAlgebra(true);
8609
8610   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8611   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8612   if (!RV)
8613     return SDValue();
8614
8615   EVT VT = RV.getValueType();
8616   SDLoc DL(N);
8617   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8618   AddToWorklist(RV.getNode());
8619
8620   // Unfortunately, RV is now NaN if the input was exactly 0.
8621   // Select out this case and force the answer to 0.
8622   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8623   EVT CCVT = getSetCCResultType(VT);
8624   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8625   AddToWorklist(ZeroCmp.getNode());
8626   AddToWorklist(RV.getNode());
8627
8628   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8629                      ZeroCmp, Zero, RV);
8630 }
8631
8632 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8633   SDValue N0 = N->getOperand(0);
8634   SDValue N1 = N->getOperand(1);
8635   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8636   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8637   EVT VT = N->getValueType(0);
8638
8639   if (N0CFP && N1CFP)  // Constant fold
8640     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8641
8642   if (N1CFP) {
8643     const APFloat& V = N1CFP->getValueAPF();
8644     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8645     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8646     if (!V.isNegative()) {
8647       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8648         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8649     } else {
8650       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8651         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8652                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8653     }
8654   }
8655
8656   // copysign(fabs(x), y) -> copysign(x, y)
8657   // copysign(fneg(x), y) -> copysign(x, y)
8658   // copysign(copysign(x,z), y) -> copysign(x, y)
8659   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8660       N0.getOpcode() == ISD::FCOPYSIGN)
8661     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8662                        N0.getOperand(0), N1);
8663
8664   // copysign(x, abs(y)) -> abs(x)
8665   if (N1.getOpcode() == ISD::FABS)
8666     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8667
8668   // copysign(x, copysign(y,z)) -> copysign(x, z)
8669   if (N1.getOpcode() == ISD::FCOPYSIGN)
8670     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8671                        N0, N1.getOperand(1));
8672
8673   // copysign(x, fp_extend(y)) -> copysign(x, y)
8674   // copysign(x, fp_round(y)) -> copysign(x, y)
8675   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8676     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8677                        N0, N1.getOperand(0));
8678
8679   return SDValue();
8680 }
8681
8682 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8683   SDValue N0 = N->getOperand(0);
8684   EVT VT = N->getValueType(0);
8685   EVT OpVT = N0.getValueType();
8686
8687   // fold (sint_to_fp c1) -> c1fp
8688   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8689       // ...but only if the target supports immediate floating-point values
8690       (!LegalOperations ||
8691        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8692     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8693
8694   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8695   // but UINT_TO_FP is legal on this target, try to convert.
8696   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8697       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8698     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8699     if (DAG.SignBitIsZero(N0))
8700       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8701   }
8702
8703   // The next optimizations are desirable only if SELECT_CC can be lowered.
8704   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8705     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8706     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8707         !VT.isVector() &&
8708         (!LegalOperations ||
8709          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8710       SDLoc DL(N);
8711       SDValue Ops[] =
8712         { N0.getOperand(0), N0.getOperand(1),
8713           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8714           N0.getOperand(2) };
8715       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8716     }
8717
8718     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8719     //      (select_cc x, y, 1.0, 0.0,, cc)
8720     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8721         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8722         (!LegalOperations ||
8723          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8724       SDLoc DL(N);
8725       SDValue Ops[] =
8726         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8727           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8728           N0.getOperand(0).getOperand(2) };
8729       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8730     }
8731   }
8732
8733   return SDValue();
8734 }
8735
8736 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8737   SDValue N0 = N->getOperand(0);
8738   EVT VT = N->getValueType(0);
8739   EVT OpVT = N0.getValueType();
8740
8741   // fold (uint_to_fp c1) -> c1fp
8742   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8743       // ...but only if the target supports immediate floating-point values
8744       (!LegalOperations ||
8745        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8746     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8747
8748   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8749   // but SINT_TO_FP is legal on this target, try to convert.
8750   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8751       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8752     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8753     if (DAG.SignBitIsZero(N0))
8754       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8755   }
8756
8757   // The next optimizations are desirable only if SELECT_CC can be lowered.
8758   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8759     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8760
8761     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8762         (!LegalOperations ||
8763          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8764       SDLoc DL(N);
8765       SDValue Ops[] =
8766         { N0.getOperand(0), N0.getOperand(1),
8767           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8768           N0.getOperand(2) };
8769       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8770     }
8771   }
8772
8773   return SDValue();
8774 }
8775
8776 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8777 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8778   SDValue N0 = N->getOperand(0);
8779   EVT VT = N->getValueType(0);
8780
8781   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8782     return SDValue();
8783
8784   SDValue Src = N0.getOperand(0);
8785   EVT SrcVT = Src.getValueType();
8786   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8787   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8788
8789   // We can safely assume the conversion won't overflow the output range,
8790   // because (for example) (uint8_t)18293.f is undefined behavior.
8791
8792   // Since we can assume the conversion won't overflow, our decision as to
8793   // whether the input will fit in the float should depend on the minimum
8794   // of the input range and output range.
8795
8796   // This means this is also safe for a signed input and unsigned output, since
8797   // a negative input would lead to undefined behavior.
8798   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8799   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8800   unsigned ActualSize = std::min(InputSize, OutputSize);
8801   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8802
8803   // We can only fold away the float conversion if the input range can be
8804   // represented exactly in the float range.
8805   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8806     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8807       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8808                                                        : ISD::ZERO_EXTEND;
8809       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8810     }
8811     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8812       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8813     if (SrcVT == VT)
8814       return Src;
8815     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8816   }
8817   return SDValue();
8818 }
8819
8820 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8821   SDValue N0 = N->getOperand(0);
8822   EVT VT = N->getValueType(0);
8823
8824   // fold (fp_to_sint c1fp) -> c1
8825   if (isConstantFPBuildVectorOrConstantFP(N0))
8826     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8827
8828   return FoldIntToFPToInt(N, DAG);
8829 }
8830
8831 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8832   SDValue N0 = N->getOperand(0);
8833   EVT VT = N->getValueType(0);
8834
8835   // fold (fp_to_uint c1fp) -> c1
8836   if (isConstantFPBuildVectorOrConstantFP(N0))
8837     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8838
8839   return FoldIntToFPToInt(N, DAG);
8840 }
8841
8842 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8843   SDValue N0 = N->getOperand(0);
8844   SDValue N1 = N->getOperand(1);
8845   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8846   EVT VT = N->getValueType(0);
8847
8848   // fold (fp_round c1fp) -> c1fp
8849   if (N0CFP)
8850     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8851
8852   // fold (fp_round (fp_extend x)) -> x
8853   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8854     return N0.getOperand(0);
8855
8856   // fold (fp_round (fp_round x)) -> (fp_round x)
8857   if (N0.getOpcode() == ISD::FP_ROUND) {
8858     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8859     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8860     // If the first fp_round isn't a value preserving truncation, it might
8861     // introduce a tie in the second fp_round, that wouldn't occur in the
8862     // single-step fp_round we want to fold to.
8863     // In other words, double rounding isn't the same as rounding.
8864     // Also, this is a value preserving truncation iff both fp_round's are.
8865     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8866       SDLoc DL(N);
8867       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8868                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8869     }
8870   }
8871
8872   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8873   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8874     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8875                               N0.getOperand(0), N1);
8876     AddToWorklist(Tmp.getNode());
8877     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8878                        Tmp, N0.getOperand(1));
8879   }
8880
8881   return SDValue();
8882 }
8883
8884 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8885   SDValue N0 = N->getOperand(0);
8886   EVT VT = N->getValueType(0);
8887   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8888   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8889
8890   // fold (fp_round_inreg c1fp) -> c1fp
8891   if (N0CFP && isTypeLegal(EVT)) {
8892     SDLoc DL(N);
8893     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8894     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8895   }
8896
8897   return SDValue();
8898 }
8899
8900 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8901   SDValue N0 = N->getOperand(0);
8902   EVT VT = N->getValueType(0);
8903
8904   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8905   if (N->hasOneUse() &&
8906       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8907     return SDValue();
8908
8909   // fold (fp_extend c1fp) -> c1fp
8910   if (isConstantFPBuildVectorOrConstantFP(N0))
8911     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8912
8913   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8914   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8915       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8916     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8917
8918   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8919   // value of X.
8920   if (N0.getOpcode() == ISD::FP_ROUND
8921       && N0.getNode()->getConstantOperandVal(1) == 1) {
8922     SDValue In = N0.getOperand(0);
8923     if (In.getValueType() == VT) return In;
8924     if (VT.bitsLT(In.getValueType()))
8925       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8926                          In, N0.getOperand(1));
8927     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8928   }
8929
8930   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8931   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8932        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8933     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8934     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8935                                      LN0->getChain(),
8936                                      LN0->getBasePtr(), N0.getValueType(),
8937                                      LN0->getMemOperand());
8938     CombineTo(N, ExtLoad);
8939     CombineTo(N0.getNode(),
8940               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8941                           N0.getValueType(), ExtLoad,
8942                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8943               ExtLoad.getValue(1));
8944     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8945   }
8946
8947   return SDValue();
8948 }
8949
8950 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8951   SDValue N0 = N->getOperand(0);
8952   EVT VT = N->getValueType(0);
8953
8954   // fold (fceil c1) -> fceil(c1)
8955   if (isConstantFPBuildVectorOrConstantFP(N0))
8956     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8957
8958   return SDValue();
8959 }
8960
8961 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8962   SDValue N0 = N->getOperand(0);
8963   EVT VT = N->getValueType(0);
8964
8965   // fold (ftrunc c1) -> ftrunc(c1)
8966   if (isConstantFPBuildVectorOrConstantFP(N0))
8967     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8968
8969   return SDValue();
8970 }
8971
8972 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8973   SDValue N0 = N->getOperand(0);
8974   EVT VT = N->getValueType(0);
8975
8976   // fold (ffloor c1) -> ffloor(c1)
8977   if (isConstantFPBuildVectorOrConstantFP(N0))
8978     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8979
8980   return SDValue();
8981 }
8982
8983 // FIXME: FNEG and FABS have a lot in common; refactor.
8984 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8985   SDValue N0 = N->getOperand(0);
8986   EVT VT = N->getValueType(0);
8987
8988   // Constant fold FNEG.
8989   if (isConstantFPBuildVectorOrConstantFP(N0))
8990     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8991
8992   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8993                          &DAG.getTarget().Options))
8994     return GetNegatedExpression(N0, DAG, LegalOperations);
8995
8996   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8997   // constant pool values.
8998   if (!TLI.isFNegFree(VT) &&
8999       N0.getOpcode() == ISD::BITCAST &&
9000       N0.getNode()->hasOneUse()) {
9001     SDValue Int = N0.getOperand(0);
9002     EVT IntVT = Int.getValueType();
9003     if (IntVT.isInteger() && !IntVT.isVector()) {
9004       APInt SignMask;
9005       if (N0.getValueType().isVector()) {
9006         // For a vector, get a mask such as 0x80... per scalar element
9007         // and splat it.
9008         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9009         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9010       } else {
9011         // For a scalar, just generate 0x80...
9012         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9013       }
9014       SDLoc DL0(N0);
9015       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9016                         DAG.getConstant(SignMask, DL0, IntVT));
9017       AddToWorklist(Int.getNode());
9018       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9019     }
9020   }
9021
9022   // (fneg (fmul c, x)) -> (fmul -c, x)
9023   if (N0.getOpcode() == ISD::FMUL &&
9024       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9025     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9026     if (CFP1) {
9027       APFloat CVal = CFP1->getValueAPF();
9028       CVal.changeSign();
9029       if (Level >= AfterLegalizeDAG &&
9030           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9031            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9032         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9033                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9034                                        N0.getOperand(1)),
9035                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9036     }
9037   }
9038
9039   return SDValue();
9040 }
9041
9042 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9043   SDValue N0 = N->getOperand(0);
9044   SDValue N1 = N->getOperand(1);
9045   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9046   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9047
9048   if (N0CFP && N1CFP) {
9049     const APFloat &C0 = N0CFP->getValueAPF();
9050     const APFloat &C1 = N1CFP->getValueAPF();
9051     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
9052   }
9053
9054   if (N0CFP) {
9055     EVT VT = N->getValueType(0);
9056     // Canonicalize to constant on RHS.
9057     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9058   }
9059
9060   return SDValue();
9061 }
9062
9063 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9064   SDValue N0 = N->getOperand(0);
9065   SDValue N1 = N->getOperand(1);
9066   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9067   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9068
9069   if (N0CFP && N1CFP) {
9070     const APFloat &C0 = N0CFP->getValueAPF();
9071     const APFloat &C1 = N1CFP->getValueAPF();
9072     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
9073   }
9074
9075   if (N0CFP) {
9076     EVT VT = N->getValueType(0);
9077     // Canonicalize to constant on RHS.
9078     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9079   }
9080
9081   return SDValue();
9082 }
9083
9084 SDValue DAGCombiner::visitFABS(SDNode *N) {
9085   SDValue N0 = N->getOperand(0);
9086   EVT VT = N->getValueType(0);
9087
9088   // fold (fabs c1) -> fabs(c1)
9089   if (isConstantFPBuildVectorOrConstantFP(N0))
9090     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9091
9092   // fold (fabs (fabs x)) -> (fabs x)
9093   if (N0.getOpcode() == ISD::FABS)
9094     return N->getOperand(0);
9095
9096   // fold (fabs (fneg x)) -> (fabs x)
9097   // fold (fabs (fcopysign x, y)) -> (fabs x)
9098   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9099     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9100
9101   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9102   // constant pool values.
9103   if (!TLI.isFAbsFree(VT) &&
9104       N0.getOpcode() == ISD::BITCAST &&
9105       N0.getNode()->hasOneUse()) {
9106     SDValue Int = N0.getOperand(0);
9107     EVT IntVT = Int.getValueType();
9108     if (IntVT.isInteger() && !IntVT.isVector()) {
9109       APInt SignMask;
9110       if (N0.getValueType().isVector()) {
9111         // For a vector, get a mask such as 0x7f... per scalar element
9112         // and splat it.
9113         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9114         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9115       } else {
9116         // For a scalar, just generate 0x7f...
9117         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9118       }
9119       SDLoc DL(N0);
9120       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9121                         DAG.getConstant(SignMask, DL, IntVT));
9122       AddToWorklist(Int.getNode());
9123       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9124     }
9125   }
9126
9127   return SDValue();
9128 }
9129
9130 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9131   SDValue Chain = N->getOperand(0);
9132   SDValue N1 = N->getOperand(1);
9133   SDValue N2 = N->getOperand(2);
9134
9135   // If N is a constant we could fold this into a fallthrough or unconditional
9136   // branch. However that doesn't happen very often in normal code, because
9137   // Instcombine/SimplifyCFG should have handled the available opportunities.
9138   // If we did this folding here, it would be necessary to update the
9139   // MachineBasicBlock CFG, which is awkward.
9140
9141   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9142   // on the target.
9143   if (N1.getOpcode() == ISD::SETCC &&
9144       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9145                                    N1.getOperand(0).getValueType())) {
9146     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9147                        Chain, N1.getOperand(2),
9148                        N1.getOperand(0), N1.getOperand(1), N2);
9149   }
9150
9151   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9152       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9153        (N1.getOperand(0).hasOneUse() &&
9154         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9155     SDNode *Trunc = nullptr;
9156     if (N1.getOpcode() == ISD::TRUNCATE) {
9157       // Look pass the truncate.
9158       Trunc = N1.getNode();
9159       N1 = N1.getOperand(0);
9160     }
9161
9162     // Match this pattern so that we can generate simpler code:
9163     //
9164     //   %a = ...
9165     //   %b = and i32 %a, 2
9166     //   %c = srl i32 %b, 1
9167     //   brcond i32 %c ...
9168     //
9169     // into
9170     //
9171     //   %a = ...
9172     //   %b = and i32 %a, 2
9173     //   %c = setcc eq %b, 0
9174     //   brcond %c ...
9175     //
9176     // This applies only when the AND constant value has one bit set and the
9177     // SRL constant is equal to the log2 of the AND constant. The back-end is
9178     // smart enough to convert the result into a TEST/JMP sequence.
9179     SDValue Op0 = N1.getOperand(0);
9180     SDValue Op1 = N1.getOperand(1);
9181
9182     if (Op0.getOpcode() == ISD::AND &&
9183         Op1.getOpcode() == ISD::Constant) {
9184       SDValue AndOp1 = Op0.getOperand(1);
9185
9186       if (AndOp1.getOpcode() == ISD::Constant) {
9187         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9188
9189         if (AndConst.isPowerOf2() &&
9190             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9191           SDLoc DL(N);
9192           SDValue SetCC =
9193             DAG.getSetCC(DL,
9194                          getSetCCResultType(Op0.getValueType()),
9195                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9196                          ISD::SETNE);
9197
9198           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9199                                           MVT::Other, Chain, SetCC, N2);
9200           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9201           // will convert it back to (X & C1) >> C2.
9202           CombineTo(N, NewBRCond, false);
9203           // Truncate is dead.
9204           if (Trunc)
9205             deleteAndRecombine(Trunc);
9206           // Replace the uses of SRL with SETCC
9207           WorklistRemover DeadNodes(*this);
9208           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9209           deleteAndRecombine(N1.getNode());
9210           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9211         }
9212       }
9213     }
9214
9215     if (Trunc)
9216       // Restore N1 if the above transformation doesn't match.
9217       N1 = N->getOperand(1);
9218   }
9219
9220   // Transform br(xor(x, y)) -> br(x != y)
9221   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9222   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9223     SDNode *TheXor = N1.getNode();
9224     SDValue Op0 = TheXor->getOperand(0);
9225     SDValue Op1 = TheXor->getOperand(1);
9226     if (Op0.getOpcode() == Op1.getOpcode()) {
9227       // Avoid missing important xor optimizations.
9228       if (SDValue Tmp = visitXOR(TheXor)) {
9229         if (Tmp.getNode() != TheXor) {
9230           DEBUG(dbgs() << "\nReplacing.8 ";
9231                 TheXor->dump(&DAG);
9232                 dbgs() << "\nWith: ";
9233                 Tmp.getNode()->dump(&DAG);
9234                 dbgs() << '\n');
9235           WorklistRemover DeadNodes(*this);
9236           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9237           deleteAndRecombine(TheXor);
9238           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9239                              MVT::Other, Chain, Tmp, N2);
9240         }
9241
9242         // visitXOR has changed XOR's operands or replaced the XOR completely,
9243         // bail out.
9244         return SDValue(N, 0);
9245       }
9246     }
9247
9248     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9249       bool Equal = false;
9250       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9251           Op0.getOpcode() == ISD::XOR) {
9252         TheXor = Op0.getNode();
9253         Equal = true;
9254       }
9255
9256       EVT SetCCVT = N1.getValueType();
9257       if (LegalTypes)
9258         SetCCVT = getSetCCResultType(SetCCVT);
9259       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9260                                    SetCCVT,
9261                                    Op0, Op1,
9262                                    Equal ? ISD::SETEQ : ISD::SETNE);
9263       // Replace the uses of XOR with SETCC
9264       WorklistRemover DeadNodes(*this);
9265       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9266       deleteAndRecombine(N1.getNode());
9267       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9268                          MVT::Other, Chain, SetCC, N2);
9269     }
9270   }
9271
9272   return SDValue();
9273 }
9274
9275 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9276 //
9277 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9278   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9279   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9280
9281   // If N is a constant we could fold this into a fallthrough or unconditional
9282   // branch. However that doesn't happen very often in normal code, because
9283   // Instcombine/SimplifyCFG should have handled the available opportunities.
9284   // If we did this folding here, it would be necessary to update the
9285   // MachineBasicBlock CFG, which is awkward.
9286
9287   // Use SimplifySetCC to simplify SETCC's.
9288   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9289                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9290                                false);
9291   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9292
9293   // fold to a simpler setcc
9294   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9295     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9296                        N->getOperand(0), Simp.getOperand(2),
9297                        Simp.getOperand(0), Simp.getOperand(1),
9298                        N->getOperand(4));
9299
9300   return SDValue();
9301 }
9302
9303 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9304 /// and that N may be folded in the load / store addressing mode.
9305 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9306                                     SelectionDAG &DAG,
9307                                     const TargetLowering &TLI) {
9308   EVT VT;
9309   unsigned AS;
9310
9311   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9312     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9313       return false;
9314     VT = LD->getMemoryVT();
9315     AS = LD->getAddressSpace();
9316   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9317     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9318       return false;
9319     VT = ST->getMemoryVT();
9320     AS = ST->getAddressSpace();
9321   } else
9322     return false;
9323
9324   TargetLowering::AddrMode AM;
9325   if (N->getOpcode() == ISD::ADD) {
9326     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9327     if (Offset)
9328       // [reg +/- imm]
9329       AM.BaseOffs = Offset->getSExtValue();
9330     else
9331       // [reg +/- reg]
9332       AM.Scale = 1;
9333   } else if (N->getOpcode() == ISD::SUB) {
9334     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9335     if (Offset)
9336       // [reg +/- imm]
9337       AM.BaseOffs = -Offset->getSExtValue();
9338     else
9339       // [reg +/- reg]
9340       AM.Scale = 1;
9341   } else
9342     return false;
9343
9344   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9345                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9346 }
9347
9348 /// Try turning a load/store into a pre-indexed load/store when the base
9349 /// pointer is an add or subtract and it has other uses besides the load/store.
9350 /// After the transformation, the new indexed load/store has effectively folded
9351 /// the add/subtract in and all of its other uses are redirected to the
9352 /// new load/store.
9353 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9354   if (Level < AfterLegalizeDAG)
9355     return false;
9356
9357   bool isLoad = true;
9358   SDValue Ptr;
9359   EVT VT;
9360   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9361     if (LD->isIndexed())
9362       return false;
9363     VT = LD->getMemoryVT();
9364     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9365         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9366       return false;
9367     Ptr = LD->getBasePtr();
9368   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9369     if (ST->isIndexed())
9370       return false;
9371     VT = ST->getMemoryVT();
9372     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9373         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9374       return false;
9375     Ptr = ST->getBasePtr();
9376     isLoad = false;
9377   } else {
9378     return false;
9379   }
9380
9381   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9382   // out.  There is no reason to make this a preinc/predec.
9383   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9384       Ptr.getNode()->hasOneUse())
9385     return false;
9386
9387   // Ask the target to do addressing mode selection.
9388   SDValue BasePtr;
9389   SDValue Offset;
9390   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9391   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9392     return false;
9393
9394   // Backends without true r+i pre-indexed forms may need to pass a
9395   // constant base with a variable offset so that constant coercion
9396   // will work with the patterns in canonical form.
9397   bool Swapped = false;
9398   if (isa<ConstantSDNode>(BasePtr)) {
9399     std::swap(BasePtr, Offset);
9400     Swapped = true;
9401   }
9402
9403   // Don't create a indexed load / store with zero offset.
9404   if (isNullConstant(Offset))
9405     return false;
9406
9407   // Try turning it into a pre-indexed load / store except when:
9408   // 1) The new base ptr is a frame index.
9409   // 2) If N is a store and the new base ptr is either the same as or is a
9410   //    predecessor of the value being stored.
9411   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9412   //    that would create a cycle.
9413   // 4) All uses are load / store ops that use it as old base ptr.
9414
9415   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9416   // (plus the implicit offset) to a register to preinc anyway.
9417   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9418     return false;
9419
9420   // Check #2.
9421   if (!isLoad) {
9422     SDValue Val = cast<StoreSDNode>(N)->getValue();
9423     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9424       return false;
9425   }
9426
9427   // If the offset is a constant, there may be other adds of constants that
9428   // can be folded with this one. We should do this to avoid having to keep
9429   // a copy of the original base pointer.
9430   SmallVector<SDNode *, 16> OtherUses;
9431   if (isa<ConstantSDNode>(Offset))
9432     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9433                               UE = BasePtr.getNode()->use_end();
9434          UI != UE; ++UI) {
9435       SDUse &Use = UI.getUse();
9436       // Skip the use that is Ptr and uses of other results from BasePtr's
9437       // node (important for nodes that return multiple results).
9438       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9439         continue;
9440
9441       if (Use.getUser()->isPredecessorOf(N))
9442         continue;
9443
9444       if (Use.getUser()->getOpcode() != ISD::ADD &&
9445           Use.getUser()->getOpcode() != ISD::SUB) {
9446         OtherUses.clear();
9447         break;
9448       }
9449
9450       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9451       if (!isa<ConstantSDNode>(Op1)) {
9452         OtherUses.clear();
9453         break;
9454       }
9455
9456       // FIXME: In some cases, we can be smarter about this.
9457       if (Op1.getValueType() != Offset.getValueType()) {
9458         OtherUses.clear();
9459         break;
9460       }
9461
9462       OtherUses.push_back(Use.getUser());
9463     }
9464
9465   if (Swapped)
9466     std::swap(BasePtr, Offset);
9467
9468   // Now check for #3 and #4.
9469   bool RealUse = false;
9470
9471   // Caches for hasPredecessorHelper
9472   SmallPtrSet<const SDNode *, 32> Visited;
9473   SmallVector<const SDNode *, 16> Worklist;
9474
9475   for (SDNode *Use : Ptr.getNode()->uses()) {
9476     if (Use == N)
9477       continue;
9478     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9479       return false;
9480
9481     // If Ptr may be folded in addressing mode of other use, then it's
9482     // not profitable to do this transformation.
9483     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9484       RealUse = true;
9485   }
9486
9487   if (!RealUse)
9488     return false;
9489
9490   SDValue Result;
9491   if (isLoad)
9492     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9493                                 BasePtr, Offset, AM);
9494   else
9495     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9496                                  BasePtr, Offset, AM);
9497   ++PreIndexedNodes;
9498   ++NodesCombined;
9499   DEBUG(dbgs() << "\nReplacing.4 ";
9500         N->dump(&DAG);
9501         dbgs() << "\nWith: ";
9502         Result.getNode()->dump(&DAG);
9503         dbgs() << '\n');
9504   WorklistRemover DeadNodes(*this);
9505   if (isLoad) {
9506     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9507     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9508   } else {
9509     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9510   }
9511
9512   // Finally, since the node is now dead, remove it from the graph.
9513   deleteAndRecombine(N);
9514
9515   if (Swapped)
9516     std::swap(BasePtr, Offset);
9517
9518   // Replace other uses of BasePtr that can be updated to use Ptr
9519   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9520     unsigned OffsetIdx = 1;
9521     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9522       OffsetIdx = 0;
9523     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9524            BasePtr.getNode() && "Expected BasePtr operand");
9525
9526     // We need to replace ptr0 in the following expression:
9527     //   x0 * offset0 + y0 * ptr0 = t0
9528     // knowing that
9529     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9530     //
9531     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9532     // indexed load/store and the expresion that needs to be re-written.
9533     //
9534     // Therefore, we have:
9535     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9536
9537     ConstantSDNode *CN =
9538       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9539     int X0, X1, Y0, Y1;
9540     APInt Offset0 = CN->getAPIntValue();
9541     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9542
9543     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9544     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9545     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9546     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9547
9548     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9549
9550     APInt CNV = Offset0;
9551     if (X0 < 0) CNV = -CNV;
9552     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9553     else CNV = CNV - Offset1;
9554
9555     SDLoc DL(OtherUses[i]);
9556
9557     // We can now generate the new expression.
9558     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9559     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9560
9561     SDValue NewUse = DAG.getNode(Opcode,
9562                                  DL,
9563                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9564     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9565     deleteAndRecombine(OtherUses[i]);
9566   }
9567
9568   // Replace the uses of Ptr with uses of the updated base value.
9569   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9570   deleteAndRecombine(Ptr.getNode());
9571
9572   return true;
9573 }
9574
9575 /// Try to combine a load/store with a add/sub of the base pointer node into a
9576 /// post-indexed load/store. The transformation folded the add/subtract into the
9577 /// new indexed load/store effectively and all of its uses are redirected to the
9578 /// new load/store.
9579 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9580   if (Level < AfterLegalizeDAG)
9581     return false;
9582
9583   bool isLoad = true;
9584   SDValue Ptr;
9585   EVT VT;
9586   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9587     if (LD->isIndexed())
9588       return false;
9589     VT = LD->getMemoryVT();
9590     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9591         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9592       return false;
9593     Ptr = LD->getBasePtr();
9594   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9595     if (ST->isIndexed())
9596       return false;
9597     VT = ST->getMemoryVT();
9598     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9599         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9600       return false;
9601     Ptr = ST->getBasePtr();
9602     isLoad = false;
9603   } else {
9604     return false;
9605   }
9606
9607   if (Ptr.getNode()->hasOneUse())
9608     return false;
9609
9610   for (SDNode *Op : Ptr.getNode()->uses()) {
9611     if (Op == N ||
9612         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9613       continue;
9614
9615     SDValue BasePtr;
9616     SDValue Offset;
9617     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9618     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9619       // Don't create a indexed load / store with zero offset.
9620       if (isNullConstant(Offset))
9621         continue;
9622
9623       // Try turning it into a post-indexed load / store except when
9624       // 1) All uses are load / store ops that use it as base ptr (and
9625       //    it may be folded as addressing mmode).
9626       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9627       //    nor a successor of N. Otherwise, if Op is folded that would
9628       //    create a cycle.
9629
9630       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9631         continue;
9632
9633       // Check for #1.
9634       bool TryNext = false;
9635       for (SDNode *Use : BasePtr.getNode()->uses()) {
9636         if (Use == Ptr.getNode())
9637           continue;
9638
9639         // If all the uses are load / store addresses, then don't do the
9640         // transformation.
9641         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9642           bool RealUse = false;
9643           for (SDNode *UseUse : Use->uses()) {
9644             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9645               RealUse = true;
9646           }
9647
9648           if (!RealUse) {
9649             TryNext = true;
9650             break;
9651           }
9652         }
9653       }
9654
9655       if (TryNext)
9656         continue;
9657
9658       // Check for #2
9659       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9660         SDValue Result = isLoad
9661           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9662                                BasePtr, Offset, AM)
9663           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9664                                 BasePtr, Offset, AM);
9665         ++PostIndexedNodes;
9666         ++NodesCombined;
9667         DEBUG(dbgs() << "\nReplacing.5 ";
9668               N->dump(&DAG);
9669               dbgs() << "\nWith: ";
9670               Result.getNode()->dump(&DAG);
9671               dbgs() << '\n');
9672         WorklistRemover DeadNodes(*this);
9673         if (isLoad) {
9674           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9675           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9676         } else {
9677           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9678         }
9679
9680         // Finally, since the node is now dead, remove it from the graph.
9681         deleteAndRecombine(N);
9682
9683         // Replace the uses of Use with uses of the updated base value.
9684         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9685                                       Result.getValue(isLoad ? 1 : 0));
9686         deleteAndRecombine(Op);
9687         return true;
9688       }
9689     }
9690   }
9691
9692   return false;
9693 }
9694
9695 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9696 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9697   ISD::MemIndexedMode AM = LD->getAddressingMode();
9698   assert(AM != ISD::UNINDEXED);
9699   SDValue BP = LD->getOperand(1);
9700   SDValue Inc = LD->getOperand(2);
9701
9702   // Some backends use TargetConstants for load offsets, but don't expect
9703   // TargetConstants in general ADD nodes. We can convert these constants into
9704   // regular Constants (if the constant is not opaque).
9705   assert((Inc.getOpcode() != ISD::TargetConstant ||
9706           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9707          "Cannot split out indexing using opaque target constants");
9708   if (Inc.getOpcode() == ISD::TargetConstant) {
9709     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9710     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9711                           ConstInc->getValueType(0));
9712   }
9713
9714   unsigned Opc =
9715       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9716   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9717 }
9718
9719 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9720   LoadSDNode *LD  = cast<LoadSDNode>(N);
9721   SDValue Chain = LD->getChain();
9722   SDValue Ptr   = LD->getBasePtr();
9723
9724   // If load is not volatile and there are no uses of the loaded value (and
9725   // the updated indexed value in case of indexed loads), change uses of the
9726   // chain value into uses of the chain input (i.e. delete the dead load).
9727   if (!LD->isVolatile()) {
9728     if (N->getValueType(1) == MVT::Other) {
9729       // Unindexed loads.
9730       if (!N->hasAnyUseOfValue(0)) {
9731         // It's not safe to use the two value CombineTo variant here. e.g.
9732         // v1, chain2 = load chain1, loc
9733         // v2, chain3 = load chain2, loc
9734         // v3         = add v2, c
9735         // Now we replace use of chain2 with chain1.  This makes the second load
9736         // isomorphic to the one we are deleting, and thus makes this load live.
9737         DEBUG(dbgs() << "\nReplacing.6 ";
9738               N->dump(&DAG);
9739               dbgs() << "\nWith chain: ";
9740               Chain.getNode()->dump(&DAG);
9741               dbgs() << "\n");
9742         WorklistRemover DeadNodes(*this);
9743         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9744
9745         if (N->use_empty())
9746           deleteAndRecombine(N);
9747
9748         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9749       }
9750     } else {
9751       // Indexed loads.
9752       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9753
9754       // If this load has an opaque TargetConstant offset, then we cannot split
9755       // the indexing into an add/sub directly (that TargetConstant may not be
9756       // valid for a different type of node, and we cannot convert an opaque
9757       // target constant into a regular constant).
9758       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9759                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9760
9761       if (!N->hasAnyUseOfValue(0) &&
9762           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9763         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9764         SDValue Index;
9765         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9766           Index = SplitIndexingFromLoad(LD);
9767           // Try to fold the base pointer arithmetic into subsequent loads and
9768           // stores.
9769           AddUsersToWorklist(N);
9770         } else
9771           Index = DAG.getUNDEF(N->getValueType(1));
9772         DEBUG(dbgs() << "\nReplacing.7 ";
9773               N->dump(&DAG);
9774               dbgs() << "\nWith: ";
9775               Undef.getNode()->dump(&DAG);
9776               dbgs() << " and 2 other values\n");
9777         WorklistRemover DeadNodes(*this);
9778         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9779         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9780         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9781         deleteAndRecombine(N);
9782         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9783       }
9784     }
9785   }
9786
9787   // If this load is directly stored, replace the load value with the stored
9788   // value.
9789   // TODO: Handle store large -> read small portion.
9790   // TODO: Handle TRUNCSTORE/LOADEXT
9791   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9792     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9793       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9794       if (PrevST->getBasePtr() == Ptr &&
9795           PrevST->getValue().getValueType() == N->getValueType(0))
9796       return CombineTo(N, Chain.getOperand(1), Chain);
9797     }
9798   }
9799
9800   // Try to infer better alignment information than the load already has.
9801   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9802     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9803       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9804         SDValue NewLoad =
9805                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9806                               LD->getValueType(0),
9807                               Chain, Ptr, LD->getPointerInfo(),
9808                               LD->getMemoryVT(),
9809                               LD->isVolatile(), LD->isNonTemporal(),
9810                               LD->isInvariant(), Align, LD->getAAInfo());
9811         if (NewLoad.getNode() != N)
9812           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9813       }
9814     }
9815   }
9816
9817   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9818                                                   : DAG.getSubtarget().useAA();
9819 #ifndef NDEBUG
9820   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9821       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9822     UseAA = false;
9823 #endif
9824   if (UseAA && LD->isUnindexed()) {
9825     // Walk up chain skipping non-aliasing memory nodes.
9826     SDValue BetterChain = FindBetterChain(N, Chain);
9827
9828     // If there is a better chain.
9829     if (Chain != BetterChain) {
9830       SDValue ReplLoad;
9831
9832       // Replace the chain to void dependency.
9833       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9834         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9835                                BetterChain, Ptr, LD->getMemOperand());
9836       } else {
9837         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9838                                   LD->getValueType(0),
9839                                   BetterChain, Ptr, LD->getMemoryVT(),
9840                                   LD->getMemOperand());
9841       }
9842
9843       // Create token factor to keep old chain connected.
9844       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9845                                   MVT::Other, Chain, ReplLoad.getValue(1));
9846
9847       // Make sure the new and old chains are cleaned up.
9848       AddToWorklist(Token.getNode());
9849
9850       // Replace uses with load result and token factor. Don't add users
9851       // to work list.
9852       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9853     }
9854   }
9855
9856   // Try transforming N to an indexed load.
9857   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9858     return SDValue(N, 0);
9859
9860   // Try to slice up N to more direct loads if the slices are mapped to
9861   // different register banks or pairing can take place.
9862   if (SliceUpLoad(N))
9863     return SDValue(N, 0);
9864
9865   return SDValue();
9866 }
9867
9868 namespace {
9869 /// \brief Helper structure used to slice a load in smaller loads.
9870 /// Basically a slice is obtained from the following sequence:
9871 /// Origin = load Ty1, Base
9872 /// Shift = srl Ty1 Origin, CstTy Amount
9873 /// Inst = trunc Shift to Ty2
9874 ///
9875 /// Then, it will be rewriten into:
9876 /// Slice = load SliceTy, Base + SliceOffset
9877 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9878 ///
9879 /// SliceTy is deduced from the number of bits that are actually used to
9880 /// build Inst.
9881 struct LoadedSlice {
9882   /// \brief Helper structure used to compute the cost of a slice.
9883   struct Cost {
9884     /// Are we optimizing for code size.
9885     bool ForCodeSize;
9886     /// Various cost.
9887     unsigned Loads;
9888     unsigned Truncates;
9889     unsigned CrossRegisterBanksCopies;
9890     unsigned ZExts;
9891     unsigned Shift;
9892
9893     Cost(bool ForCodeSize = false)
9894         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9895           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9896
9897     /// \brief Get the cost of one isolated slice.
9898     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9899         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9900           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9901       EVT TruncType = LS.Inst->getValueType(0);
9902       EVT LoadedType = LS.getLoadedType();
9903       if (TruncType != LoadedType &&
9904           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9905         ZExts = 1;
9906     }
9907
9908     /// \brief Account for slicing gain in the current cost.
9909     /// Slicing provide a few gains like removing a shift or a
9910     /// truncate. This method allows to grow the cost of the original
9911     /// load with the gain from this slice.
9912     void addSliceGain(const LoadedSlice &LS) {
9913       // Each slice saves a truncate.
9914       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9915       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9916                               LS.Inst->getValueType(0)))
9917         ++Truncates;
9918       // If there is a shift amount, this slice gets rid of it.
9919       if (LS.Shift)
9920         ++Shift;
9921       // If this slice can merge a cross register bank copy, account for it.
9922       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9923         ++CrossRegisterBanksCopies;
9924     }
9925
9926     Cost &operator+=(const Cost &RHS) {
9927       Loads += RHS.Loads;
9928       Truncates += RHS.Truncates;
9929       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9930       ZExts += RHS.ZExts;
9931       Shift += RHS.Shift;
9932       return *this;
9933     }
9934
9935     bool operator==(const Cost &RHS) const {
9936       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9937              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9938              ZExts == RHS.ZExts && Shift == RHS.Shift;
9939     }
9940
9941     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9942
9943     bool operator<(const Cost &RHS) const {
9944       // Assume cross register banks copies are as expensive as loads.
9945       // FIXME: Do we want some more target hooks?
9946       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9947       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9948       // Unless we are optimizing for code size, consider the
9949       // expensive operation first.
9950       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9951         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9952       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9953              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9954     }
9955
9956     bool operator>(const Cost &RHS) const { return RHS < *this; }
9957
9958     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9959
9960     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9961   };
9962   // The last instruction that represent the slice. This should be a
9963   // truncate instruction.
9964   SDNode *Inst;
9965   // The original load instruction.
9966   LoadSDNode *Origin;
9967   // The right shift amount in bits from the original load.
9968   unsigned Shift;
9969   // The DAG from which Origin came from.
9970   // This is used to get some contextual information about legal types, etc.
9971   SelectionDAG *DAG;
9972
9973   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9974               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9975       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9976
9977   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9978   /// \return Result is \p BitWidth and has used bits set to 1 and
9979   ///         not used bits set to 0.
9980   APInt getUsedBits() const {
9981     // Reproduce the trunc(lshr) sequence:
9982     // - Start from the truncated value.
9983     // - Zero extend to the desired bit width.
9984     // - Shift left.
9985     assert(Origin && "No original load to compare against.");
9986     unsigned BitWidth = Origin->getValueSizeInBits(0);
9987     assert(Inst && "This slice is not bound to an instruction");
9988     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9989            "Extracted slice is bigger than the whole type!");
9990     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9991     UsedBits.setAllBits();
9992     UsedBits = UsedBits.zext(BitWidth);
9993     UsedBits <<= Shift;
9994     return UsedBits;
9995   }
9996
9997   /// \brief Get the size of the slice to be loaded in bytes.
9998   unsigned getLoadedSize() const {
9999     unsigned SliceSize = getUsedBits().countPopulation();
10000     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10001     return SliceSize / 8;
10002   }
10003
10004   /// \brief Get the type that will be loaded for this slice.
10005   /// Note: This may not be the final type for the slice.
10006   EVT getLoadedType() const {
10007     assert(DAG && "Missing context");
10008     LLVMContext &Ctxt = *DAG->getContext();
10009     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10010   }
10011
10012   /// \brief Get the alignment of the load used for this slice.
10013   unsigned getAlignment() const {
10014     unsigned Alignment = Origin->getAlignment();
10015     unsigned Offset = getOffsetFromBase();
10016     if (Offset != 0)
10017       Alignment = MinAlign(Alignment, Alignment + Offset);
10018     return Alignment;
10019   }
10020
10021   /// \brief Check if this slice can be rewritten with legal operations.
10022   bool isLegal() const {
10023     // An invalid slice is not legal.
10024     if (!Origin || !Inst || !DAG)
10025       return false;
10026
10027     // Offsets are for indexed load only, we do not handle that.
10028     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10029       return false;
10030
10031     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10032
10033     // Check that the type is legal.
10034     EVT SliceType = getLoadedType();
10035     if (!TLI.isTypeLegal(SliceType))
10036       return false;
10037
10038     // Check that the load is legal for this type.
10039     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10040       return false;
10041
10042     // Check that the offset can be computed.
10043     // 1. Check its type.
10044     EVT PtrType = Origin->getBasePtr().getValueType();
10045     if (PtrType == MVT::Untyped || PtrType.isExtended())
10046       return false;
10047
10048     // 2. Check that it fits in the immediate.
10049     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10050       return false;
10051
10052     // 3. Check that the computation is legal.
10053     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10054       return false;
10055
10056     // Check that the zext is legal if it needs one.
10057     EVT TruncateType = Inst->getValueType(0);
10058     if (TruncateType != SliceType &&
10059         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10060       return false;
10061
10062     return true;
10063   }
10064
10065   /// \brief Get the offset in bytes of this slice in the original chunk of
10066   /// bits.
10067   /// \pre DAG != nullptr.
10068   uint64_t getOffsetFromBase() const {
10069     assert(DAG && "Missing context.");
10070     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10071     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10072     uint64_t Offset = Shift / 8;
10073     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10074     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10075            "The size of the original loaded type is not a multiple of a"
10076            " byte.");
10077     // If Offset is bigger than TySizeInBytes, it means we are loading all
10078     // zeros. This should have been optimized before in the process.
10079     assert(TySizeInBytes > Offset &&
10080            "Invalid shift amount for given loaded size");
10081     if (IsBigEndian)
10082       Offset = TySizeInBytes - Offset - getLoadedSize();
10083     return Offset;
10084   }
10085
10086   /// \brief Generate the sequence of instructions to load the slice
10087   /// represented by this object and redirect the uses of this slice to
10088   /// this new sequence of instructions.
10089   /// \pre this->Inst && this->Origin are valid Instructions and this
10090   /// object passed the legal check: LoadedSlice::isLegal returned true.
10091   /// \return The last instruction of the sequence used to load the slice.
10092   SDValue loadSlice() const {
10093     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10094     const SDValue &OldBaseAddr = Origin->getBasePtr();
10095     SDValue BaseAddr = OldBaseAddr;
10096     // Get the offset in that chunk of bytes w.r.t. the endianess.
10097     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10098     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10099     if (Offset) {
10100       // BaseAddr = BaseAddr + Offset.
10101       EVT ArithType = BaseAddr.getValueType();
10102       SDLoc DL(Origin);
10103       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10104                               DAG->getConstant(Offset, DL, ArithType));
10105     }
10106
10107     // Create the type of the loaded slice according to its size.
10108     EVT SliceType = getLoadedType();
10109
10110     // Create the load for the slice.
10111     SDValue LastInst = DAG->getLoad(
10112         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10113         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10114         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10115     // If the final type is not the same as the loaded type, this means that
10116     // we have to pad with zero. Create a zero extend for that.
10117     EVT FinalType = Inst->getValueType(0);
10118     if (SliceType != FinalType)
10119       LastInst =
10120           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10121     return LastInst;
10122   }
10123
10124   /// \brief Check if this slice can be merged with an expensive cross register
10125   /// bank copy. E.g.,
10126   /// i = load i32
10127   /// f = bitcast i32 i to float
10128   bool canMergeExpensiveCrossRegisterBankCopy() const {
10129     if (!Inst || !Inst->hasOneUse())
10130       return false;
10131     SDNode *Use = *Inst->use_begin();
10132     if (Use->getOpcode() != ISD::BITCAST)
10133       return false;
10134     assert(DAG && "Missing context");
10135     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10136     EVT ResVT = Use->getValueType(0);
10137     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10138     const TargetRegisterClass *ArgRC =
10139         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10140     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10141       return false;
10142
10143     // At this point, we know that we perform a cross-register-bank copy.
10144     // Check if it is expensive.
10145     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10146     // Assume bitcasts are cheap, unless both register classes do not
10147     // explicitly share a common sub class.
10148     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10149       return false;
10150
10151     // Check if it will be merged with the load.
10152     // 1. Check the alignment constraint.
10153     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10154         ResVT.getTypeForEVT(*DAG->getContext()));
10155
10156     if (RequiredAlignment > getAlignment())
10157       return false;
10158
10159     // 2. Check that the load is a legal operation for that type.
10160     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10161       return false;
10162
10163     // 3. Check that we do not have a zext in the way.
10164     if (Inst->getValueType(0) != getLoadedType())
10165       return false;
10166
10167     return true;
10168   }
10169 };
10170 }
10171
10172 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10173 /// \p UsedBits looks like 0..0 1..1 0..0.
10174 static bool areUsedBitsDense(const APInt &UsedBits) {
10175   // If all the bits are one, this is dense!
10176   if (UsedBits.isAllOnesValue())
10177     return true;
10178
10179   // Get rid of the unused bits on the right.
10180   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10181   // Get rid of the unused bits on the left.
10182   if (NarrowedUsedBits.countLeadingZeros())
10183     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10184   // Check that the chunk of bits is completely used.
10185   return NarrowedUsedBits.isAllOnesValue();
10186 }
10187
10188 /// \brief Check whether or not \p First and \p Second are next to each other
10189 /// in memory. This means that there is no hole between the bits loaded
10190 /// by \p First and the bits loaded by \p Second.
10191 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10192                                      const LoadedSlice &Second) {
10193   assert(First.Origin == Second.Origin && First.Origin &&
10194          "Unable to match different memory origins.");
10195   APInt UsedBits = First.getUsedBits();
10196   assert((UsedBits & Second.getUsedBits()) == 0 &&
10197          "Slices are not supposed to overlap.");
10198   UsedBits |= Second.getUsedBits();
10199   return areUsedBitsDense(UsedBits);
10200 }
10201
10202 /// \brief Adjust the \p GlobalLSCost according to the target
10203 /// paring capabilities and the layout of the slices.
10204 /// \pre \p GlobalLSCost should account for at least as many loads as
10205 /// there is in the slices in \p LoadedSlices.
10206 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10207                                  LoadedSlice::Cost &GlobalLSCost) {
10208   unsigned NumberOfSlices = LoadedSlices.size();
10209   // If there is less than 2 elements, no pairing is possible.
10210   if (NumberOfSlices < 2)
10211     return;
10212
10213   // Sort the slices so that elements that are likely to be next to each
10214   // other in memory are next to each other in the list.
10215   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10216             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10217     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10218     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10219   });
10220   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10221   // First (resp. Second) is the first (resp. Second) potentially candidate
10222   // to be placed in a paired load.
10223   const LoadedSlice *First = nullptr;
10224   const LoadedSlice *Second = nullptr;
10225   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10226                 // Set the beginning of the pair.
10227                                                            First = Second) {
10228
10229     Second = &LoadedSlices[CurrSlice];
10230
10231     // If First is NULL, it means we start a new pair.
10232     // Get to the next slice.
10233     if (!First)
10234       continue;
10235
10236     EVT LoadedType = First->getLoadedType();
10237
10238     // If the types of the slices are different, we cannot pair them.
10239     if (LoadedType != Second->getLoadedType())
10240       continue;
10241
10242     // Check if the target supplies paired loads for this type.
10243     unsigned RequiredAlignment = 0;
10244     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10245       // move to the next pair, this type is hopeless.
10246       Second = nullptr;
10247       continue;
10248     }
10249     // Check if we meet the alignment requirement.
10250     if (RequiredAlignment > First->getAlignment())
10251       continue;
10252
10253     // Check that both loads are next to each other in memory.
10254     if (!areSlicesNextToEachOther(*First, *Second))
10255       continue;
10256
10257     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10258     --GlobalLSCost.Loads;
10259     // Move to the next pair.
10260     Second = nullptr;
10261   }
10262 }
10263
10264 /// \brief Check the profitability of all involved LoadedSlice.
10265 /// Currently, it is considered profitable if there is exactly two
10266 /// involved slices (1) which are (2) next to each other in memory, and
10267 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10268 ///
10269 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10270 /// the elements themselves.
10271 ///
10272 /// FIXME: When the cost model will be mature enough, we can relax
10273 /// constraints (1) and (2).
10274 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10275                                 const APInt &UsedBits, bool ForCodeSize) {
10276   unsigned NumberOfSlices = LoadedSlices.size();
10277   if (StressLoadSlicing)
10278     return NumberOfSlices > 1;
10279
10280   // Check (1).
10281   if (NumberOfSlices != 2)
10282     return false;
10283
10284   // Check (2).
10285   if (!areUsedBitsDense(UsedBits))
10286     return false;
10287
10288   // Check (3).
10289   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10290   // The original code has one big load.
10291   OrigCost.Loads = 1;
10292   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10293     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10294     // Accumulate the cost of all the slices.
10295     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10296     GlobalSlicingCost += SliceCost;
10297
10298     // Account as cost in the original configuration the gain obtained
10299     // with the current slices.
10300     OrigCost.addSliceGain(LS);
10301   }
10302
10303   // If the target supports paired load, adjust the cost accordingly.
10304   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10305   return OrigCost > GlobalSlicingCost;
10306 }
10307
10308 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10309 /// operations, split it in the various pieces being extracted.
10310 ///
10311 /// This sort of thing is introduced by SROA.
10312 /// This slicing takes care not to insert overlapping loads.
10313 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10314 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10315   if (Level < AfterLegalizeDAG)
10316     return false;
10317
10318   LoadSDNode *LD = cast<LoadSDNode>(N);
10319   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10320       !LD->getValueType(0).isInteger())
10321     return false;
10322
10323   // Keep track of already used bits to detect overlapping values.
10324   // In that case, we will just abort the transformation.
10325   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10326
10327   SmallVector<LoadedSlice, 4> LoadedSlices;
10328
10329   // Check if this load is used as several smaller chunks of bits.
10330   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10331   // of computation for each trunc.
10332   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10333        UI != UIEnd; ++UI) {
10334     // Skip the uses of the chain.
10335     if (UI.getUse().getResNo() != 0)
10336       continue;
10337
10338     SDNode *User = *UI;
10339     unsigned Shift = 0;
10340
10341     // Check if this is a trunc(lshr).
10342     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10343         isa<ConstantSDNode>(User->getOperand(1))) {
10344       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10345       User = *User->use_begin();
10346     }
10347
10348     // At this point, User is a Truncate, iff we encountered, trunc or
10349     // trunc(lshr).
10350     if (User->getOpcode() != ISD::TRUNCATE)
10351       return false;
10352
10353     // The width of the type must be a power of 2 and greater than 8-bits.
10354     // Otherwise the load cannot be represented in LLVM IR.
10355     // Moreover, if we shifted with a non-8-bits multiple, the slice
10356     // will be across several bytes. We do not support that.
10357     unsigned Width = User->getValueSizeInBits(0);
10358     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10359       return 0;
10360
10361     // Build the slice for this chain of computations.
10362     LoadedSlice LS(User, LD, Shift, &DAG);
10363     APInt CurrentUsedBits = LS.getUsedBits();
10364
10365     // Check if this slice overlaps with another.
10366     if ((CurrentUsedBits & UsedBits) != 0)
10367       return false;
10368     // Update the bits used globally.
10369     UsedBits |= CurrentUsedBits;
10370
10371     // Check if the new slice would be legal.
10372     if (!LS.isLegal())
10373       return false;
10374
10375     // Record the slice.
10376     LoadedSlices.push_back(LS);
10377   }
10378
10379   // Abort slicing if it does not seem to be profitable.
10380   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10381     return false;
10382
10383   ++SlicedLoads;
10384
10385   // Rewrite each chain to use an independent load.
10386   // By construction, each chain can be represented by a unique load.
10387
10388   // Prepare the argument for the new token factor for all the slices.
10389   SmallVector<SDValue, 8> ArgChains;
10390   for (SmallVectorImpl<LoadedSlice>::const_iterator
10391            LSIt = LoadedSlices.begin(),
10392            LSItEnd = LoadedSlices.end();
10393        LSIt != LSItEnd; ++LSIt) {
10394     SDValue SliceInst = LSIt->loadSlice();
10395     CombineTo(LSIt->Inst, SliceInst, true);
10396     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10397       SliceInst = SliceInst.getOperand(0);
10398     assert(SliceInst->getOpcode() == ISD::LOAD &&
10399            "It takes more than a zext to get to the loaded slice!!");
10400     ArgChains.push_back(SliceInst.getValue(1));
10401   }
10402
10403   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10404                               ArgChains);
10405   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10406   return true;
10407 }
10408
10409 /// Check to see if V is (and load (ptr), imm), where the load is having
10410 /// specific bytes cleared out.  If so, return the byte size being masked out
10411 /// and the shift amount.
10412 static std::pair<unsigned, unsigned>
10413 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10414   std::pair<unsigned, unsigned> Result(0, 0);
10415
10416   // Check for the structure we're looking for.
10417   if (V->getOpcode() != ISD::AND ||
10418       !isa<ConstantSDNode>(V->getOperand(1)) ||
10419       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10420     return Result;
10421
10422   // Check the chain and pointer.
10423   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10424   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10425
10426   // The store should be chained directly to the load or be an operand of a
10427   // tokenfactor.
10428   if (LD == Chain.getNode())
10429     ; // ok.
10430   else if (Chain->getOpcode() != ISD::TokenFactor)
10431     return Result; // Fail.
10432   else {
10433     bool isOk = false;
10434     for (const SDValue &ChainOp : Chain->op_values())
10435       if (ChainOp.getNode() == LD) {
10436         isOk = true;
10437         break;
10438       }
10439     if (!isOk) return Result;
10440   }
10441
10442   // This only handles simple types.
10443   if (V.getValueType() != MVT::i16 &&
10444       V.getValueType() != MVT::i32 &&
10445       V.getValueType() != MVT::i64)
10446     return Result;
10447
10448   // Check the constant mask.  Invert it so that the bits being masked out are
10449   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10450   // follow the sign bit for uniformity.
10451   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10452   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10453   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10454   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10455   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10456   if (NotMaskLZ == 64) return Result;  // All zero mask.
10457
10458   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10459   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10460     return Result;
10461
10462   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10463   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10464     NotMaskLZ -= 64-V.getValueSizeInBits();
10465
10466   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10467   switch (MaskedBytes) {
10468   case 1:
10469   case 2:
10470   case 4: break;
10471   default: return Result; // All one mask, or 5-byte mask.
10472   }
10473
10474   // Verify that the first bit starts at a multiple of mask so that the access
10475   // is aligned the same as the access width.
10476   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10477
10478   Result.first = MaskedBytes;
10479   Result.second = NotMaskTZ/8;
10480   return Result;
10481 }
10482
10483
10484 /// Check to see if IVal is something that provides a value as specified by
10485 /// MaskInfo. If so, replace the specified store with a narrower store of
10486 /// truncated IVal.
10487 static SDNode *
10488 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10489                                 SDValue IVal, StoreSDNode *St,
10490                                 DAGCombiner *DC) {
10491   unsigned NumBytes = MaskInfo.first;
10492   unsigned ByteShift = MaskInfo.second;
10493   SelectionDAG &DAG = DC->getDAG();
10494
10495   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10496   // that uses this.  If not, this is not a replacement.
10497   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10498                                   ByteShift*8, (ByteShift+NumBytes)*8);
10499   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10500
10501   // Check that it is legal on the target to do this.  It is legal if the new
10502   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10503   // legalization.
10504   MVT VT = MVT::getIntegerVT(NumBytes*8);
10505   if (!DC->isTypeLegal(VT))
10506     return nullptr;
10507
10508   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10509   // shifted by ByteShift and truncated down to NumBytes.
10510   if (ByteShift) {
10511     SDLoc DL(IVal);
10512     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10513                        DAG.getConstant(ByteShift*8, DL,
10514                                     DC->getShiftAmountTy(IVal.getValueType())));
10515   }
10516
10517   // Figure out the offset for the store and the alignment of the access.
10518   unsigned StOffset;
10519   unsigned NewAlign = St->getAlignment();
10520
10521   if (DAG.getDataLayout().isLittleEndian())
10522     StOffset = ByteShift;
10523   else
10524     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10525
10526   SDValue Ptr = St->getBasePtr();
10527   if (StOffset) {
10528     SDLoc DL(IVal);
10529     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10530                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10531     NewAlign = MinAlign(NewAlign, StOffset);
10532   }
10533
10534   // Truncate down to the new size.
10535   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10536
10537   ++OpsNarrowed;
10538   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10539                       St->getPointerInfo().getWithOffset(StOffset),
10540                       false, false, NewAlign).getNode();
10541 }
10542
10543
10544 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10545 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10546 /// narrowing the load and store if it would end up being a win for performance
10547 /// or code size.
10548 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10549   StoreSDNode *ST  = cast<StoreSDNode>(N);
10550   if (ST->isVolatile())
10551     return SDValue();
10552
10553   SDValue Chain = ST->getChain();
10554   SDValue Value = ST->getValue();
10555   SDValue Ptr   = ST->getBasePtr();
10556   EVT VT = Value.getValueType();
10557
10558   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10559     return SDValue();
10560
10561   unsigned Opc = Value.getOpcode();
10562
10563   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10564   // is a byte mask indicating a consecutive number of bytes, check to see if
10565   // Y is known to provide just those bytes.  If so, we try to replace the
10566   // load + replace + store sequence with a single (narrower) store, which makes
10567   // the load dead.
10568   if (Opc == ISD::OR) {
10569     std::pair<unsigned, unsigned> MaskedLoad;
10570     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10571     if (MaskedLoad.first)
10572       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10573                                                   Value.getOperand(1), ST,this))
10574         return SDValue(NewST, 0);
10575
10576     // Or is commutative, so try swapping X and Y.
10577     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10578     if (MaskedLoad.first)
10579       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10580                                                   Value.getOperand(0), ST,this))
10581         return SDValue(NewST, 0);
10582   }
10583
10584   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10585       Value.getOperand(1).getOpcode() != ISD::Constant)
10586     return SDValue();
10587
10588   SDValue N0 = Value.getOperand(0);
10589   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10590       Chain == SDValue(N0.getNode(), 1)) {
10591     LoadSDNode *LD = cast<LoadSDNode>(N0);
10592     if (LD->getBasePtr() != Ptr ||
10593         LD->getPointerInfo().getAddrSpace() !=
10594         ST->getPointerInfo().getAddrSpace())
10595       return SDValue();
10596
10597     // Find the type to narrow it the load / op / store to.
10598     SDValue N1 = Value.getOperand(1);
10599     unsigned BitWidth = N1.getValueSizeInBits();
10600     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10601     if (Opc == ISD::AND)
10602       Imm ^= APInt::getAllOnesValue(BitWidth);
10603     if (Imm == 0 || Imm.isAllOnesValue())
10604       return SDValue();
10605     unsigned ShAmt = Imm.countTrailingZeros();
10606     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10607     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10608     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10609     // The narrowing should be profitable, the load/store operation should be
10610     // legal (or custom) and the store size should be equal to the NewVT width.
10611     while (NewBW < BitWidth &&
10612            (NewVT.getStoreSizeInBits() != NewBW ||
10613             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10614             !TLI.isNarrowingProfitable(VT, NewVT))) {
10615       NewBW = NextPowerOf2(NewBW);
10616       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10617     }
10618     if (NewBW >= BitWidth)
10619       return SDValue();
10620
10621     // If the lsb changed does not start at the type bitwidth boundary,
10622     // start at the previous one.
10623     if (ShAmt % NewBW)
10624       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10625     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10626                                    std::min(BitWidth, ShAmt + NewBW));
10627     if ((Imm & Mask) == Imm) {
10628       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10629       if (Opc == ISD::AND)
10630         NewImm ^= APInt::getAllOnesValue(NewBW);
10631       uint64_t PtrOff = ShAmt / 8;
10632       // For big endian targets, we need to adjust the offset to the pointer to
10633       // load the correct bytes.
10634       if (DAG.getDataLayout().isBigEndian())
10635         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10636
10637       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10638       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10639       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10640         return SDValue();
10641
10642       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10643                                    Ptr.getValueType(), Ptr,
10644                                    DAG.getConstant(PtrOff, SDLoc(LD),
10645                                                    Ptr.getValueType()));
10646       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10647                                   LD->getChain(), NewPtr,
10648                                   LD->getPointerInfo().getWithOffset(PtrOff),
10649                                   LD->isVolatile(), LD->isNonTemporal(),
10650                                   LD->isInvariant(), NewAlign,
10651                                   LD->getAAInfo());
10652       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10653                                    DAG.getConstant(NewImm, SDLoc(Value),
10654                                                    NewVT));
10655       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10656                                    NewVal, NewPtr,
10657                                    ST->getPointerInfo().getWithOffset(PtrOff),
10658                                    false, false, NewAlign);
10659
10660       AddToWorklist(NewPtr.getNode());
10661       AddToWorklist(NewLD.getNode());
10662       AddToWorklist(NewVal.getNode());
10663       WorklistRemover DeadNodes(*this);
10664       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10665       ++OpsNarrowed;
10666       return NewST;
10667     }
10668   }
10669
10670   return SDValue();
10671 }
10672
10673 /// For a given floating point load / store pair, if the load value isn't used
10674 /// by any other operations, then consider transforming the pair to integer
10675 /// load / store operations if the target deems the transformation profitable.
10676 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10677   StoreSDNode *ST  = cast<StoreSDNode>(N);
10678   SDValue Chain = ST->getChain();
10679   SDValue Value = ST->getValue();
10680   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10681       Value.hasOneUse() &&
10682       Chain == SDValue(Value.getNode(), 1)) {
10683     LoadSDNode *LD = cast<LoadSDNode>(Value);
10684     EVT VT = LD->getMemoryVT();
10685     if (!VT.isFloatingPoint() ||
10686         VT != ST->getMemoryVT() ||
10687         LD->isNonTemporal() ||
10688         ST->isNonTemporal() ||
10689         LD->getPointerInfo().getAddrSpace() != 0 ||
10690         ST->getPointerInfo().getAddrSpace() != 0)
10691       return SDValue();
10692
10693     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10694     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10695         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10696         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10697         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10698       return SDValue();
10699
10700     unsigned LDAlign = LD->getAlignment();
10701     unsigned STAlign = ST->getAlignment();
10702     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10703     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10704     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10705       return SDValue();
10706
10707     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10708                                 LD->getChain(), LD->getBasePtr(),
10709                                 LD->getPointerInfo(),
10710                                 false, false, false, LDAlign);
10711
10712     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10713                                  NewLD, ST->getBasePtr(),
10714                                  ST->getPointerInfo(),
10715                                  false, false, STAlign);
10716
10717     AddToWorklist(NewLD.getNode());
10718     AddToWorklist(NewST.getNode());
10719     WorklistRemover DeadNodes(*this);
10720     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10721     ++LdStFP2Int;
10722     return NewST;
10723   }
10724
10725   return SDValue();
10726 }
10727
10728 namespace {
10729 /// Helper struct to parse and store a memory address as base + index + offset.
10730 /// We ignore sign extensions when it is safe to do so.
10731 /// The following two expressions are not equivalent. To differentiate we need
10732 /// to store whether there was a sign extension involved in the index
10733 /// computation.
10734 ///  (load (i64 add (i64 copyfromreg %c)
10735 ///                 (i64 signextend (add (i8 load %index)
10736 ///                                      (i8 1))))
10737 /// vs
10738 ///
10739 /// (load (i64 add (i64 copyfromreg %c)
10740 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10741 ///                                         (i32 1)))))
10742 struct BaseIndexOffset {
10743   SDValue Base;
10744   SDValue Index;
10745   int64_t Offset;
10746   bool IsIndexSignExt;
10747
10748   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10749
10750   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10751                   bool IsIndexSignExt) :
10752     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10753
10754   bool equalBaseIndex(const BaseIndexOffset &Other) {
10755     return Other.Base == Base && Other.Index == Index &&
10756       Other.IsIndexSignExt == IsIndexSignExt;
10757   }
10758
10759   /// Parses tree in Ptr for base, index, offset addresses.
10760   static BaseIndexOffset match(SDValue Ptr) {
10761     bool IsIndexSignExt = false;
10762
10763     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10764     // instruction, then it could be just the BASE or everything else we don't
10765     // know how to handle. Just use Ptr as BASE and give up.
10766     if (Ptr->getOpcode() != ISD::ADD)
10767       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10768
10769     // We know that we have at least an ADD instruction. Try to pattern match
10770     // the simple case of BASE + OFFSET.
10771     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10772       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10773       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10774                               IsIndexSignExt);
10775     }
10776
10777     // Inside a loop the current BASE pointer is calculated using an ADD and a
10778     // MUL instruction. In this case Ptr is the actual BASE pointer.
10779     // (i64 add (i64 %array_ptr)
10780     //          (i64 mul (i64 %induction_var)
10781     //                   (i64 %element_size)))
10782     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10783       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10784
10785     // Look at Base + Index + Offset cases.
10786     SDValue Base = Ptr->getOperand(0);
10787     SDValue IndexOffset = Ptr->getOperand(1);
10788
10789     // Skip signextends.
10790     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10791       IndexOffset = IndexOffset->getOperand(0);
10792       IsIndexSignExt = true;
10793     }
10794
10795     // Either the case of Base + Index (no offset) or something else.
10796     if (IndexOffset->getOpcode() != ISD::ADD)
10797       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10798
10799     // Now we have the case of Base + Index + offset.
10800     SDValue Index = IndexOffset->getOperand(0);
10801     SDValue Offset = IndexOffset->getOperand(1);
10802
10803     if (!isa<ConstantSDNode>(Offset))
10804       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10805
10806     // Ignore signextends.
10807     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10808       Index = Index->getOperand(0);
10809       IsIndexSignExt = true;
10810     } else IsIndexSignExt = false;
10811
10812     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10813     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10814   }
10815 };
10816 } // namespace
10817
10818 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10819                                                   SDLoc SL,
10820                                                   ArrayRef<MemOpLink> Stores,
10821                                                   SmallVectorImpl<SDValue> &Chains,
10822                                                   EVT Ty) const {
10823   SmallVector<SDValue, 8> BuildVector;
10824
10825   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10826     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10827     Chains.push_back(St->getChain());
10828     BuildVector.push_back(St->getValue());
10829   }
10830
10831   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10832 }
10833
10834 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10835                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10836                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10837   // Make sure we have something to merge.
10838   if (NumStores < 2)
10839     return false;
10840
10841   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10842   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10843   unsigned LatestNodeUsed = 0;
10844
10845   for (unsigned i=0; i < NumStores; ++i) {
10846     // Find a chain for the new wide-store operand. Notice that some
10847     // of the store nodes that we found may not be selected for inclusion
10848     // in the wide store. The chain we use needs to be the chain of the
10849     // latest store node which is *used* and replaced by the wide store.
10850     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10851       LatestNodeUsed = i;
10852   }
10853
10854   SmallVector<SDValue, 8> Chains;
10855
10856   // The latest Node in the DAG.
10857   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10858   SDLoc DL(StoreNodes[0].MemNode);
10859
10860   SDValue StoredVal;
10861   if (UseVector) {
10862     bool IsVec = MemVT.isVector();
10863     unsigned Elts = NumStores;
10864     if (IsVec) {
10865       // When merging vector stores, get the total number of elements.
10866       Elts *= MemVT.getVectorNumElements();
10867     }
10868     // Get the type for the merged vector store.
10869     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10870     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10871
10872     if (IsConstantSrc) {
10873       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10874     } else {
10875       SmallVector<SDValue, 8> Ops;
10876       for (unsigned i = 0; i < NumStores; ++i) {
10877         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10878         SDValue Val = St->getValue();
10879         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10880         if (Val.getValueType() != MemVT)
10881           return false;
10882         Ops.push_back(Val);
10883         Chains.push_back(St->getChain());
10884       }
10885
10886       // Build the extracted vector elements back into a vector.
10887       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10888                               DL, Ty, Ops);    }
10889   } else {
10890     // We should always use a vector store when merging extracted vector
10891     // elements, so this path implies a store of constants.
10892     assert(IsConstantSrc && "Merged vector elements should use vector store");
10893
10894     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10895     APInt StoreInt(SizeInBits, 0);
10896
10897     // Construct a single integer constant which is made of the smaller
10898     // constant inputs.
10899     bool IsLE = DAG.getDataLayout().isLittleEndian();
10900     for (unsigned i = 0; i < NumStores; ++i) {
10901       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10902       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10903       Chains.push_back(St->getChain());
10904
10905       SDValue Val = St->getValue();
10906       StoreInt <<= ElementSizeBytes * 8;
10907       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10908         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10909       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10910         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10911       } else {
10912         llvm_unreachable("Invalid constant element type");
10913       }
10914     }
10915
10916     // Create the new Load and Store operations.
10917     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10918     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10919   }
10920
10921   assert(!Chains.empty());
10922
10923   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10924   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10925                                   FirstInChain->getBasePtr(),
10926                                   FirstInChain->getPointerInfo(),
10927                                   false, false,
10928                                   FirstInChain->getAlignment());
10929
10930   // Replace the last store with the new store
10931   CombineTo(LatestOp, NewStore);
10932   // Erase all other stores.
10933   for (unsigned i = 0; i < NumStores; ++i) {
10934     if (StoreNodes[i].MemNode == LatestOp)
10935       continue;
10936     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10937     // ReplaceAllUsesWith will replace all uses that existed when it was
10938     // called, but graph optimizations may cause new ones to appear. For
10939     // example, the case in pr14333 looks like
10940     //
10941     //  St's chain -> St -> another store -> X
10942     //
10943     // And the only difference from St to the other store is the chain.
10944     // When we change it's chain to be St's chain they become identical,
10945     // get CSEed and the net result is that X is now a use of St.
10946     // Since we know that St is redundant, just iterate.
10947     while (!St->use_empty())
10948       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10949     deleteAndRecombine(St);
10950   }
10951
10952   return true;
10953 }
10954
10955 void DAGCombiner::getStoreMergeAndAliasCandidates(
10956     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10957     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10958   // This holds the base pointer, index, and the offset in bytes from the base
10959   // pointer.
10960   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10961
10962   // We must have a base and an offset.
10963   if (!BasePtr.Base.getNode())
10964     return;
10965
10966   // Do not handle stores to undef base pointers.
10967   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10968     return;
10969
10970   // Walk up the chain and look for nodes with offsets from the same
10971   // base pointer. Stop when reaching an instruction with a different kind
10972   // or instruction which has a different base pointer.
10973   EVT MemVT = St->getMemoryVT();
10974   unsigned Seq = 0;
10975   StoreSDNode *Index = St;
10976
10977
10978   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10979                                                   : DAG.getSubtarget().useAA();
10980
10981   if (UseAA) {
10982     // Look at other users of the same chain. Stores on the same chain do not
10983     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10984     // to be on the same chain, so don't bother looking at adjacent chains.
10985
10986     SDValue Chain = St->getChain();
10987     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10988       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10989         if (I.getOperandNo() != 0)
10990           continue;
10991
10992         if (OtherST->isVolatile() || OtherST->isIndexed())
10993           continue;
10994
10995         if (OtherST->getMemoryVT() != MemVT)
10996           continue;
10997
10998         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10999
11000         if (Ptr.equalBaseIndex(BasePtr))
11001           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11002       }
11003     }
11004
11005     return;
11006   }
11007
11008   while (Index) {
11009     // If the chain has more than one use, then we can't reorder the mem ops.
11010     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11011       break;
11012
11013     // Find the base pointer and offset for this memory node.
11014     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11015
11016     // Check that the base pointer is the same as the original one.
11017     if (!Ptr.equalBaseIndex(BasePtr))
11018       break;
11019
11020     // The memory operands must not be volatile.
11021     if (Index->isVolatile() || Index->isIndexed())
11022       break;
11023
11024     // No truncation.
11025     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11026       if (St->isTruncatingStore())
11027         break;
11028
11029     // The stored memory type must be the same.
11030     if (Index->getMemoryVT() != MemVT)
11031       break;
11032
11033     // We found a potential memory operand to merge.
11034     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11035
11036     // Find the next memory operand in the chain. If the next operand in the
11037     // chain is a store then move up and continue the scan with the next
11038     // memory operand. If the next operand is a load save it and use alias
11039     // information to check if it interferes with anything.
11040     SDNode *NextInChain = Index->getChain().getNode();
11041     while (1) {
11042       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11043         // We found a store node. Use it for the next iteration.
11044         Index = STn;
11045         break;
11046       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11047         if (Ldn->isVolatile()) {
11048           Index = nullptr;
11049           break;
11050         }
11051
11052         // Save the load node for later. Continue the scan.
11053         AliasLoadNodes.push_back(Ldn);
11054         NextInChain = Ldn->getChain().getNode();
11055         continue;
11056       } else {
11057         Index = nullptr;
11058         break;
11059       }
11060     }
11061   }
11062 }
11063
11064 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11065   if (OptLevel == CodeGenOpt::None)
11066     return false;
11067
11068   EVT MemVT = St->getMemoryVT();
11069   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11070   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11071       Attribute::NoImplicitFloat);
11072
11073   // This function cannot currently deal with non-byte-sized memory sizes.
11074   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11075     return false;
11076
11077   if (!MemVT.isSimple())
11078     return false;
11079
11080   // Perform an early exit check. Do not bother looking at stored values that
11081   // are not constants, loads, or extracted vector elements.
11082   SDValue StoredVal = St->getValue();
11083   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11084   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11085                        isa<ConstantFPSDNode>(StoredVal);
11086   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11087                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11088
11089   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11090     return false;
11091
11092   // Don't merge vectors into wider vectors if the source data comes from loads.
11093   // TODO: This restriction can be lifted by using logic similar to the
11094   // ExtractVecSrc case.
11095   if (MemVT.isVector() && IsLoadSrc)
11096     return false;
11097
11098   // Only look at ends of store sequences.
11099   SDValue Chain = SDValue(St, 0);
11100   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11101     return false;
11102
11103   // Save the LoadSDNodes that we find in the chain.
11104   // We need to make sure that these nodes do not interfere with
11105   // any of the store nodes.
11106   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11107
11108   // Save the StoreSDNodes that we find in the chain.
11109   SmallVector<MemOpLink, 8> StoreNodes;
11110
11111   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11112
11113   // Check if there is anything to merge.
11114   if (StoreNodes.size() < 2)
11115     return false;
11116
11117   // Sort the memory operands according to their distance from the base pointer.
11118   std::sort(StoreNodes.begin(), StoreNodes.end(),
11119             [](MemOpLink LHS, MemOpLink RHS) {
11120     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11121            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11122             LHS.SequenceNum > RHS.SequenceNum);
11123   });
11124
11125   // Scan the memory operations on the chain and find the first non-consecutive
11126   // store memory address.
11127   unsigned LastConsecutiveStore = 0;
11128   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11129   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11130
11131     // Check that the addresses are consecutive starting from the second
11132     // element in the list of stores.
11133     if (i > 0) {
11134       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11135       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11136         break;
11137     }
11138
11139     bool Alias = false;
11140     // Check if this store interferes with any of the loads that we found.
11141     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11142       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11143         Alias = true;
11144         break;
11145       }
11146     // We found a load that alias with this store. Stop the sequence.
11147     if (Alias)
11148       break;
11149
11150     // Mark this node as useful.
11151     LastConsecutiveStore = i;
11152   }
11153
11154   // The node with the lowest store address.
11155   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11156   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11157   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11158   LLVMContext &Context = *DAG.getContext();
11159   const DataLayout &DL = DAG.getDataLayout();
11160
11161   // Store the constants into memory as one consecutive store.
11162   if (IsConstantSrc) {
11163     unsigned LastLegalType = 0;
11164     unsigned LastLegalVectorType = 0;
11165     bool NonZero = false;
11166     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11167       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11168       SDValue StoredVal = St->getValue();
11169
11170       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11171         NonZero |= !C->isNullValue();
11172       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11173         NonZero |= !C->getConstantFPValue()->isNullValue();
11174       } else {
11175         // Non-constant.
11176         break;
11177       }
11178
11179       // Find a legal type for the constant store.
11180       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11181       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11182       bool IsFast;
11183       if (TLI.isTypeLegal(StoreTy) &&
11184           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11185                                  FirstStoreAlign, &IsFast) && IsFast) {
11186         LastLegalType = i+1;
11187       // Or check whether a truncstore is legal.
11188       } else if (TLI.getTypeAction(Context, StoreTy) ==
11189                  TargetLowering::TypePromoteInteger) {
11190         EVT LegalizedStoredValueTy =
11191           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11192         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11193             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11194                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11195             IsFast) {
11196           LastLegalType = i + 1;
11197         }
11198       }
11199
11200       // We only use vectors if the constant is known to be zero or the target
11201       // allows it and the function is not marked with the noimplicitfloat
11202       // attribute.
11203       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11204                                                         FirstStoreAS)) &&
11205           !NoVectors) {
11206         // Find a legal type for the vector store.
11207         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11208         if (TLI.isTypeLegal(Ty) &&
11209             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11210                                    FirstStoreAlign, &IsFast) && IsFast)
11211           LastLegalVectorType = i + 1;
11212       }
11213     }
11214
11215     // Check if we found a legal integer type to store.
11216     if (LastLegalType == 0 && LastLegalVectorType == 0)
11217       return false;
11218
11219     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11220     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11221
11222     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11223                                            true, UseVector);
11224   }
11225
11226   // When extracting multiple vector elements, try to store them
11227   // in one vector store rather than a sequence of scalar stores.
11228   if (IsExtractVecSrc) {
11229     unsigned NumStoresToMerge = 0;
11230     bool IsVec = MemVT.isVector();
11231     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11232       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11233       unsigned StoreValOpcode = St->getValue().getOpcode();
11234       // This restriction could be loosened.
11235       // Bail out if any stored values are not elements extracted from a vector.
11236       // It should be possible to handle mixed sources, but load sources need
11237       // more careful handling (see the block of code below that handles
11238       // consecutive loads).
11239       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11240           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11241         return false;
11242
11243       // Find a legal type for the vector store.
11244       unsigned Elts = i + 1;
11245       if (IsVec) {
11246         // When merging vector stores, get the total number of elements.
11247         Elts *= MemVT.getVectorNumElements();
11248       }
11249       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11250       bool IsFast;
11251       if (TLI.isTypeLegal(Ty) &&
11252           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11253                                  FirstStoreAlign, &IsFast) && IsFast)
11254         NumStoresToMerge = i + 1;
11255     }
11256
11257     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11258                                            false, true);
11259   }
11260
11261   // Below we handle the case of multiple consecutive stores that
11262   // come from multiple consecutive loads. We merge them into a single
11263   // wide load and a single wide store.
11264
11265   // Look for load nodes which are used by the stored values.
11266   SmallVector<MemOpLink, 8> LoadNodes;
11267
11268   // Find acceptable loads. Loads need to have the same chain (token factor),
11269   // must not be zext, volatile, indexed, and they must be consecutive.
11270   BaseIndexOffset LdBasePtr;
11271   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11272     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11273     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11274     if (!Ld) break;
11275
11276     // Loads must only have one use.
11277     if (!Ld->hasNUsesOfValue(1, 0))
11278       break;
11279
11280     // The memory operands must not be volatile.
11281     if (Ld->isVolatile() || Ld->isIndexed())
11282       break;
11283
11284     // We do not accept ext loads.
11285     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11286       break;
11287
11288     // The stored memory type must be the same.
11289     if (Ld->getMemoryVT() != MemVT)
11290       break;
11291
11292     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11293     // If this is not the first ptr that we check.
11294     if (LdBasePtr.Base.getNode()) {
11295       // The base ptr must be the same.
11296       if (!LdPtr.equalBaseIndex(LdBasePtr))
11297         break;
11298     } else {
11299       // Check that all other base pointers are the same as this one.
11300       LdBasePtr = LdPtr;
11301     }
11302
11303     // We found a potential memory operand to merge.
11304     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11305   }
11306
11307   if (LoadNodes.size() < 2)
11308     return false;
11309
11310   // If we have load/store pair instructions and we only have two values,
11311   // don't bother.
11312   unsigned RequiredAlignment;
11313   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11314       St->getAlignment() >= RequiredAlignment)
11315     return false;
11316
11317   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11318   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11319   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11320
11321   // Scan the memory operations on the chain and find the first non-consecutive
11322   // load memory address. These variables hold the index in the store node
11323   // array.
11324   unsigned LastConsecutiveLoad = 0;
11325   // This variable refers to the size and not index in the array.
11326   unsigned LastLegalVectorType = 0;
11327   unsigned LastLegalIntegerType = 0;
11328   StartAddress = LoadNodes[0].OffsetFromBase;
11329   SDValue FirstChain = FirstLoad->getChain();
11330   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11331     // All loads much share the same chain.
11332     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11333       break;
11334
11335     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11336     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11337       break;
11338     LastConsecutiveLoad = i;
11339     // Find a legal type for the vector store.
11340     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11341     bool IsFastSt, IsFastLd;
11342     if (TLI.isTypeLegal(StoreTy) &&
11343         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11344                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11345         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11346                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11347       LastLegalVectorType = i + 1;
11348     }
11349
11350     // Find a legal type for the integer store.
11351     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11352     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11353     if (TLI.isTypeLegal(StoreTy) &&
11354         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11355                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11356         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11357                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11358       LastLegalIntegerType = i + 1;
11359     // Or check whether a truncstore and extload is legal.
11360     else if (TLI.getTypeAction(Context, StoreTy) ==
11361              TargetLowering::TypePromoteInteger) {
11362       EVT LegalizedStoredValueTy =
11363         TLI.getTypeToTransformTo(Context, StoreTy);
11364       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11365           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11366           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11367           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11368           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11369                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11370           IsFastSt &&
11371           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11372                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11373           IsFastLd)
11374         LastLegalIntegerType = i+1;
11375     }
11376   }
11377
11378   // Only use vector types if the vector type is larger than the integer type.
11379   // If they are the same, use integers.
11380   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11381   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11382
11383   // We add +1 here because the LastXXX variables refer to location while
11384   // the NumElem refers to array/index size.
11385   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11386   NumElem = std::min(LastLegalType, NumElem);
11387
11388   if (NumElem < 2)
11389     return false;
11390
11391   // Collect the chains from all merged stores.
11392   SmallVector<SDValue, 8> MergeStoreChains;
11393   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11394
11395   // The latest Node in the DAG.
11396   unsigned LatestNodeUsed = 0;
11397   for (unsigned i=1; i<NumElem; ++i) {
11398     // Find a chain for the new wide-store operand. Notice that some
11399     // of the store nodes that we found may not be selected for inclusion
11400     // in the wide store. The chain we use needs to be the chain of the
11401     // latest store node which is *used* and replaced by the wide store.
11402     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11403       LatestNodeUsed = i;
11404
11405     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11406   }
11407
11408   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11409
11410   // Find if it is better to use vectors or integers to load and store
11411   // to memory.
11412   EVT JointMemOpVT;
11413   if (UseVectorTy) {
11414     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11415   } else {
11416     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11417     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11418   }
11419
11420   SDLoc LoadDL(LoadNodes[0].MemNode);
11421   SDLoc StoreDL(StoreNodes[0].MemNode);
11422
11423   // The merged loads are required to have the same chain, so using the first's
11424   // chain is acceptable.
11425   SDValue NewLoad = DAG.getLoad(
11426       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11427       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11428
11429   SDValue NewStoreChain =
11430     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11431
11432   SDValue NewStore = DAG.getStore(
11433     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11434       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11435
11436   // Replace one of the loads with the new load.
11437   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11438   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11439                                 SDValue(NewLoad.getNode(), 1));
11440
11441   // Remove the rest of the load chains.
11442   for (unsigned i = 1; i < NumElem ; ++i) {
11443     // Replace all chain users of the old load nodes with the chain of the new
11444     // load node.
11445     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11446     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11447   }
11448
11449   // Replace the last store with the new store.
11450   CombineTo(LatestOp, NewStore);
11451   // Erase all other stores.
11452   for (unsigned i = 0; i < NumElem ; ++i) {
11453     // Remove all Store nodes.
11454     if (StoreNodes[i].MemNode == LatestOp)
11455       continue;
11456     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11457     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11458     deleteAndRecombine(St);
11459   }
11460
11461   return true;
11462 }
11463
11464 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11465   SDLoc SL(ST);
11466   SDValue ReplStore;
11467
11468   // Replace the chain to avoid dependency.
11469   if (ST->isTruncatingStore()) {
11470     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11471                                   ST->getBasePtr(), ST->getMemoryVT(),
11472                                   ST->getMemOperand());
11473   } else {
11474     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11475                              ST->getMemOperand());
11476   }
11477
11478   // Create token to keep both nodes around.
11479   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11480                               MVT::Other, ST->getChain(), ReplStore);
11481
11482   // Make sure the new and old chains are cleaned up.
11483   AddToWorklist(Token.getNode());
11484
11485   // Don't add users to work list.
11486   return CombineTo(ST, Token, false);
11487 }
11488
11489 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11490   SDValue Value = ST->getValue();
11491   if (Value.getOpcode() == ISD::TargetConstantFP)
11492     return SDValue();
11493
11494   SDLoc DL(ST);
11495
11496   SDValue Chain = ST->getChain();
11497   SDValue Ptr = ST->getBasePtr();
11498
11499   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11500
11501   // NOTE: If the original store is volatile, this transform must not increase
11502   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11503   // processor operation but an i64 (which is not legal) requires two.  So the
11504   // transform should not be done in this case.
11505
11506   SDValue Tmp;
11507   switch (CFP->getSimpleValueType(0).SimpleTy) {
11508   default:
11509     llvm_unreachable("Unknown FP type");
11510   case MVT::f16:    // We don't do this for these yet.
11511   case MVT::f80:
11512   case MVT::f128:
11513   case MVT::ppcf128:
11514     return SDValue();
11515   case MVT::f32:
11516     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11517         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11518       ;
11519       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11520                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11521                             MVT::i32);
11522       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11523     }
11524
11525     return SDValue();
11526   case MVT::f64:
11527     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11528          !ST->isVolatile()) ||
11529         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11530       ;
11531       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11532                             getZExtValue(), SDLoc(CFP), MVT::i64);
11533       return DAG.getStore(Chain, DL, Tmp,
11534                           Ptr, ST->getMemOperand());
11535     }
11536
11537     if (!ST->isVolatile() &&
11538         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11539       // Many FP stores are not made apparent until after legalize, e.g. for
11540       // argument passing.  Since this is so common, custom legalize the
11541       // 64-bit integer store into two 32-bit stores.
11542       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11543       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11544       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11545       if (DAG.getDataLayout().isBigEndian())
11546         std::swap(Lo, Hi);
11547
11548       unsigned Alignment = ST->getAlignment();
11549       bool isVolatile = ST->isVolatile();
11550       bool isNonTemporal = ST->isNonTemporal();
11551       AAMDNodes AAInfo = ST->getAAInfo();
11552
11553       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11554                                  Ptr, ST->getPointerInfo(),
11555                                  isVolatile, isNonTemporal,
11556                                  ST->getAlignment(), AAInfo);
11557       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11558                         DAG.getConstant(4, DL, Ptr.getValueType()));
11559       Alignment = MinAlign(Alignment, 4U);
11560       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11561                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11562                                  isVolatile, isNonTemporal,
11563                                  Alignment, AAInfo);
11564       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11565                          St0, St1);
11566     }
11567
11568     return SDValue();
11569   }
11570 }
11571
11572 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11573   StoreSDNode *ST  = cast<StoreSDNode>(N);
11574   SDValue Chain = ST->getChain();
11575   SDValue Value = ST->getValue();
11576   SDValue Ptr   = ST->getBasePtr();
11577
11578   // If this is a store of a bit convert, store the input value if the
11579   // resultant store does not need a higher alignment than the original.
11580   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11581       ST->isUnindexed()) {
11582     unsigned OrigAlign = ST->getAlignment();
11583     EVT SVT = Value.getOperand(0).getValueType();
11584     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11585         SVT.getTypeForEVT(*DAG.getContext()));
11586     if (Align <= OrigAlign &&
11587         ((!LegalOperations && !ST->isVolatile()) ||
11588          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11589       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11590                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11591                           ST->isNonTemporal(), OrigAlign,
11592                           ST->getAAInfo());
11593   }
11594
11595   // Turn 'store undef, Ptr' -> nothing.
11596   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11597     return Chain;
11598
11599   // Try to infer better alignment information than the store already has.
11600   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11601     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11602       if (Align > ST->getAlignment()) {
11603         SDValue NewStore =
11604                DAG.getTruncStore(Chain, SDLoc(N), Value,
11605                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11606                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11607                                  ST->getAAInfo());
11608         if (NewStore.getNode() != N)
11609           return CombineTo(ST, NewStore, true);
11610       }
11611     }
11612   }
11613
11614   // Try transforming a pair floating point load / store ops to integer
11615   // load / store ops.
11616   if (SDValue NewST = TransformFPLoadStorePair(N))
11617     return NewST;
11618
11619   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11620                                                   : DAG.getSubtarget().useAA();
11621 #ifndef NDEBUG
11622   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11623       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11624     UseAA = false;
11625 #endif
11626   if (UseAA && ST->isUnindexed()) {
11627     // FIXME: We should do this even without AA enabled. AA will just allow
11628     // FindBetterChain to work in more situations. The problem with this is that
11629     // any combine that expects memory operations to be on consecutive chains
11630     // first needs to be updated to look for users of the same chain.
11631
11632     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11633     // adjacent stores.
11634     if (findBetterNeighborChains(ST)) {
11635       // replaceStoreChain uses CombineTo, which handled all of the worklist
11636       // manipulation. Return the original node to not do anything else.
11637       return SDValue(ST, 0);
11638     }
11639   }
11640
11641   // Try transforming N to an indexed store.
11642   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11643     return SDValue(N, 0);
11644
11645   // FIXME: is there such a thing as a truncating indexed store?
11646   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11647       Value.getValueType().isInteger()) {
11648     // See if we can simplify the input to this truncstore with knowledge that
11649     // only the low bits are being used.  For example:
11650     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11651     SDValue Shorter =
11652       GetDemandedBits(Value,
11653                       APInt::getLowBitsSet(
11654                         Value.getValueType().getScalarType().getSizeInBits(),
11655                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11656     AddToWorklist(Value.getNode());
11657     if (Shorter.getNode())
11658       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11659                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11660
11661     // Otherwise, see if we can simplify the operation with
11662     // SimplifyDemandedBits, which only works if the value has a single use.
11663     if (SimplifyDemandedBits(Value,
11664                         APInt::getLowBitsSet(
11665                           Value.getValueType().getScalarType().getSizeInBits(),
11666                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11667       return SDValue(N, 0);
11668   }
11669
11670   // If this is a load followed by a store to the same location, then the store
11671   // is dead/noop.
11672   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11673     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11674         ST->isUnindexed() && !ST->isVolatile() &&
11675         // There can't be any side effects between the load and store, such as
11676         // a call or store.
11677         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11678       // The store is dead, remove it.
11679       return Chain;
11680     }
11681   }
11682
11683   // If this is a store followed by a store with the same value to the same
11684   // location, then the store is dead/noop.
11685   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11686     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11687         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11688         ST1->isUnindexed() && !ST1->isVolatile()) {
11689       // The store is dead, remove it.
11690       return Chain;
11691     }
11692   }
11693
11694   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11695   // truncating store.  We can do this even if this is already a truncstore.
11696   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11697       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11698       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11699                             ST->getMemoryVT())) {
11700     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11701                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11702   }
11703
11704   // Only perform this optimization before the types are legal, because we
11705   // don't want to perform this optimization on every DAGCombine invocation.
11706   if (!LegalTypes) {
11707     bool EverChanged = false;
11708
11709     do {
11710       // There can be multiple store sequences on the same chain.
11711       // Keep trying to merge store sequences until we are unable to do so
11712       // or until we merge the last store on the chain.
11713       bool Changed = MergeConsecutiveStores(ST);
11714       EverChanged |= Changed;
11715       if (!Changed) break;
11716     } while (ST->getOpcode() != ISD::DELETED_NODE);
11717
11718     if (EverChanged)
11719       return SDValue(N, 0);
11720   }
11721
11722   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11723   //
11724   // Make sure to do this only after attempting to merge stores in order to
11725   //  avoid changing the types of some subset of stores due to visit order,
11726   //  preventing their merging.
11727   if (isa<ConstantFPSDNode>(Value)) {
11728     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11729       return NewSt;
11730   }
11731
11732   return ReduceLoadOpStoreWidth(N);
11733 }
11734
11735 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11736   SDValue InVec = N->getOperand(0);
11737   SDValue InVal = N->getOperand(1);
11738   SDValue EltNo = N->getOperand(2);
11739   SDLoc dl(N);
11740
11741   // If the inserted element is an UNDEF, just use the input vector.
11742   if (InVal.getOpcode() == ISD::UNDEF)
11743     return InVec;
11744
11745   EVT VT = InVec.getValueType();
11746
11747   // If we can't generate a legal BUILD_VECTOR, exit
11748   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11749     return SDValue();
11750
11751   // Check that we know which element is being inserted
11752   if (!isa<ConstantSDNode>(EltNo))
11753     return SDValue();
11754   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11755
11756   // Canonicalize insert_vector_elt dag nodes.
11757   // Example:
11758   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11759   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11760   //
11761   // Do this only if the child insert_vector node has one use; also
11762   // do this only if indices are both constants and Idx1 < Idx0.
11763   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11764       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11765     unsigned OtherElt =
11766       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11767     if (Elt < OtherElt) {
11768       // Swap nodes.
11769       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11770                                   InVec.getOperand(0), InVal, EltNo);
11771       AddToWorklist(NewOp.getNode());
11772       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11773                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11774     }
11775   }
11776
11777   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11778   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11779   // vector elements.
11780   SmallVector<SDValue, 8> Ops;
11781   // Do not combine these two vectors if the output vector will not replace
11782   // the input vector.
11783   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11784     Ops.append(InVec.getNode()->op_begin(),
11785                InVec.getNode()->op_end());
11786   } else if (InVec.getOpcode() == ISD::UNDEF) {
11787     unsigned NElts = VT.getVectorNumElements();
11788     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11789   } else {
11790     return SDValue();
11791   }
11792
11793   // Insert the element
11794   if (Elt < Ops.size()) {
11795     // All the operands of BUILD_VECTOR must have the same type;
11796     // we enforce that here.
11797     EVT OpVT = Ops[0].getValueType();
11798     if (InVal.getValueType() != OpVT)
11799       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11800                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11801                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11802     Ops[Elt] = InVal;
11803   }
11804
11805   // Return the new vector
11806   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11807 }
11808
11809 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11810     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11811   EVT ResultVT = EVE->getValueType(0);
11812   EVT VecEltVT = InVecVT.getVectorElementType();
11813   unsigned Align = OriginalLoad->getAlignment();
11814   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11815       VecEltVT.getTypeForEVT(*DAG.getContext()));
11816
11817   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11818     return SDValue();
11819
11820   Align = NewAlign;
11821
11822   SDValue NewPtr = OriginalLoad->getBasePtr();
11823   SDValue Offset;
11824   EVT PtrType = NewPtr.getValueType();
11825   MachinePointerInfo MPI;
11826   SDLoc DL(EVE);
11827   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11828     int Elt = ConstEltNo->getZExtValue();
11829     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11830     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11831     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11832   } else {
11833     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11834     Offset = DAG.getNode(
11835         ISD::MUL, DL, PtrType, Offset,
11836         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11837     MPI = OriginalLoad->getPointerInfo();
11838   }
11839   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11840
11841   // The replacement we need to do here is a little tricky: we need to
11842   // replace an extractelement of a load with a load.
11843   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11844   // Note that this replacement assumes that the extractvalue is the only
11845   // use of the load; that's okay because we don't want to perform this
11846   // transformation in other cases anyway.
11847   SDValue Load;
11848   SDValue Chain;
11849   if (ResultVT.bitsGT(VecEltVT)) {
11850     // If the result type of vextract is wider than the load, then issue an
11851     // extending load instead.
11852     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11853                                                   VecEltVT)
11854                                    ? ISD::ZEXTLOAD
11855                                    : ISD::EXTLOAD;
11856     Load = DAG.getExtLoad(
11857         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11858         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11859         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11860     Chain = Load.getValue(1);
11861   } else {
11862     Load = DAG.getLoad(
11863         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11864         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11865         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11866     Chain = Load.getValue(1);
11867     if (ResultVT.bitsLT(VecEltVT))
11868       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11869     else
11870       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11871   }
11872   WorklistRemover DeadNodes(*this);
11873   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11874   SDValue To[] = { Load, Chain };
11875   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11876   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11877   // worklist explicitly as well.
11878   AddToWorklist(Load.getNode());
11879   AddUsersToWorklist(Load.getNode()); // Add users too
11880   // Make sure to revisit this node to clean it up; it will usually be dead.
11881   AddToWorklist(EVE);
11882   ++OpsNarrowed;
11883   return SDValue(EVE, 0);
11884 }
11885
11886 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11887   // (vextract (scalar_to_vector val, 0) -> val
11888   SDValue InVec = N->getOperand(0);
11889   EVT VT = InVec.getValueType();
11890   EVT NVT = N->getValueType(0);
11891
11892   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11893     // Check if the result type doesn't match the inserted element type. A
11894     // SCALAR_TO_VECTOR may truncate the inserted element and the
11895     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11896     SDValue InOp = InVec.getOperand(0);
11897     if (InOp.getValueType() != NVT) {
11898       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11899       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11900     }
11901     return InOp;
11902   }
11903
11904   SDValue EltNo = N->getOperand(1);
11905   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11906
11907   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11908   // We only perform this optimization before the op legalization phase because
11909   // we may introduce new vector instructions which are not backed by TD
11910   // patterns. For example on AVX, extracting elements from a wide vector
11911   // without using extract_subvector. However, if we can find an underlying
11912   // scalar value, then we can always use that.
11913   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11914       && ConstEltNo) {
11915     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11916     int NumElem = VT.getVectorNumElements();
11917     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11918     // Find the new index to extract from.
11919     int OrigElt = SVOp->getMaskElt(Elt);
11920
11921     // Extracting an undef index is undef.
11922     if (OrigElt == -1)
11923       return DAG.getUNDEF(NVT);
11924
11925     // Select the right vector half to extract from.
11926     SDValue SVInVec;
11927     if (OrigElt < NumElem) {
11928       SVInVec = InVec->getOperand(0);
11929     } else {
11930       SVInVec = InVec->getOperand(1);
11931       OrigElt -= NumElem;
11932     }
11933
11934     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11935       SDValue InOp = SVInVec.getOperand(OrigElt);
11936       if (InOp.getValueType() != NVT) {
11937         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11938         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11939       }
11940
11941       return InOp;
11942     }
11943
11944     // FIXME: We should handle recursing on other vector shuffles and
11945     // scalar_to_vector here as well.
11946
11947     if (!LegalOperations) {
11948       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11949       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11950                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11951     }
11952   }
11953
11954   bool BCNumEltsChanged = false;
11955   EVT ExtVT = VT.getVectorElementType();
11956   EVT LVT = ExtVT;
11957
11958   // If the result of load has to be truncated, then it's not necessarily
11959   // profitable.
11960   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11961     return SDValue();
11962
11963   if (InVec.getOpcode() == ISD::BITCAST) {
11964     // Don't duplicate a load with other uses.
11965     if (!InVec.hasOneUse())
11966       return SDValue();
11967
11968     EVT BCVT = InVec.getOperand(0).getValueType();
11969     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11970       return SDValue();
11971     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11972       BCNumEltsChanged = true;
11973     InVec = InVec.getOperand(0);
11974     ExtVT = BCVT.getVectorElementType();
11975   }
11976
11977   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11978   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11979       ISD::isNormalLoad(InVec.getNode()) &&
11980       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11981     SDValue Index = N->getOperand(1);
11982     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11983       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11984                                                            OrigLoad);
11985   }
11986
11987   // Perform only after legalization to ensure build_vector / vector_shuffle
11988   // optimizations have already been done.
11989   if (!LegalOperations) return SDValue();
11990
11991   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11992   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11993   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11994
11995   if (ConstEltNo) {
11996     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11997
11998     LoadSDNode *LN0 = nullptr;
11999     const ShuffleVectorSDNode *SVN = nullptr;
12000     if (ISD::isNormalLoad(InVec.getNode())) {
12001       LN0 = cast<LoadSDNode>(InVec);
12002     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12003                InVec.getOperand(0).getValueType() == ExtVT &&
12004                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12005       // Don't duplicate a load with other uses.
12006       if (!InVec.hasOneUse())
12007         return SDValue();
12008
12009       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12010     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12011       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12012       // =>
12013       // (load $addr+1*size)
12014
12015       // Don't duplicate a load with other uses.
12016       if (!InVec.hasOneUse())
12017         return SDValue();
12018
12019       // If the bit convert changed the number of elements, it is unsafe
12020       // to examine the mask.
12021       if (BCNumEltsChanged)
12022         return SDValue();
12023
12024       // Select the input vector, guarding against out of range extract vector.
12025       unsigned NumElems = VT.getVectorNumElements();
12026       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12027       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12028
12029       if (InVec.getOpcode() == ISD::BITCAST) {
12030         // Don't duplicate a load with other uses.
12031         if (!InVec.hasOneUse())
12032           return SDValue();
12033
12034         InVec = InVec.getOperand(0);
12035       }
12036       if (ISD::isNormalLoad(InVec.getNode())) {
12037         LN0 = cast<LoadSDNode>(InVec);
12038         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12039         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12040       }
12041     }
12042
12043     // Make sure we found a non-volatile load and the extractelement is
12044     // the only use.
12045     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12046       return SDValue();
12047
12048     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12049     if (Elt == -1)
12050       return DAG.getUNDEF(LVT);
12051
12052     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12053   }
12054
12055   return SDValue();
12056 }
12057
12058 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12059 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12060   // We perform this optimization post type-legalization because
12061   // the type-legalizer often scalarizes integer-promoted vectors.
12062   // Performing this optimization before may create bit-casts which
12063   // will be type-legalized to complex code sequences.
12064   // We perform this optimization only before the operation legalizer because we
12065   // may introduce illegal operations.
12066   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12067     return SDValue();
12068
12069   unsigned NumInScalars = N->getNumOperands();
12070   SDLoc dl(N);
12071   EVT VT = N->getValueType(0);
12072
12073   // Check to see if this is a BUILD_VECTOR of a bunch of values
12074   // which come from any_extend or zero_extend nodes. If so, we can create
12075   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12076   // optimizations. We do not handle sign-extend because we can't fill the sign
12077   // using shuffles.
12078   EVT SourceType = MVT::Other;
12079   bool AllAnyExt = true;
12080
12081   for (unsigned i = 0; i != NumInScalars; ++i) {
12082     SDValue In = N->getOperand(i);
12083     // Ignore undef inputs.
12084     if (In.getOpcode() == ISD::UNDEF) continue;
12085
12086     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12087     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12088
12089     // Abort if the element is not an extension.
12090     if (!ZeroExt && !AnyExt) {
12091       SourceType = MVT::Other;
12092       break;
12093     }
12094
12095     // The input is a ZeroExt or AnyExt. Check the original type.
12096     EVT InTy = In.getOperand(0).getValueType();
12097
12098     // Check that all of the widened source types are the same.
12099     if (SourceType == MVT::Other)
12100       // First time.
12101       SourceType = InTy;
12102     else if (InTy != SourceType) {
12103       // Multiple income types. Abort.
12104       SourceType = MVT::Other;
12105       break;
12106     }
12107
12108     // Check if all of the extends are ANY_EXTENDs.
12109     AllAnyExt &= AnyExt;
12110   }
12111
12112   // In order to have valid types, all of the inputs must be extended from the
12113   // same source type and all of the inputs must be any or zero extend.
12114   // Scalar sizes must be a power of two.
12115   EVT OutScalarTy = VT.getScalarType();
12116   bool ValidTypes = SourceType != MVT::Other &&
12117                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12118                  isPowerOf2_32(SourceType.getSizeInBits());
12119
12120   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12121   // turn into a single shuffle instruction.
12122   if (!ValidTypes)
12123     return SDValue();
12124
12125   bool isLE = DAG.getDataLayout().isLittleEndian();
12126   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12127   assert(ElemRatio > 1 && "Invalid element size ratio");
12128   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12129                                DAG.getConstant(0, SDLoc(N), SourceType);
12130
12131   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12132   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12133
12134   // Populate the new build_vector
12135   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12136     SDValue Cast = N->getOperand(i);
12137     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12138             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12139             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12140     SDValue In;
12141     if (Cast.getOpcode() == ISD::UNDEF)
12142       In = DAG.getUNDEF(SourceType);
12143     else
12144       In = Cast->getOperand(0);
12145     unsigned Index = isLE ? (i * ElemRatio) :
12146                             (i * ElemRatio + (ElemRatio - 1));
12147
12148     assert(Index < Ops.size() && "Invalid index");
12149     Ops[Index] = In;
12150   }
12151
12152   // The type of the new BUILD_VECTOR node.
12153   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12154   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12155          "Invalid vector size");
12156   // Check if the new vector type is legal.
12157   if (!isTypeLegal(VecVT)) return SDValue();
12158
12159   // Make the new BUILD_VECTOR.
12160   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12161
12162   // The new BUILD_VECTOR node has the potential to be further optimized.
12163   AddToWorklist(BV.getNode());
12164   // Bitcast to the desired type.
12165   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12166 }
12167
12168 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12169   EVT VT = N->getValueType(0);
12170
12171   unsigned NumInScalars = N->getNumOperands();
12172   SDLoc dl(N);
12173
12174   EVT SrcVT = MVT::Other;
12175   unsigned Opcode = ISD::DELETED_NODE;
12176   unsigned NumDefs = 0;
12177
12178   for (unsigned i = 0; i != NumInScalars; ++i) {
12179     SDValue In = N->getOperand(i);
12180     unsigned Opc = In.getOpcode();
12181
12182     if (Opc == ISD::UNDEF)
12183       continue;
12184
12185     // If all scalar values are floats and converted from integers.
12186     if (Opcode == ISD::DELETED_NODE &&
12187         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12188       Opcode = Opc;
12189     }
12190
12191     if (Opc != Opcode)
12192       return SDValue();
12193
12194     EVT InVT = In.getOperand(0).getValueType();
12195
12196     // If all scalar values are typed differently, bail out. It's chosen to
12197     // simplify BUILD_VECTOR of integer types.
12198     if (SrcVT == MVT::Other)
12199       SrcVT = InVT;
12200     if (SrcVT != InVT)
12201       return SDValue();
12202     NumDefs++;
12203   }
12204
12205   // If the vector has just one element defined, it's not worth to fold it into
12206   // a vectorized one.
12207   if (NumDefs < 2)
12208     return SDValue();
12209
12210   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12211          && "Should only handle conversion from integer to float.");
12212   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12213
12214   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12215
12216   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12217     return SDValue();
12218
12219   // Just because the floating-point vector type is legal does not necessarily
12220   // mean that the corresponding integer vector type is.
12221   if (!isTypeLegal(NVT))
12222     return SDValue();
12223
12224   SmallVector<SDValue, 8> Opnds;
12225   for (unsigned i = 0; i != NumInScalars; ++i) {
12226     SDValue In = N->getOperand(i);
12227
12228     if (In.getOpcode() == ISD::UNDEF)
12229       Opnds.push_back(DAG.getUNDEF(SrcVT));
12230     else
12231       Opnds.push_back(In.getOperand(0));
12232   }
12233   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12234   AddToWorklist(BV.getNode());
12235
12236   return DAG.getNode(Opcode, dl, VT, BV);
12237 }
12238
12239 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12240   unsigned NumInScalars = N->getNumOperands();
12241   SDLoc dl(N);
12242   EVT VT = N->getValueType(0);
12243
12244   // A vector built entirely of undefs is undef.
12245   if (ISD::allOperandsUndef(N))
12246     return DAG.getUNDEF(VT);
12247
12248   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12249     return V;
12250
12251   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12252     return V;
12253
12254   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12255   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12256   // at most two distinct vectors, turn this into a shuffle node.
12257
12258   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12259   if (!isTypeLegal(VT))
12260     return SDValue();
12261
12262   // May only combine to shuffle after legalize if shuffle is legal.
12263   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12264     return SDValue();
12265
12266   SDValue VecIn1, VecIn2;
12267   bool UsesZeroVector = false;
12268   for (unsigned i = 0; i != NumInScalars; ++i) {
12269     SDValue Op = N->getOperand(i);
12270     // Ignore undef inputs.
12271     if (Op.getOpcode() == ISD::UNDEF) continue;
12272
12273     // See if we can combine this build_vector into a blend with a zero vector.
12274     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12275       UsesZeroVector = true;
12276       continue;
12277     }
12278
12279     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12280     // constant index, bail out.
12281     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12282         !isa<ConstantSDNode>(Op.getOperand(1))) {
12283       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12284       break;
12285     }
12286
12287     // We allow up to two distinct input vectors.
12288     SDValue ExtractedFromVec = Op.getOperand(0);
12289     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12290       continue;
12291
12292     if (!VecIn1.getNode()) {
12293       VecIn1 = ExtractedFromVec;
12294     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12295       VecIn2 = ExtractedFromVec;
12296     } else {
12297       // Too many inputs.
12298       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12299       break;
12300     }
12301   }
12302
12303   // If everything is good, we can make a shuffle operation.
12304   if (VecIn1.getNode()) {
12305     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12306     SmallVector<int, 8> Mask;
12307     for (unsigned i = 0; i != NumInScalars; ++i) {
12308       unsigned Opcode = N->getOperand(i).getOpcode();
12309       if (Opcode == ISD::UNDEF) {
12310         Mask.push_back(-1);
12311         continue;
12312       }
12313
12314       // Operands can also be zero.
12315       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12316         assert(UsesZeroVector &&
12317                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12318                "Unexpected node found!");
12319         Mask.push_back(NumInScalars+i);
12320         continue;
12321       }
12322
12323       // If extracting from the first vector, just use the index directly.
12324       SDValue Extract = N->getOperand(i);
12325       SDValue ExtVal = Extract.getOperand(1);
12326       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12327       if (Extract.getOperand(0) == VecIn1) {
12328         Mask.push_back(ExtIndex);
12329         continue;
12330       }
12331
12332       // Otherwise, use InIdx + InputVecSize
12333       Mask.push_back(InNumElements + ExtIndex);
12334     }
12335
12336     // Avoid introducing illegal shuffles with zero.
12337     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12338       return SDValue();
12339
12340     // We can't generate a shuffle node with mismatched input and output types.
12341     // Attempt to transform a single input vector to the correct type.
12342     if ((VT != VecIn1.getValueType())) {
12343       // If the input vector type has a different base type to the output
12344       // vector type, bail out.
12345       EVT VTElemType = VT.getVectorElementType();
12346       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12347           (VecIn2.getNode() &&
12348            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12349         return SDValue();
12350
12351       // If the input vector is too small, widen it.
12352       // We only support widening of vectors which are half the size of the
12353       // output registers. For example XMM->YMM widening on X86 with AVX.
12354       EVT VecInT = VecIn1.getValueType();
12355       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12356         // If we only have one small input, widen it by adding undef values.
12357         if (!VecIn2.getNode())
12358           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12359                                DAG.getUNDEF(VecIn1.getValueType()));
12360         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12361           // If we have two small inputs of the same type, try to concat them.
12362           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12363           VecIn2 = SDValue(nullptr, 0);
12364         } else
12365           return SDValue();
12366       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12367         // If the input vector is too large, try to split it.
12368         // We don't support having two input vectors that are too large.
12369         // If the zero vector was used, we can not split the vector,
12370         // since we'd need 3 inputs.
12371         if (UsesZeroVector || VecIn2.getNode())
12372           return SDValue();
12373
12374         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12375           return SDValue();
12376
12377         // Try to replace VecIn1 with two extract_subvectors
12378         // No need to update the masks, they should still be correct.
12379         VecIn2 = DAG.getNode(
12380             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12381             DAG.getConstant(VT.getVectorNumElements(), dl,
12382                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12383         VecIn1 = DAG.getNode(
12384             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12385             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12386       } else
12387         return SDValue();
12388     }
12389
12390     if (UsesZeroVector)
12391       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12392                                 DAG.getConstantFP(0.0, dl, VT);
12393     else
12394       // If VecIn2 is unused then change it to undef.
12395       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12396
12397     // Check that we were able to transform all incoming values to the same
12398     // type.
12399     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12400         VecIn1.getValueType() != VT)
12401           return SDValue();
12402
12403     // Return the new VECTOR_SHUFFLE node.
12404     SDValue Ops[2];
12405     Ops[0] = VecIn1;
12406     Ops[1] = VecIn2;
12407     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12408   }
12409
12410   return SDValue();
12411 }
12412
12413 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12415   EVT OpVT = N->getOperand(0).getValueType();
12416
12417   // If the operands are legal vectors, leave them alone.
12418   if (TLI.isTypeLegal(OpVT))
12419     return SDValue();
12420
12421   SDLoc DL(N);
12422   EVT VT = N->getValueType(0);
12423   SmallVector<SDValue, 8> Ops;
12424
12425   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12426   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12427
12428   // Keep track of what we encounter.
12429   bool AnyInteger = false;
12430   bool AnyFP = false;
12431   for (const SDValue &Op : N->ops()) {
12432     if (ISD::BITCAST == Op.getOpcode() &&
12433         !Op.getOperand(0).getValueType().isVector())
12434       Ops.push_back(Op.getOperand(0));
12435     else if (ISD::UNDEF == Op.getOpcode())
12436       Ops.push_back(ScalarUndef);
12437     else
12438       return SDValue();
12439
12440     // Note whether we encounter an integer or floating point scalar.
12441     // If it's neither, bail out, it could be something weird like x86mmx.
12442     EVT LastOpVT = Ops.back().getValueType();
12443     if (LastOpVT.isFloatingPoint())
12444       AnyFP = true;
12445     else if (LastOpVT.isInteger())
12446       AnyInteger = true;
12447     else
12448       return SDValue();
12449   }
12450
12451   // If any of the operands is a floating point scalar bitcast to a vector,
12452   // use floating point types throughout, and bitcast everything.
12453   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12454   if (AnyFP) {
12455     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12456     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12457     if (AnyInteger) {
12458       for (SDValue &Op : Ops) {
12459         if (Op.getValueType() == SVT)
12460           continue;
12461         if (Op.getOpcode() == ISD::UNDEF)
12462           Op = ScalarUndef;
12463         else
12464           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12465       }
12466     }
12467   }
12468
12469   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12470                                VT.getSizeInBits() / SVT.getSizeInBits());
12471   return DAG.getNode(ISD::BITCAST, DL, VT,
12472                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12473 }
12474
12475 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12476 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12477 // most two distinct vectors the same size as the result, attempt to turn this
12478 // into a legal shuffle.
12479 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12480   EVT VT = N->getValueType(0);
12481   EVT OpVT = N->getOperand(0).getValueType();
12482   int NumElts = VT.getVectorNumElements();
12483   int NumOpElts = OpVT.getVectorNumElements();
12484
12485   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12486   SmallVector<int, 8> Mask;
12487
12488   for (SDValue Op : N->ops()) {
12489     // Peek through any bitcast.
12490     while (Op.getOpcode() == ISD::BITCAST)
12491       Op = Op.getOperand(0);
12492
12493     // UNDEF nodes convert to UNDEF shuffle mask values.
12494     if (Op.getOpcode() == ISD::UNDEF) {
12495       Mask.append((unsigned)NumOpElts, -1);
12496       continue;
12497     }
12498
12499     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12500       return SDValue();
12501
12502     // What vector are we extracting the subvector from and at what index?
12503     SDValue ExtVec = Op.getOperand(0);
12504
12505     // We want the EVT of the original extraction to correctly scale the
12506     // extraction index.
12507     EVT ExtVT = ExtVec.getValueType();
12508
12509     // Peek through any bitcast.
12510     while (ExtVec.getOpcode() == ISD::BITCAST)
12511       ExtVec = ExtVec.getOperand(0);
12512
12513     // UNDEF nodes convert to UNDEF shuffle mask values.
12514     if (ExtVec.getOpcode() == ISD::UNDEF) {
12515       Mask.append((unsigned)NumOpElts, -1);
12516       continue;
12517     }
12518
12519     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12520       return SDValue();
12521     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12522
12523     // Ensure that we are extracting a subvector from a vector the same
12524     // size as the result.
12525     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12526       return SDValue();
12527
12528     // Scale the subvector index to account for any bitcast.
12529     int NumExtElts = ExtVT.getVectorNumElements();
12530     if (0 == (NumExtElts % NumElts))
12531       ExtIdx /= (NumExtElts / NumElts);
12532     else if (0 == (NumElts % NumExtElts))
12533       ExtIdx *= (NumElts / NumExtElts);
12534     else
12535       return SDValue();
12536
12537     // At most we can reference 2 inputs in the final shuffle.
12538     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12539       SV0 = ExtVec;
12540       for (int i = 0; i != NumOpElts; ++i)
12541         Mask.push_back(i + ExtIdx);
12542     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12543       SV1 = ExtVec;
12544       for (int i = 0; i != NumOpElts; ++i)
12545         Mask.push_back(i + ExtIdx + NumElts);
12546     } else {
12547       return SDValue();
12548     }
12549   }
12550
12551   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12552     return SDValue();
12553
12554   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12555                               DAG.getBitcast(VT, SV1), Mask);
12556 }
12557
12558 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12559   // If we only have one input vector, we don't need to do any concatenation.
12560   if (N->getNumOperands() == 1)
12561     return N->getOperand(0);
12562
12563   // Check if all of the operands are undefs.
12564   EVT VT = N->getValueType(0);
12565   if (ISD::allOperandsUndef(N))
12566     return DAG.getUNDEF(VT);
12567
12568   // Optimize concat_vectors where all but the first of the vectors are undef.
12569   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12570         return Op.getOpcode() == ISD::UNDEF;
12571       })) {
12572     SDValue In = N->getOperand(0);
12573     assert(In.getValueType().isVector() && "Must concat vectors");
12574
12575     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12576     if (In->getOpcode() == ISD::BITCAST &&
12577         !In->getOperand(0)->getValueType(0).isVector()) {
12578       SDValue Scalar = In->getOperand(0);
12579
12580       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12581       // look through the trunc so we can still do the transform:
12582       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12583       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12584           !TLI.isTypeLegal(Scalar.getValueType()) &&
12585           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12586         Scalar = Scalar->getOperand(0);
12587
12588       EVT SclTy = Scalar->getValueType(0);
12589
12590       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12591         return SDValue();
12592
12593       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12594                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12595       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12596         return SDValue();
12597
12598       SDLoc dl = SDLoc(N);
12599       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12600       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12601     }
12602   }
12603
12604   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12605   // We have already tested above for an UNDEF only concatenation.
12606   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12607   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12608   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12609     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12610   };
12611   bool AllBuildVectorsOrUndefs =
12612       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12613   if (AllBuildVectorsOrUndefs) {
12614     SmallVector<SDValue, 8> Opnds;
12615     EVT SVT = VT.getScalarType();
12616
12617     EVT MinVT = SVT;
12618     if (!SVT.isFloatingPoint()) {
12619       // If BUILD_VECTOR are from built from integer, they may have different
12620       // operand types. Get the smallest type and truncate all operands to it.
12621       bool FoundMinVT = false;
12622       for (const SDValue &Op : N->ops())
12623         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12624           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12625           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12626           FoundMinVT = true;
12627         }
12628       assert(FoundMinVT && "Concat vector type mismatch");
12629     }
12630
12631     for (const SDValue &Op : N->ops()) {
12632       EVT OpVT = Op.getValueType();
12633       unsigned NumElts = OpVT.getVectorNumElements();
12634
12635       if (ISD::UNDEF == Op.getOpcode())
12636         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12637
12638       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12639         if (SVT.isFloatingPoint()) {
12640           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12641           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12642         } else {
12643           for (unsigned i = 0; i != NumElts; ++i)
12644             Opnds.push_back(
12645                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12646         }
12647       }
12648     }
12649
12650     assert(VT.getVectorNumElements() == Opnds.size() &&
12651            "Concat vector type mismatch");
12652     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12653   }
12654
12655   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12656   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12657     return V;
12658
12659   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12660   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12661     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12662       return V;
12663
12664   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12665   // nodes often generate nop CONCAT_VECTOR nodes.
12666   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12667   // place the incoming vectors at the exact same location.
12668   SDValue SingleSource = SDValue();
12669   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12670
12671   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12672     SDValue Op = N->getOperand(i);
12673
12674     if (Op.getOpcode() == ISD::UNDEF)
12675       continue;
12676
12677     // Check if this is the identity extract:
12678     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12679       return SDValue();
12680
12681     // Find the single incoming vector for the extract_subvector.
12682     if (SingleSource.getNode()) {
12683       if (Op.getOperand(0) != SingleSource)
12684         return SDValue();
12685     } else {
12686       SingleSource = Op.getOperand(0);
12687
12688       // Check the source type is the same as the type of the result.
12689       // If not, this concat may extend the vector, so we can not
12690       // optimize it away.
12691       if (SingleSource.getValueType() != N->getValueType(0))
12692         return SDValue();
12693     }
12694
12695     unsigned IdentityIndex = i * PartNumElem;
12696     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12697     // The extract index must be constant.
12698     if (!CS)
12699       return SDValue();
12700
12701     // Check that we are reading from the identity index.
12702     if (CS->getZExtValue() != IdentityIndex)
12703       return SDValue();
12704   }
12705
12706   if (SingleSource.getNode())
12707     return SingleSource;
12708
12709   return SDValue();
12710 }
12711
12712 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12713   EVT NVT = N->getValueType(0);
12714   SDValue V = N->getOperand(0);
12715
12716   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12717     // Combine:
12718     //    (extract_subvec (concat V1, V2, ...), i)
12719     // Into:
12720     //    Vi if possible
12721     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12722     // type.
12723     if (V->getOperand(0).getValueType() != NVT)
12724       return SDValue();
12725     unsigned Idx = N->getConstantOperandVal(1);
12726     unsigned NumElems = NVT.getVectorNumElements();
12727     assert((Idx % NumElems) == 0 &&
12728            "IDX in concat is not a multiple of the result vector length.");
12729     return V->getOperand(Idx / NumElems);
12730   }
12731
12732   // Skip bitcasting
12733   if (V->getOpcode() == ISD::BITCAST)
12734     V = V.getOperand(0);
12735
12736   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12737     SDLoc dl(N);
12738     // Handle only simple case where vector being inserted and vector
12739     // being extracted are of same type, and are half size of larger vectors.
12740     EVT BigVT = V->getOperand(0).getValueType();
12741     EVT SmallVT = V->getOperand(1).getValueType();
12742     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12743       return SDValue();
12744
12745     // Only handle cases where both indexes are constants with the same type.
12746     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12747     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12748
12749     if (InsIdx && ExtIdx &&
12750         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12751         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12752       // Combine:
12753       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12754       // Into:
12755       //    indices are equal or bit offsets are equal => V1
12756       //    otherwise => (extract_subvec V1, ExtIdx)
12757       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12758           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12759         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12760       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12761                          DAG.getNode(ISD::BITCAST, dl,
12762                                      N->getOperand(0).getValueType(),
12763                                      V->getOperand(0)), N->getOperand(1));
12764     }
12765   }
12766
12767   return SDValue();
12768 }
12769
12770 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12771                                                  SDValue V, SelectionDAG &DAG) {
12772   SDLoc DL(V);
12773   EVT VT = V.getValueType();
12774
12775   switch (V.getOpcode()) {
12776   default:
12777     return V;
12778
12779   case ISD::CONCAT_VECTORS: {
12780     EVT OpVT = V->getOperand(0).getValueType();
12781     int OpSize = OpVT.getVectorNumElements();
12782     SmallBitVector OpUsedElements(OpSize, false);
12783     bool FoundSimplification = false;
12784     SmallVector<SDValue, 4> NewOps;
12785     NewOps.reserve(V->getNumOperands());
12786     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12787       SDValue Op = V->getOperand(i);
12788       bool OpUsed = false;
12789       for (int j = 0; j < OpSize; ++j)
12790         if (UsedElements[i * OpSize + j]) {
12791           OpUsedElements[j] = true;
12792           OpUsed = true;
12793         }
12794       NewOps.push_back(
12795           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12796                  : DAG.getUNDEF(OpVT));
12797       FoundSimplification |= Op == NewOps.back();
12798       OpUsedElements.reset();
12799     }
12800     if (FoundSimplification)
12801       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12802     return V;
12803   }
12804
12805   case ISD::INSERT_SUBVECTOR: {
12806     SDValue BaseV = V->getOperand(0);
12807     SDValue SubV = V->getOperand(1);
12808     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12809     if (!IdxN)
12810       return V;
12811
12812     int SubSize = SubV.getValueType().getVectorNumElements();
12813     int Idx = IdxN->getZExtValue();
12814     bool SubVectorUsed = false;
12815     SmallBitVector SubUsedElements(SubSize, false);
12816     for (int i = 0; i < SubSize; ++i)
12817       if (UsedElements[i + Idx]) {
12818         SubVectorUsed = true;
12819         SubUsedElements[i] = true;
12820         UsedElements[i + Idx] = false;
12821       }
12822
12823     // Now recurse on both the base and sub vectors.
12824     SDValue SimplifiedSubV =
12825         SubVectorUsed
12826             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12827             : DAG.getUNDEF(SubV.getValueType());
12828     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12829     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12830       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12831                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12832     return V;
12833   }
12834   }
12835 }
12836
12837 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12838                                        SDValue N1, SelectionDAG &DAG) {
12839   EVT VT = SVN->getValueType(0);
12840   int NumElts = VT.getVectorNumElements();
12841   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12842   for (int M : SVN->getMask())
12843     if (M >= 0 && M < NumElts)
12844       N0UsedElements[M] = true;
12845     else if (M >= NumElts)
12846       N1UsedElements[M - NumElts] = true;
12847
12848   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12849   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12850   if (S0 == N0 && S1 == N1)
12851     return SDValue();
12852
12853   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12854 }
12855
12856 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12857 // or turn a shuffle of a single concat into simpler shuffle then concat.
12858 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12859   EVT VT = N->getValueType(0);
12860   unsigned NumElts = VT.getVectorNumElements();
12861
12862   SDValue N0 = N->getOperand(0);
12863   SDValue N1 = N->getOperand(1);
12864   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12865
12866   SmallVector<SDValue, 4> Ops;
12867   EVT ConcatVT = N0.getOperand(0).getValueType();
12868   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12869   unsigned NumConcats = NumElts / NumElemsPerConcat;
12870
12871   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12872   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12873   // half vector elements.
12874   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12875       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12876                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12877     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12878                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12879     N1 = DAG.getUNDEF(ConcatVT);
12880     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12881   }
12882
12883   // Look at every vector that's inserted. We're looking for exact
12884   // subvector-sized copies from a concatenated vector
12885   for (unsigned I = 0; I != NumConcats; ++I) {
12886     // Make sure we're dealing with a copy.
12887     unsigned Begin = I * NumElemsPerConcat;
12888     bool AllUndef = true, NoUndef = true;
12889     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12890       if (SVN->getMaskElt(J) >= 0)
12891         AllUndef = false;
12892       else
12893         NoUndef = false;
12894     }
12895
12896     if (NoUndef) {
12897       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12898         return SDValue();
12899
12900       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12901         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12902           return SDValue();
12903
12904       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12905       if (FirstElt < N0.getNumOperands())
12906         Ops.push_back(N0.getOperand(FirstElt));
12907       else
12908         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12909
12910     } else if (AllUndef) {
12911       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12912     } else { // Mixed with general masks and undefs, can't do optimization.
12913       return SDValue();
12914     }
12915   }
12916
12917   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12918 }
12919
12920 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12921   EVT VT = N->getValueType(0);
12922   unsigned NumElts = VT.getVectorNumElements();
12923
12924   SDValue N0 = N->getOperand(0);
12925   SDValue N1 = N->getOperand(1);
12926
12927   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12928
12929   // Canonicalize shuffle undef, undef -> undef
12930   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12931     return DAG.getUNDEF(VT);
12932
12933   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12934
12935   // Canonicalize shuffle v, v -> v, undef
12936   if (N0 == N1) {
12937     SmallVector<int, 8> NewMask;
12938     for (unsigned i = 0; i != NumElts; ++i) {
12939       int Idx = SVN->getMaskElt(i);
12940       if (Idx >= (int)NumElts) Idx -= NumElts;
12941       NewMask.push_back(Idx);
12942     }
12943     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12944                                 &NewMask[0]);
12945   }
12946
12947   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12948   if (N0.getOpcode() == ISD::UNDEF) {
12949     SmallVector<int, 8> NewMask;
12950     for (unsigned i = 0; i != NumElts; ++i) {
12951       int Idx = SVN->getMaskElt(i);
12952       if (Idx >= 0) {
12953         if (Idx >= (int)NumElts)
12954           Idx -= NumElts;
12955         else
12956           Idx = -1; // remove reference to lhs
12957       }
12958       NewMask.push_back(Idx);
12959     }
12960     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12961                                 &NewMask[0]);
12962   }
12963
12964   // Remove references to rhs if it is undef
12965   if (N1.getOpcode() == ISD::UNDEF) {
12966     bool Changed = false;
12967     SmallVector<int, 8> NewMask;
12968     for (unsigned i = 0; i != NumElts; ++i) {
12969       int Idx = SVN->getMaskElt(i);
12970       if (Idx >= (int)NumElts) {
12971         Idx = -1;
12972         Changed = true;
12973       }
12974       NewMask.push_back(Idx);
12975     }
12976     if (Changed)
12977       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12978   }
12979
12980   // If it is a splat, check if the argument vector is another splat or a
12981   // build_vector.
12982   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12983     SDNode *V = N0.getNode();
12984
12985     // If this is a bit convert that changes the element type of the vector but
12986     // not the number of vector elements, look through it.  Be careful not to
12987     // look though conversions that change things like v4f32 to v2f64.
12988     if (V->getOpcode() == ISD::BITCAST) {
12989       SDValue ConvInput = V->getOperand(0);
12990       if (ConvInput.getValueType().isVector() &&
12991           ConvInput.getValueType().getVectorNumElements() == NumElts)
12992         V = ConvInput.getNode();
12993     }
12994
12995     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12996       assert(V->getNumOperands() == NumElts &&
12997              "BUILD_VECTOR has wrong number of operands");
12998       SDValue Base;
12999       bool AllSame = true;
13000       for (unsigned i = 0; i != NumElts; ++i) {
13001         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13002           Base = V->getOperand(i);
13003           break;
13004         }
13005       }
13006       // Splat of <u, u, u, u>, return <u, u, u, u>
13007       if (!Base.getNode())
13008         return N0;
13009       for (unsigned i = 0; i != NumElts; ++i) {
13010         if (V->getOperand(i) != Base) {
13011           AllSame = false;
13012           break;
13013         }
13014       }
13015       // Splat of <x, x, x, x>, return <x, x, x, x>
13016       if (AllSame)
13017         return N0;
13018
13019       // Canonicalize any other splat as a build_vector.
13020       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13021       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13022       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13023                                   V->getValueType(0), Ops);
13024
13025       // We may have jumped through bitcasts, so the type of the
13026       // BUILD_VECTOR may not match the type of the shuffle.
13027       if (V->getValueType(0) != VT)
13028         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13029       return NewBV;
13030     }
13031   }
13032
13033   // There are various patterns used to build up a vector from smaller vectors,
13034   // subvectors, or elements. Scan chains of these and replace unused insertions
13035   // or components with undef.
13036   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13037     return S;
13038
13039   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13040       Level < AfterLegalizeVectorOps &&
13041       (N1.getOpcode() == ISD::UNDEF ||
13042       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13043        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13044     SDValue V = partitionShuffleOfConcats(N, DAG);
13045
13046     if (V.getNode())
13047       return V;
13048   }
13049
13050   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13051   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13052   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13053     SmallVector<SDValue, 8> Ops;
13054     for (int M : SVN->getMask()) {
13055       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13056       if (M >= 0) {
13057         int Idx = M % NumElts;
13058         SDValue &S = (M < (int)NumElts ? N0 : N1);
13059         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13060           Op = S.getOperand(Idx);
13061         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13062           if (Idx == 0)
13063             Op = S.getOperand(0);
13064         } else {
13065           // Operand can't be combined - bail out.
13066           break;
13067         }
13068       }
13069       Ops.push_back(Op);
13070     }
13071     if (Ops.size() == VT.getVectorNumElements()) {
13072       // BUILD_VECTOR requires all inputs to be of the same type, find the
13073       // maximum type and extend them all.
13074       EVT SVT = VT.getScalarType();
13075       if (SVT.isInteger())
13076         for (SDValue &Op : Ops)
13077           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13078       if (SVT != VT.getScalarType())
13079         for (SDValue &Op : Ops)
13080           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13081                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13082                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13083       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13084     }
13085   }
13086
13087   // If this shuffle only has a single input that is a bitcasted shuffle,
13088   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13089   // back to their original types.
13090   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13091       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13092       TLI.isTypeLegal(VT)) {
13093
13094     // Peek through the bitcast only if there is one user.
13095     SDValue BC0 = N0;
13096     while (BC0.getOpcode() == ISD::BITCAST) {
13097       if (!BC0.hasOneUse())
13098         break;
13099       BC0 = BC0.getOperand(0);
13100     }
13101
13102     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13103       if (Scale == 1)
13104         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13105
13106       SmallVector<int, 8> NewMask;
13107       for (int M : Mask)
13108         for (int s = 0; s != Scale; ++s)
13109           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13110       return NewMask;
13111     };
13112
13113     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13114       EVT SVT = VT.getScalarType();
13115       EVT InnerVT = BC0->getValueType(0);
13116       EVT InnerSVT = InnerVT.getScalarType();
13117
13118       // Determine which shuffle works with the smaller scalar type.
13119       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13120       EVT ScaleSVT = ScaleVT.getScalarType();
13121
13122       if (TLI.isTypeLegal(ScaleVT) &&
13123           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13124           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13125
13126         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13127         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13128
13129         // Scale the shuffle masks to the smaller scalar type.
13130         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13131         SmallVector<int, 8> InnerMask =
13132             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13133         SmallVector<int, 8> OuterMask =
13134             ScaleShuffleMask(SVN->getMask(), OuterScale);
13135
13136         // Merge the shuffle masks.
13137         SmallVector<int, 8> NewMask;
13138         for (int M : OuterMask)
13139           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13140
13141         // Test for shuffle mask legality over both commutations.
13142         SDValue SV0 = BC0->getOperand(0);
13143         SDValue SV1 = BC0->getOperand(1);
13144         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13145         if (!LegalMask) {
13146           std::swap(SV0, SV1);
13147           ShuffleVectorSDNode::commuteMask(NewMask);
13148           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13149         }
13150
13151         if (LegalMask) {
13152           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13153           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13154           return DAG.getNode(
13155               ISD::BITCAST, SDLoc(N), VT,
13156               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13157         }
13158       }
13159     }
13160   }
13161
13162   // Canonicalize shuffles according to rules:
13163   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13164   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13165   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13166   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13167       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13168       TLI.isTypeLegal(VT)) {
13169     // The incoming shuffle must be of the same type as the result of the
13170     // current shuffle.
13171     assert(N1->getOperand(0).getValueType() == VT &&
13172            "Shuffle types don't match");
13173
13174     SDValue SV0 = N1->getOperand(0);
13175     SDValue SV1 = N1->getOperand(1);
13176     bool HasSameOp0 = N0 == SV0;
13177     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13178     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13179       // Commute the operands of this shuffle so that next rule
13180       // will trigger.
13181       return DAG.getCommutedVectorShuffle(*SVN);
13182   }
13183
13184   // Try to fold according to rules:
13185   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13186   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13187   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13188   // Don't try to fold shuffles with illegal type.
13189   // Only fold if this shuffle is the only user of the other shuffle.
13190   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13191       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13192     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13193
13194     // The incoming shuffle must be of the same type as the result of the
13195     // current shuffle.
13196     assert(OtherSV->getOperand(0).getValueType() == VT &&
13197            "Shuffle types don't match");
13198
13199     SDValue SV0, SV1;
13200     SmallVector<int, 4> Mask;
13201     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13202     // operand, and SV1 as the second operand.
13203     for (unsigned i = 0; i != NumElts; ++i) {
13204       int Idx = SVN->getMaskElt(i);
13205       if (Idx < 0) {
13206         // Propagate Undef.
13207         Mask.push_back(Idx);
13208         continue;
13209       }
13210
13211       SDValue CurrentVec;
13212       if (Idx < (int)NumElts) {
13213         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13214         // shuffle mask to identify which vector is actually referenced.
13215         Idx = OtherSV->getMaskElt(Idx);
13216         if (Idx < 0) {
13217           // Propagate Undef.
13218           Mask.push_back(Idx);
13219           continue;
13220         }
13221
13222         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13223                                            : OtherSV->getOperand(1);
13224       } else {
13225         // This shuffle index references an element within N1.
13226         CurrentVec = N1;
13227       }
13228
13229       // Simple case where 'CurrentVec' is UNDEF.
13230       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13231         Mask.push_back(-1);
13232         continue;
13233       }
13234
13235       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13236       // will be the first or second operand of the combined shuffle.
13237       Idx = Idx % NumElts;
13238       if (!SV0.getNode() || SV0 == CurrentVec) {
13239         // Ok. CurrentVec is the left hand side.
13240         // Update the mask accordingly.
13241         SV0 = CurrentVec;
13242         Mask.push_back(Idx);
13243         continue;
13244       }
13245
13246       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13247       if (SV1.getNode() && SV1 != CurrentVec)
13248         return SDValue();
13249
13250       // Ok. CurrentVec is the right hand side.
13251       // Update the mask accordingly.
13252       SV1 = CurrentVec;
13253       Mask.push_back(Idx + NumElts);
13254     }
13255
13256     // Check if all indices in Mask are Undef. In case, propagate Undef.
13257     bool isUndefMask = true;
13258     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13259       isUndefMask &= Mask[i] < 0;
13260
13261     if (isUndefMask)
13262       return DAG.getUNDEF(VT);
13263
13264     if (!SV0.getNode())
13265       SV0 = DAG.getUNDEF(VT);
13266     if (!SV1.getNode())
13267       SV1 = DAG.getUNDEF(VT);
13268
13269     // Avoid introducing shuffles with illegal mask.
13270     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13271       ShuffleVectorSDNode::commuteMask(Mask);
13272
13273       if (!TLI.isShuffleMaskLegal(Mask, VT))
13274         return SDValue();
13275
13276       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13277       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13278       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13279       std::swap(SV0, SV1);
13280     }
13281
13282     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13283     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13284     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13285     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13286   }
13287
13288   return SDValue();
13289 }
13290
13291 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13292   SDValue InVal = N->getOperand(0);
13293   EVT VT = N->getValueType(0);
13294
13295   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13296   // with a VECTOR_SHUFFLE.
13297   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13298     SDValue InVec = InVal->getOperand(0);
13299     SDValue EltNo = InVal->getOperand(1);
13300
13301     // FIXME: We could support implicit truncation if the shuffle can be
13302     // scaled to a smaller vector scalar type.
13303     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13304     if (C0 && VT == InVec.getValueType() &&
13305         VT.getScalarType() == InVal.getValueType()) {
13306       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13307       int Elt = C0->getZExtValue();
13308       NewMask[0] = Elt;
13309
13310       if (TLI.isShuffleMaskLegal(NewMask, VT))
13311         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13312                                     NewMask);
13313     }
13314   }
13315
13316   return SDValue();
13317 }
13318
13319 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13320   SDValue N0 = N->getOperand(0);
13321   SDValue N2 = N->getOperand(2);
13322
13323   // If the input vector is a concatenation, and the insert replaces
13324   // one of the halves, we can optimize into a single concat_vectors.
13325   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13326       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13327     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13328     EVT VT = N->getValueType(0);
13329
13330     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13331     // (concat_vectors Z, Y)
13332     if (InsIdx == 0)
13333       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13334                          N->getOperand(1), N0.getOperand(1));
13335
13336     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13337     // (concat_vectors X, Z)
13338     if (InsIdx == VT.getVectorNumElements()/2)
13339       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13340                          N0.getOperand(0), N->getOperand(1));
13341   }
13342
13343   return SDValue();
13344 }
13345
13346 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13347   SDValue N0 = N->getOperand(0);
13348
13349   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13350   if (N0->getOpcode() == ISD::FP16_TO_FP)
13351     return N0->getOperand(0);
13352
13353   return SDValue();
13354 }
13355
13356 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13357   SDValue N0 = N->getOperand(0);
13358
13359   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13360   if (N0->getOpcode() == ISD::AND) {
13361     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13362     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13363       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13364                          N0.getOperand(0));
13365     }
13366   }
13367
13368   return SDValue();
13369 }
13370
13371 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13372 /// with the destination vector and a zero vector.
13373 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13374 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13375 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13376   EVT VT = N->getValueType(0);
13377   SDValue LHS = N->getOperand(0);
13378   SDValue RHS = N->getOperand(1);
13379   SDLoc dl(N);
13380
13381   // Make sure we're not running after operation legalization where it
13382   // may have custom lowered the vector shuffles.
13383   if (LegalOperations)
13384     return SDValue();
13385
13386   if (N->getOpcode() != ISD::AND)
13387     return SDValue();
13388
13389   if (RHS.getOpcode() == ISD::BITCAST)
13390     RHS = RHS.getOperand(0);
13391
13392   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13393     return SDValue();
13394
13395   EVT RVT = RHS.getValueType();
13396   unsigned NumElts = RHS.getNumOperands();
13397
13398   // Attempt to create a valid clear mask, splitting the mask into
13399   // sub elements and checking to see if each is
13400   // all zeros or all ones - suitable for shuffle masking.
13401   auto BuildClearMask = [&](int Split) {
13402     int NumSubElts = NumElts * Split;
13403     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13404
13405     SmallVector<int, 8> Indices;
13406     for (int i = 0; i != NumSubElts; ++i) {
13407       int EltIdx = i / Split;
13408       int SubIdx = i % Split;
13409       SDValue Elt = RHS.getOperand(EltIdx);
13410       if (Elt.getOpcode() == ISD::UNDEF) {
13411         Indices.push_back(-1);
13412         continue;
13413       }
13414
13415       APInt Bits;
13416       if (isa<ConstantSDNode>(Elt))
13417         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13418       else if (isa<ConstantFPSDNode>(Elt))
13419         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13420       else
13421         return SDValue();
13422
13423       // Extract the sub element from the constant bit mask.
13424       if (DAG.getDataLayout().isBigEndian()) {
13425         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13426       } else {
13427         Bits = Bits.lshr(SubIdx * NumSubBits);
13428       }
13429
13430       if (Split > 1)
13431         Bits = Bits.trunc(NumSubBits);
13432
13433       if (Bits.isAllOnesValue())
13434         Indices.push_back(i);
13435       else if (Bits == 0)
13436         Indices.push_back(i + NumSubElts);
13437       else
13438         return SDValue();
13439     }
13440
13441     // Let's see if the target supports this vector_shuffle.
13442     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13443     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13444     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13445       return SDValue();
13446
13447     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13448     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13449                                                    DAG.getBitcast(ClearVT, LHS),
13450                                                    Zero, &Indices[0]));
13451   };
13452
13453   // Determine maximum split level (byte level masking).
13454   int MaxSplit = 1;
13455   if (RVT.getScalarSizeInBits() % 8 == 0)
13456     MaxSplit = RVT.getScalarSizeInBits() / 8;
13457
13458   for (int Split = 1; Split <= MaxSplit; ++Split)
13459     if (RVT.getScalarSizeInBits() % Split == 0)
13460       if (SDValue S = BuildClearMask(Split))
13461         return S;
13462
13463   return SDValue();
13464 }
13465
13466 /// Visit a binary vector operation, like ADD.
13467 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13468   assert(N->getValueType(0).isVector() &&
13469          "SimplifyVBinOp only works on vectors!");
13470
13471   SDValue LHS = N->getOperand(0);
13472   SDValue RHS = N->getOperand(1);
13473
13474   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13475   // this operation.
13476   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13477       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13478     // Check if both vectors are constants. If not bail out.
13479     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13480           cast<BuildVectorSDNode>(RHS)->isConstant()))
13481       return SDValue();
13482
13483     SmallVector<SDValue, 8> Ops;
13484     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13485       SDValue LHSOp = LHS.getOperand(i);
13486       SDValue RHSOp = RHS.getOperand(i);
13487
13488       // Can't fold divide by zero.
13489       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13490           N->getOpcode() == ISD::FDIV) {
13491         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13492              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13493           break;
13494       }
13495
13496       EVT VT = LHSOp.getValueType();
13497       EVT RVT = RHSOp.getValueType();
13498       EVT ST = VT;
13499
13500       if (RVT.getSizeInBits() < VT.getSizeInBits())
13501         ST = RVT;
13502
13503       // Integer BUILD_VECTOR operands may have types larger than the element
13504       // size (e.g., when the element type is not legal).  Prior to type
13505       // legalization, the types may not match between the two BUILD_VECTORS.
13506       // Truncate the operands to make them match.
13507       if (VT.getSizeInBits() != LHS.getValueType().getScalarSizeInBits()) {
13508         EVT ScalarT = LHS.getValueType().getScalarType();
13509         LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, LHSOp);
13510         VT = LHSOp.getValueType();
13511       }
13512       if (RVT.getSizeInBits() != RHS.getValueType().getScalarSizeInBits()) {
13513         EVT ScalarT = RHS.getValueType().getScalarType();
13514         RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, RHSOp);
13515         RVT = RHSOp.getValueType();
13516       }
13517
13518       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13519                                    LHSOp, RHSOp, N->getFlags());
13520
13521       // We need the resulting constant to be legal if we are in a phase after
13522       // legalization, so zero extend to the smallest operand type if required.
13523       if (ST != VT && Level != BeforeLegalizeTypes)
13524         FoldOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LHS), ST, FoldOp);
13525
13526       if (FoldOp.getOpcode() != ISD::UNDEF &&
13527           FoldOp.getOpcode() != ISD::Constant &&
13528           FoldOp.getOpcode() != ISD::ConstantFP)
13529         break;
13530       Ops.push_back(FoldOp);
13531       AddToWorklist(FoldOp.getNode());
13532     }
13533
13534     if (Ops.size() == LHS.getNumOperands())
13535       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13536   }
13537
13538   // Try to convert a constant mask AND into a shuffle clear mask.
13539   if (SDValue Shuffle = XformToShuffleWithZero(N))
13540     return Shuffle;
13541
13542   // Type legalization might introduce new shuffles in the DAG.
13543   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13544   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13545   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13546       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13547       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13548       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13549     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13550     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13551
13552     if (SVN0->getMask().equals(SVN1->getMask())) {
13553       EVT VT = N->getValueType(0);
13554       SDValue UndefVector = LHS.getOperand(1);
13555       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13556                                      LHS.getOperand(0), RHS.getOperand(0),
13557                                      N->getFlags());
13558       AddUsersToWorklist(N);
13559       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13560                                   &SVN0->getMask()[0]);
13561     }
13562   }
13563
13564   return SDValue();
13565 }
13566
13567 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13568                                     SDValue N1, SDValue N2){
13569   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13570
13571   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13572                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13573
13574   // If we got a simplified select_cc node back from SimplifySelectCC, then
13575   // break it down into a new SETCC node, and a new SELECT node, and then return
13576   // the SELECT node, since we were called with a SELECT node.
13577   if (SCC.getNode()) {
13578     // Check to see if we got a select_cc back (to turn into setcc/select).
13579     // Otherwise, just return whatever node we got back, like fabs.
13580     if (SCC.getOpcode() == ISD::SELECT_CC) {
13581       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13582                                   N0.getValueType(),
13583                                   SCC.getOperand(0), SCC.getOperand(1),
13584                                   SCC.getOperand(4));
13585       AddToWorklist(SETCC.getNode());
13586       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13587                            SCC.getOperand(2), SCC.getOperand(3));
13588     }
13589
13590     return SCC;
13591   }
13592   return SDValue();
13593 }
13594
13595 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13596 /// being selected between, see if we can simplify the select.  Callers of this
13597 /// should assume that TheSelect is deleted if this returns true.  As such, they
13598 /// should return the appropriate thing (e.g. the node) back to the top-level of
13599 /// the DAG combiner loop to avoid it being looked at.
13600 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13601                                     SDValue RHS) {
13602
13603   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13604   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13605   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13606     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13607       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13608       SDValue Sqrt = RHS;
13609       ISD::CondCode CC;
13610       SDValue CmpLHS;
13611       const ConstantFPSDNode *NegZero = nullptr;
13612
13613       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13614         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13615         CmpLHS = TheSelect->getOperand(0);
13616         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13617       } else {
13618         // SELECT or VSELECT
13619         SDValue Cmp = TheSelect->getOperand(0);
13620         if (Cmp.getOpcode() == ISD::SETCC) {
13621           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13622           CmpLHS = Cmp.getOperand(0);
13623           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13624         }
13625       }
13626       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13627           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13628           CC == ISD::SETULT || CC == ISD::SETLT)) {
13629         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13630         CombineTo(TheSelect, Sqrt);
13631         return true;
13632       }
13633     }
13634   }
13635   // Cannot simplify select with vector condition
13636   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13637
13638   // If this is a select from two identical things, try to pull the operation
13639   // through the select.
13640   if (LHS.getOpcode() != RHS.getOpcode() ||
13641       !LHS.hasOneUse() || !RHS.hasOneUse())
13642     return false;
13643
13644   // If this is a load and the token chain is identical, replace the select
13645   // of two loads with a load through a select of the address to load from.
13646   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13647   // constants have been dropped into the constant pool.
13648   if (LHS.getOpcode() == ISD::LOAD) {
13649     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13650     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13651
13652     // Token chains must be identical.
13653     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13654         // Do not let this transformation reduce the number of volatile loads.
13655         LLD->isVolatile() || RLD->isVolatile() ||
13656         // FIXME: If either is a pre/post inc/dec load,
13657         // we'd need to split out the address adjustment.
13658         LLD->isIndexed() || RLD->isIndexed() ||
13659         // If this is an EXTLOAD, the VT's must match.
13660         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13661         // If this is an EXTLOAD, the kind of extension must match.
13662         (LLD->getExtensionType() != RLD->getExtensionType() &&
13663          // The only exception is if one of the extensions is anyext.
13664          LLD->getExtensionType() != ISD::EXTLOAD &&
13665          RLD->getExtensionType() != ISD::EXTLOAD) ||
13666         // FIXME: this discards src value information.  This is
13667         // over-conservative. It would be beneficial to be able to remember
13668         // both potential memory locations.  Since we are discarding
13669         // src value info, don't do the transformation if the memory
13670         // locations are not in the default address space.
13671         LLD->getPointerInfo().getAddrSpace() != 0 ||
13672         RLD->getPointerInfo().getAddrSpace() != 0 ||
13673         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13674                                       LLD->getBasePtr().getValueType()))
13675       return false;
13676
13677     // Check that the select condition doesn't reach either load.  If so,
13678     // folding this will induce a cycle into the DAG.  If not, this is safe to
13679     // xform, so create a select of the addresses.
13680     SDValue Addr;
13681     if (TheSelect->getOpcode() == ISD::SELECT) {
13682       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13683       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13684           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13685         return false;
13686       // The loads must not depend on one another.
13687       if (LLD->isPredecessorOf(RLD) ||
13688           RLD->isPredecessorOf(LLD))
13689         return false;
13690       Addr = DAG.getSelect(SDLoc(TheSelect),
13691                            LLD->getBasePtr().getValueType(),
13692                            TheSelect->getOperand(0), LLD->getBasePtr(),
13693                            RLD->getBasePtr());
13694     } else {  // Otherwise SELECT_CC
13695       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13696       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13697
13698       if ((LLD->hasAnyUseOfValue(1) &&
13699            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13700           (RLD->hasAnyUseOfValue(1) &&
13701            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13702         return false;
13703
13704       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13705                          LLD->getBasePtr().getValueType(),
13706                          TheSelect->getOperand(0),
13707                          TheSelect->getOperand(1),
13708                          LLD->getBasePtr(), RLD->getBasePtr(),
13709                          TheSelect->getOperand(4));
13710     }
13711
13712     SDValue Load;
13713     // It is safe to replace the two loads if they have different alignments,
13714     // but the new load must be the minimum (most restrictive) alignment of the
13715     // inputs.
13716     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13717     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13718     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13719       Load = DAG.getLoad(TheSelect->getValueType(0),
13720                          SDLoc(TheSelect),
13721                          // FIXME: Discards pointer and AA info.
13722                          LLD->getChain(), Addr, MachinePointerInfo(),
13723                          LLD->isVolatile(), LLD->isNonTemporal(),
13724                          isInvariant, Alignment);
13725     } else {
13726       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13727                             RLD->getExtensionType() : LLD->getExtensionType(),
13728                             SDLoc(TheSelect),
13729                             TheSelect->getValueType(0),
13730                             // FIXME: Discards pointer and AA info.
13731                             LLD->getChain(), Addr, MachinePointerInfo(),
13732                             LLD->getMemoryVT(), LLD->isVolatile(),
13733                             LLD->isNonTemporal(), isInvariant, Alignment);
13734     }
13735
13736     // Users of the select now use the result of the load.
13737     CombineTo(TheSelect, Load);
13738
13739     // Users of the old loads now use the new load's chain.  We know the
13740     // old-load value is dead now.
13741     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13742     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13743     return true;
13744   }
13745
13746   return false;
13747 }
13748
13749 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13750 /// where 'cond' is the comparison specified by CC.
13751 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13752                                       SDValue N2, SDValue N3,
13753                                       ISD::CondCode CC, bool NotExtCompare) {
13754   // (x ? y : y) -> y.
13755   if (N2 == N3) return N2;
13756
13757   EVT VT = N2.getValueType();
13758   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13759   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13760
13761   // Determine if the condition we're dealing with is constant
13762   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13763                               N0, N1, CC, DL, false);
13764   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13765
13766   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13767     // fold select_cc true, x, y -> x
13768     // fold select_cc false, x, y -> y
13769     return !SCCC->isNullValue() ? N2 : N3;
13770   }
13771
13772   // Check to see if we can simplify the select into an fabs node
13773   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13774     // Allow either -0.0 or 0.0
13775     if (CFP->isZero()) {
13776       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13777       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13778           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13779           N2 == N3.getOperand(0))
13780         return DAG.getNode(ISD::FABS, DL, VT, N0);
13781
13782       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13783       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13784           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13785           N2.getOperand(0) == N3)
13786         return DAG.getNode(ISD::FABS, DL, VT, N3);
13787     }
13788   }
13789
13790   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13791   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13792   // in it.  This is a win when the constant is not otherwise available because
13793   // it replaces two constant pool loads with one.  We only do this if the FP
13794   // type is known to be legal, because if it isn't, then we are before legalize
13795   // types an we want the other legalization to happen first (e.g. to avoid
13796   // messing with soft float) and if the ConstantFP is not legal, because if
13797   // it is legal, we may not need to store the FP constant in a constant pool.
13798   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13799     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13800       if (TLI.isTypeLegal(N2.getValueType()) &&
13801           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13802                TargetLowering::Legal &&
13803            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13804            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13805           // If both constants have multiple uses, then we won't need to do an
13806           // extra load, they are likely around in registers for other users.
13807           (TV->hasOneUse() || FV->hasOneUse())) {
13808         Constant *Elts[] = {
13809           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13810           const_cast<ConstantFP*>(TV->getConstantFPValue())
13811         };
13812         Type *FPTy = Elts[0]->getType();
13813         const DataLayout &TD = DAG.getDataLayout();
13814
13815         // Create a ConstantArray of the two constants.
13816         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13817         SDValue CPIdx =
13818             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13819                                 TD.getPrefTypeAlignment(FPTy));
13820         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13821
13822         // Get the offsets to the 0 and 1 element of the array so that we can
13823         // select between them.
13824         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13825         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13826         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13827
13828         SDValue Cond = DAG.getSetCC(DL,
13829                                     getSetCCResultType(N0.getValueType()),
13830                                     N0, N1, CC);
13831         AddToWorklist(Cond.getNode());
13832         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13833                                           Cond, One, Zero);
13834         AddToWorklist(CstOffset.getNode());
13835         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13836                             CstOffset);
13837         AddToWorklist(CPIdx.getNode());
13838         return DAG.getLoad(
13839             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13840             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13841             false, false, false, Alignment);
13842       }
13843     }
13844
13845   // Check to see if we can perform the "gzip trick", transforming
13846   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13847   if (isNullConstant(N3) && CC == ISD::SETLT &&
13848       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13849        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13850     EVT XType = N0.getValueType();
13851     EVT AType = N2.getValueType();
13852     if (XType.bitsGE(AType)) {
13853       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13854       // single-bit constant.
13855       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13856         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13857         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13858         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13859                                        getShiftAmountTy(N0.getValueType()));
13860         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13861                                     XType, N0, ShCt);
13862         AddToWorklist(Shift.getNode());
13863
13864         if (XType.bitsGT(AType)) {
13865           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13866           AddToWorklist(Shift.getNode());
13867         }
13868
13869         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13870       }
13871
13872       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13873                                   XType, N0,
13874                                   DAG.getConstant(XType.getSizeInBits() - 1,
13875                                                   SDLoc(N0),
13876                                          getShiftAmountTy(N0.getValueType())));
13877       AddToWorklist(Shift.getNode());
13878
13879       if (XType.bitsGT(AType)) {
13880         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13881         AddToWorklist(Shift.getNode());
13882       }
13883
13884       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13885     }
13886   }
13887
13888   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13889   // where y is has a single bit set.
13890   // A plaintext description would be, we can turn the SELECT_CC into an AND
13891   // when the condition can be materialized as an all-ones register.  Any
13892   // single bit-test can be materialized as an all-ones register with
13893   // shift-left and shift-right-arith.
13894   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13895       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13896     SDValue AndLHS = N0->getOperand(0);
13897     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13898     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13899       // Shift the tested bit over the sign bit.
13900       APInt AndMask = ConstAndRHS->getAPIntValue();
13901       SDValue ShlAmt =
13902         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13903                         getShiftAmountTy(AndLHS.getValueType()));
13904       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13905
13906       // Now arithmetic right shift it all the way over, so the result is either
13907       // all-ones, or zero.
13908       SDValue ShrAmt =
13909         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13910                         getShiftAmountTy(Shl.getValueType()));
13911       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13912
13913       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13914     }
13915   }
13916
13917   // fold select C, 16, 0 -> shl C, 4
13918   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13919       TLI.getBooleanContents(N0.getValueType()) ==
13920           TargetLowering::ZeroOrOneBooleanContent) {
13921
13922     // If the caller doesn't want us to simplify this into a zext of a compare,
13923     // don't do it.
13924     if (NotExtCompare && N2C->isOne())
13925       return SDValue();
13926
13927     // Get a SetCC of the condition
13928     // NOTE: Don't create a SETCC if it's not legal on this target.
13929     if (!LegalOperations ||
13930         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13931       SDValue Temp, SCC;
13932       // cast from setcc result type to select result type
13933       if (LegalTypes) {
13934         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13935                             N0, N1, CC);
13936         if (N2.getValueType().bitsLT(SCC.getValueType()))
13937           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13938                                         N2.getValueType());
13939         else
13940           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13941                              N2.getValueType(), SCC);
13942       } else {
13943         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13944         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13945                            N2.getValueType(), SCC);
13946       }
13947
13948       AddToWorklist(SCC.getNode());
13949       AddToWorklist(Temp.getNode());
13950
13951       if (N2C->isOne())
13952         return Temp;
13953
13954       // shl setcc result by log2 n2c
13955       return DAG.getNode(
13956           ISD::SHL, DL, N2.getValueType(), Temp,
13957           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13958                           getShiftAmountTy(Temp.getValueType())));
13959     }
13960   }
13961
13962   // Check to see if this is an integer abs.
13963   // select_cc setg[te] X,  0,  X, -X ->
13964   // select_cc setgt    X, -1,  X, -X ->
13965   // select_cc setl[te] X,  0, -X,  X ->
13966   // select_cc setlt    X,  1, -X,  X ->
13967   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13968   if (N1C) {
13969     ConstantSDNode *SubC = nullptr;
13970     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13971          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13972         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13973       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13974     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13975               (N1C->isOne() && CC == ISD::SETLT)) &&
13976              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13977       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13978
13979     EVT XType = N0.getValueType();
13980     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13981       SDLoc DL(N0);
13982       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13983                                   N0,
13984                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13985                                          getShiftAmountTy(N0.getValueType())));
13986       SDValue Add = DAG.getNode(ISD::ADD, DL,
13987                                 XType, N0, Shift);
13988       AddToWorklist(Shift.getNode());
13989       AddToWorklist(Add.getNode());
13990       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13991     }
13992   }
13993
13994   return SDValue();
13995 }
13996
13997 /// This is a stub for TargetLowering::SimplifySetCC.
13998 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13999                                    SDValue N1, ISD::CondCode Cond,
14000                                    SDLoc DL, bool foldBooleans) {
14001   TargetLowering::DAGCombinerInfo
14002     DagCombineInfo(DAG, Level, false, this);
14003   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14004 }
14005
14006 /// Given an ISD::SDIV node expressing a divide by constant, return
14007 /// a DAG expression to select that will generate the same value by multiplying
14008 /// by a magic number.
14009 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14010 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14011   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14012   if (!C)
14013     return SDValue();
14014
14015   // Avoid division by zero.
14016   if (C->isNullValue())
14017     return SDValue();
14018
14019   std::vector<SDNode*> Built;
14020   SDValue S =
14021       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14022
14023   for (SDNode *N : Built)
14024     AddToWorklist(N);
14025   return S;
14026 }
14027
14028 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14029 /// DAG expression that will generate the same value by right shifting.
14030 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14031   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14032   if (!C)
14033     return SDValue();
14034
14035   // Avoid division by zero.
14036   if (C->isNullValue())
14037     return SDValue();
14038
14039   std::vector<SDNode *> Built;
14040   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14041
14042   for (SDNode *N : Built)
14043     AddToWorklist(N);
14044   return S;
14045 }
14046
14047 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14048 /// expression that will generate the same value by multiplying by a magic
14049 /// number.
14050 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14051 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14052   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14053   if (!C)
14054     return SDValue();
14055
14056   // Avoid division by zero.
14057   if (C->isNullValue())
14058     return SDValue();
14059
14060   std::vector<SDNode*> Built;
14061   SDValue S =
14062       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14063
14064   for (SDNode *N : Built)
14065     AddToWorklist(N);
14066   return S;
14067 }
14068
14069 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14070   if (Level >= AfterLegalizeDAG)
14071     return SDValue();
14072
14073   // Expose the DAG combiner to the target combiner implementations.
14074   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14075
14076   unsigned Iterations = 0;
14077   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14078     if (Iterations) {
14079       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14080       // For the reciprocal, we need to find the zero of the function:
14081       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14082       //     =>
14083       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14084       //     does not require additional intermediate precision]
14085       EVT VT = Op.getValueType();
14086       SDLoc DL(Op);
14087       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14088
14089       AddToWorklist(Est.getNode());
14090
14091       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14092       for (unsigned i = 0; i < Iterations; ++i) {
14093         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14094         AddToWorklist(NewEst.getNode());
14095
14096         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14097         AddToWorklist(NewEst.getNode());
14098
14099         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14100         AddToWorklist(NewEst.getNode());
14101
14102         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14103         AddToWorklist(Est.getNode());
14104       }
14105     }
14106     return Est;
14107   }
14108
14109   return SDValue();
14110 }
14111
14112 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14113 /// For the reciprocal sqrt, we need to find the zero of the function:
14114 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14115 ///     =>
14116 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14117 /// As a result, we precompute A/2 prior to the iteration loop.
14118 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14119                                           unsigned Iterations,
14120                                           SDNodeFlags *Flags) {
14121   EVT VT = Arg.getValueType();
14122   SDLoc DL(Arg);
14123   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14124
14125   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14126   // this entire sequence requires only one FP constant.
14127   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14128   AddToWorklist(HalfArg.getNode());
14129
14130   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14131   AddToWorklist(HalfArg.getNode());
14132
14133   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14134   for (unsigned i = 0; i < Iterations; ++i) {
14135     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14136     AddToWorklist(NewEst.getNode());
14137
14138     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14139     AddToWorklist(NewEst.getNode());
14140
14141     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14142     AddToWorklist(NewEst.getNode());
14143
14144     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14145     AddToWorklist(Est.getNode());
14146   }
14147   return Est;
14148 }
14149
14150 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14151 /// For the reciprocal sqrt, we need to find the zero of the function:
14152 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14153 ///     =>
14154 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14155 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14156                                           unsigned Iterations,
14157                                           SDNodeFlags *Flags) {
14158   EVT VT = Arg.getValueType();
14159   SDLoc DL(Arg);
14160   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14161   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14162
14163   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14164   for (unsigned i = 0; i < Iterations; ++i) {
14165     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14166     AddToWorklist(HalfEst.getNode());
14167
14168     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14169     AddToWorklist(Est.getNode());
14170
14171     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14172     AddToWorklist(Est.getNode());
14173
14174     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14175     AddToWorklist(Est.getNode());
14176
14177     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14178     AddToWorklist(Est.getNode());
14179   }
14180   return Est;
14181 }
14182
14183 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14184   if (Level >= AfterLegalizeDAG)
14185     return SDValue();
14186
14187   // Expose the DAG combiner to the target combiner implementations.
14188   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14189   unsigned Iterations = 0;
14190   bool UseOneConstNR = false;
14191   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14192     AddToWorklist(Est.getNode());
14193     if (Iterations) {
14194       Est = UseOneConstNR ?
14195         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14196         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14197     }
14198     return Est;
14199   }
14200
14201   return SDValue();
14202 }
14203
14204 /// Return true if base is a frame index, which is known not to alias with
14205 /// anything but itself.  Provides base object and offset as results.
14206 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14207                            const GlobalValue *&GV, const void *&CV) {
14208   // Assume it is a primitive operation.
14209   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14210
14211   // If it's an adding a simple constant then integrate the offset.
14212   if (Base.getOpcode() == ISD::ADD) {
14213     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14214       Base = Base.getOperand(0);
14215       Offset += C->getZExtValue();
14216     }
14217   }
14218
14219   // Return the underlying GlobalValue, and update the Offset.  Return false
14220   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14221   // by multiple nodes with different offsets.
14222   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14223     GV = G->getGlobal();
14224     Offset += G->getOffset();
14225     return false;
14226   }
14227
14228   // Return the underlying Constant value, and update the Offset.  Return false
14229   // for ConstantSDNodes since the same constant pool entry may be represented
14230   // by multiple nodes with different offsets.
14231   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14232     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14233                                          : (const void *)C->getConstVal();
14234     Offset += C->getOffset();
14235     return false;
14236   }
14237   // If it's any of the following then it can't alias with anything but itself.
14238   return isa<FrameIndexSDNode>(Base);
14239 }
14240
14241 /// Return true if there is any possibility that the two addresses overlap.
14242 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14243   // If they are the same then they must be aliases.
14244   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14245
14246   // If they are both volatile then they cannot be reordered.
14247   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14248
14249   // If one operation reads from invariant memory, and the other may store, they
14250   // cannot alias. These should really be checking the equivalent of mayWrite,
14251   // but it only matters for memory nodes other than load /store.
14252   if (Op0->isInvariant() && Op1->writeMem())
14253     return false;
14254
14255   if (Op1->isInvariant() && Op0->writeMem())
14256     return false;
14257
14258   // Gather base node and offset information.
14259   SDValue Base1, Base2;
14260   int64_t Offset1, Offset2;
14261   const GlobalValue *GV1, *GV2;
14262   const void *CV1, *CV2;
14263   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14264                                       Base1, Offset1, GV1, CV1);
14265   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14266                                       Base2, Offset2, GV2, CV2);
14267
14268   // If they have a same base address then check to see if they overlap.
14269   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14270     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14271              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14272
14273   // It is possible for different frame indices to alias each other, mostly
14274   // when tail call optimization reuses return address slots for arguments.
14275   // To catch this case, look up the actual index of frame indices to compute
14276   // the real alias relationship.
14277   if (isFrameIndex1 && isFrameIndex2) {
14278     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14279     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14280     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14281     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14282              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14283   }
14284
14285   // Otherwise, if we know what the bases are, and they aren't identical, then
14286   // we know they cannot alias.
14287   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14288     return false;
14289
14290   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14291   // compared to the size and offset of the access, we may be able to prove they
14292   // do not alias.  This check is conservative for now to catch cases created by
14293   // splitting vector types.
14294   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14295       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14296       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14297        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14298       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14299     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14300     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14301
14302     // There is no overlap between these relatively aligned accesses of similar
14303     // size, return no alias.
14304     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14305         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14306       return false;
14307   }
14308
14309   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14310                    ? CombinerGlobalAA
14311                    : DAG.getSubtarget().useAA();
14312 #ifndef NDEBUG
14313   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14314       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14315     UseAA = false;
14316 #endif
14317   if (UseAA &&
14318       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14319     // Use alias analysis information.
14320     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14321                                  Op1->getSrcValueOffset());
14322     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14323         Op0->getSrcValueOffset() - MinOffset;
14324     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14325         Op1->getSrcValueOffset() - MinOffset;
14326     AliasResult AAResult =
14327         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14328                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14329                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14330                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14331     if (AAResult == NoAlias)
14332       return false;
14333   }
14334
14335   // Otherwise we have to assume they alias.
14336   return true;
14337 }
14338
14339 /// Walk up chain skipping non-aliasing memory nodes,
14340 /// looking for aliasing nodes and adding them to the Aliases vector.
14341 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14342                                    SmallVectorImpl<SDValue> &Aliases) {
14343   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14344   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14345
14346   // Get alias information for node.
14347   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14348
14349   // Starting off.
14350   Chains.push_back(OriginalChain);
14351   unsigned Depth = 0;
14352
14353   // Look at each chain and determine if it is an alias.  If so, add it to the
14354   // aliases list.  If not, then continue up the chain looking for the next
14355   // candidate.
14356   while (!Chains.empty()) {
14357     SDValue Chain = Chains.pop_back_val();
14358
14359     // For TokenFactor nodes, look at each operand and only continue up the
14360     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14361     // find more and revert to original chain since the xform is unlikely to be
14362     // profitable.
14363     //
14364     // FIXME: The depth check could be made to return the last non-aliasing
14365     // chain we found before we hit a tokenfactor rather than the original
14366     // chain.
14367     if (Depth > 6 || Aliases.size() == 2) {
14368       Aliases.clear();
14369       Aliases.push_back(OriginalChain);
14370       return;
14371     }
14372
14373     // Don't bother if we've been before.
14374     if (!Visited.insert(Chain.getNode()).second)
14375       continue;
14376
14377     switch (Chain.getOpcode()) {
14378     case ISD::EntryToken:
14379       // Entry token is ideal chain operand, but handled in FindBetterChain.
14380       break;
14381
14382     case ISD::LOAD:
14383     case ISD::STORE: {
14384       // Get alias information for Chain.
14385       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14386           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14387
14388       // If chain is alias then stop here.
14389       if (!(IsLoad && IsOpLoad) &&
14390           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14391         Aliases.push_back(Chain);
14392       } else {
14393         // Look further up the chain.
14394         Chains.push_back(Chain.getOperand(0));
14395         ++Depth;
14396       }
14397       break;
14398     }
14399
14400     case ISD::TokenFactor:
14401       // We have to check each of the operands of the token factor for "small"
14402       // token factors, so we queue them up.  Adding the operands to the queue
14403       // (stack) in reverse order maintains the original order and increases the
14404       // likelihood that getNode will find a matching token factor (CSE.)
14405       if (Chain.getNumOperands() > 16) {
14406         Aliases.push_back(Chain);
14407         break;
14408       }
14409       for (unsigned n = Chain.getNumOperands(); n;)
14410         Chains.push_back(Chain.getOperand(--n));
14411       ++Depth;
14412       break;
14413
14414     default:
14415       // For all other instructions we will just have to take what we can get.
14416       Aliases.push_back(Chain);
14417       break;
14418     }
14419   }
14420
14421   // We need to be careful here to also search for aliases through the
14422   // value operand of a store, etc. Consider the following situation:
14423   //   Token1 = ...
14424   //   L1 = load Token1, %52
14425   //   S1 = store Token1, L1, %51
14426   //   L2 = load Token1, %52+8
14427   //   S2 = store Token1, L2, %51+8
14428   //   Token2 = Token(S1, S2)
14429   //   L3 = load Token2, %53
14430   //   S3 = store Token2, L3, %52
14431   //   L4 = load Token2, %53+8
14432   //   S4 = store Token2, L4, %52+8
14433   // If we search for aliases of S3 (which loads address %52), and we look
14434   // only through the chain, then we'll miss the trivial dependence on L1
14435   // (which also loads from %52). We then might change all loads and
14436   // stores to use Token1 as their chain operand, which could result in
14437   // copying %53 into %52 before copying %52 into %51 (which should
14438   // happen first).
14439   //
14440   // The problem is, however, that searching for such data dependencies
14441   // can become expensive, and the cost is not directly related to the
14442   // chain depth. Instead, we'll rule out such configurations here by
14443   // insisting that we've visited all chain users (except for users
14444   // of the original chain, which is not necessary). When doing this,
14445   // we need to look through nodes we don't care about (otherwise, things
14446   // like register copies will interfere with trivial cases).
14447
14448   SmallVector<const SDNode *, 16> Worklist;
14449   for (const SDNode *N : Visited)
14450     if (N != OriginalChain.getNode())
14451       Worklist.push_back(N);
14452
14453   while (!Worklist.empty()) {
14454     const SDNode *M = Worklist.pop_back_val();
14455
14456     // We have already visited M, and want to make sure we've visited any uses
14457     // of M that we care about. For uses that we've not visisted, and don't
14458     // care about, queue them to the worklist.
14459
14460     for (SDNode::use_iterator UI = M->use_begin(),
14461          UIE = M->use_end(); UI != UIE; ++UI)
14462       if (UI.getUse().getValueType() == MVT::Other &&
14463           Visited.insert(*UI).second) {
14464         if (isa<MemSDNode>(*UI)) {
14465           // We've not visited this use, and we care about it (it could have an
14466           // ordering dependency with the original node).
14467           Aliases.clear();
14468           Aliases.push_back(OriginalChain);
14469           return;
14470         }
14471
14472         // We've not visited this use, but we don't care about it. Mark it as
14473         // visited and enqueue it to the worklist.
14474         Worklist.push_back(*UI);
14475       }
14476   }
14477 }
14478
14479 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14480 /// (aliasing node.)
14481 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14482   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14483
14484   // Accumulate all the aliases to this node.
14485   GatherAllAliases(N, OldChain, Aliases);
14486
14487   // If no operands then chain to entry token.
14488   if (Aliases.size() == 0)
14489     return DAG.getEntryNode();
14490
14491   // If a single operand then chain to it.  We don't need to revisit it.
14492   if (Aliases.size() == 1)
14493     return Aliases[0];
14494
14495   // Construct a custom tailored token factor.
14496   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14497 }
14498
14499 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14500   // This holds the base pointer, index, and the offset in bytes from the base
14501   // pointer.
14502   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14503
14504   // We must have a base and an offset.
14505   if (!BasePtr.Base.getNode())
14506     return false;
14507
14508   // Do not handle stores to undef base pointers.
14509   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14510     return false;
14511
14512   SmallVector<StoreSDNode *, 8> ChainedStores;
14513   ChainedStores.push_back(St);
14514
14515   // Walk up the chain and look for nodes with offsets from the same
14516   // base pointer. Stop when reaching an instruction with a different kind
14517   // or instruction which has a different base pointer.
14518   StoreSDNode *Index = St;
14519   while (Index) {
14520     // If the chain has more than one use, then we can't reorder the mem ops.
14521     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14522       break;
14523
14524     if (Index->isVolatile() || Index->isIndexed())
14525       break;
14526
14527     // Find the base pointer and offset for this memory node.
14528     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14529
14530     // Check that the base pointer is the same as the original one.
14531     if (!Ptr.equalBaseIndex(BasePtr))
14532       break;
14533
14534     // Find the next memory operand in the chain. If the next operand in the
14535     // chain is a store then move up and continue the scan with the next
14536     // memory operand. If the next operand is a load save it and use alias
14537     // information to check if it interferes with anything.
14538     SDNode *NextInChain = Index->getChain().getNode();
14539     while (true) {
14540       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14541         // We found a store node. Use it for the next iteration.
14542         ChainedStores.push_back(STn);
14543         Index = STn;
14544         break;
14545       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14546         NextInChain = Ldn->getChain().getNode();
14547         continue;
14548       } else {
14549         Index = nullptr;
14550         break;
14551       }
14552     }
14553   }
14554
14555   bool MadeChange = false;
14556   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14557
14558   for (StoreSDNode *ChainedStore : ChainedStores) {
14559     SDValue Chain = ChainedStore->getChain();
14560     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14561
14562     if (Chain != BetterChain) {
14563       MadeChange = true;
14564       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14565     }
14566   }
14567
14568   // Do all replacements after finding the replacements to make to avoid making
14569   // the chains more complicated by introducing new TokenFactors.
14570   for (auto Replacement : BetterChains)
14571     replaceStoreChain(Replacement.first, Replacement.second);
14572
14573   return MadeChange;
14574 }
14575
14576 /// This is the entry point for the file.
14577 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14578                            CodeGenOpt::Level OptLevel) {
14579   /// This is the main entry point to this class.
14580   DAGCombiner(*this, AA, OptLevel).Run(Level);
14581 }