]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge ^/head r317503 through r317807.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.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/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/KnownBits.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <algorithm>
44 using namespace llvm;
45
46 #define DEBUG_TYPE "dagcombine"
47
48 STATISTIC(NodesCombined   , "Number of dag nodes combined");
49 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
50 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
51 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
52 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
53 STATISTIC(SlicedLoads, "Number of load sliced");
54
55 namespace {
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79   static cl::opt<bool>
80     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
81                       cl::desc("DAG combiner may split indexing from loads"));
82
83 //------------------------------ DAGCombiner ---------------------------------//
84
85   class DAGCombiner {
86     SelectionDAG &DAG;
87     const TargetLowering &TLI;
88     CombineLevel Level;
89     CodeGenOpt::Level OptLevel;
90     bool LegalOperations;
91     bool LegalTypes;
92     bool ForCodeSize;
93
94     /// \brief Worklist of all of the nodes that need to be simplified.
95     ///
96     /// This must behave as a stack -- new nodes to process are pushed onto the
97     /// back and when processing we pop off of the back.
98     ///
99     /// The worklist will not contain duplicates but may contain null entries
100     /// due to nodes being deleted from the underlying DAG.
101     SmallVector<SDNode *, 64> Worklist;
102
103     /// \brief Mapping from an SDNode to its position on the worklist.
104     ///
105     /// This is used to find and remove nodes from the worklist (by nulling
106     /// them) when they are deleted from the underlying DAG. It relies on
107     /// stable indices of nodes within the worklist.
108     DenseMap<SDNode *, unsigned> WorklistMap;
109
110     /// \brief Set of nodes which have been combined (at least once).
111     ///
112     /// This is used to allow us to reliably add any operands of a DAG node
113     /// which have not yet been combined to the worklist.
114     SmallPtrSet<SDNode *, 32> CombinedNodes;
115
116     // AA - Used for DAG load/store alias analysis.
117     AliasAnalysis &AA;
118
119     /// When an instruction is simplified, add all users of the instruction to
120     /// the work lists because they might get more simplified now.
121     void AddUsersToWorklist(SDNode *N) {
122       for (SDNode *Node : N->uses())
123         AddToWorklist(Node);
124     }
125
126     /// Call the node-specific routine that folds each particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// Add to the worklist making sure its instance is at the back (next to be
131     /// processed.)
132     void AddToWorklist(SDNode *N) {
133       assert(N->getOpcode() != ISD::DELETED_NODE &&
134              "Deleted Node added to Worklist");
135
136       // Skip handle nodes as they can't usefully be combined and confuse the
137       // zero-use deletion strategy.
138       if (N->getOpcode() == ISD::HANDLENODE)
139         return;
140
141       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
142         Worklist.push_back(N);
143     }
144
145     /// Remove all instances of N from the worklist.
146     void removeFromWorklist(SDNode *N) {
147       CombinedNodes.erase(N);
148
149       auto It = WorklistMap.find(N);
150       if (It == WorklistMap.end())
151         return; // Not in the worklist.
152
153       // Null out the entry rather than erasing it to avoid a linear operation.
154       Worklist[It->second] = nullptr;
155       WorklistMap.erase(It);
156     }
157
158     void deleteAndRecombine(SDNode *N);
159     bool recursivelyDeleteUnusedNodes(SDNode *N);
160
161     /// Replaces all uses of the results of one DAG node with new values.
162     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163                       bool AddTo = true);
164
165     /// Replaces all uses of the results of one DAG node with new values.
166     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
167       return CombineTo(N, &Res, 1, AddTo);
168     }
169
170     /// Replaces all uses of the results of one DAG node with new values.
171     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
172                       bool AddTo = true) {
173       SDValue To[] = { Res0, Res1 };
174       return CombineTo(N, To, 2, AddTo);
175     }
176
177     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
178
179   private:
180     unsigned MaximumLegalStoreInBits;
181
182     /// Check the specified integer node value to see if it can be simplified or
183     /// if things it uses can be simplified by bit propagation.
184     /// If so, return true.
185     bool SimplifyDemandedBits(SDValue Op) {
186       unsigned BitWidth = Op.getScalarValueSizeInBits();
187       APInt Demanded = APInt::getAllOnesValue(BitWidth);
188       return SimplifyDemandedBits(Op, Demanded);
189     }
190
191     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
192
193     bool CombineToPreIndexedLoadStore(SDNode *N);
194     bool CombineToPostIndexedLoadStore(SDNode *N);
195     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
196     bool SliceUpLoad(SDNode *N);
197
198     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
199     ///   load.
200     ///
201     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
202     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
203     /// \param EltNo index of the vector element to load.
204     /// \param OriginalLoad load that EVE came from to be replaced.
205     /// \returns EVE on success SDValue() on failure.
206     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
207         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
208     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
209     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
210     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
211     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
212     SDValue PromoteIntBinOp(SDValue Op);
213     SDValue PromoteIntShiftOp(SDValue Op);
214     SDValue PromoteExtend(SDValue Op);
215     bool PromoteLoad(SDValue Op);
216
217     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
218                          SDValue ExtLoad, const SDLoc &DL,
219                          ISD::NodeType ExtType);
220
221     /// Call the node-specific routine that knows how to fold each
222     /// particular type of node. If that doesn't do anything, try the
223     /// target-specific DAG combines.
224     SDValue combine(SDNode *N);
225
226     // Visitation implementation - Implement dag node combining for different
227     // node types.  The semantics are as follows:
228     // Return Value:
229     //   SDValue.getNode() == 0 - No change was made
230     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
231     //   otherwise              - N should be replaced by the returned Operand.
232     //
233     SDValue visitTokenFactor(SDNode *N);
234     SDValue visitMERGE_VALUES(SDNode *N);
235     SDValue visitADD(SDNode *N);
236     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
237     SDValue visitSUB(SDNode *N);
238     SDValue visitADDC(SDNode *N);
239     SDValue visitUADDO(SDNode *N);
240     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
241     SDValue visitSUBC(SDNode *N);
242     SDValue visitUSUBO(SDNode *N);
243     SDValue visitADDE(SDNode *N);
244     SDValue visitADDCARRY(SDNode *N);
245     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
246     SDValue visitSUBE(SDNode *N);
247     SDValue visitSUBCARRY(SDNode *N);
248     SDValue visitMUL(SDNode *N);
249     SDValue useDivRem(SDNode *N);
250     SDValue visitSDIV(SDNode *N);
251     SDValue visitUDIV(SDNode *N);
252     SDValue visitREM(SDNode *N);
253     SDValue visitMULHU(SDNode *N);
254     SDValue visitMULHS(SDNode *N);
255     SDValue visitSMUL_LOHI(SDNode *N);
256     SDValue visitUMUL_LOHI(SDNode *N);
257     SDValue visitSMULO(SDNode *N);
258     SDValue visitUMULO(SDNode *N);
259     SDValue visitIMINMAX(SDNode *N);
260     SDValue visitAND(SDNode *N);
261     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
262     SDValue visitOR(SDNode *N);
263     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
264     SDValue visitXOR(SDNode *N);
265     SDValue SimplifyVBinOp(SDNode *N);
266     SDValue visitSHL(SDNode *N);
267     SDValue visitSRA(SDNode *N);
268     SDValue visitSRL(SDNode *N);
269     SDValue visitRotate(SDNode *N);
270     SDValue visitABS(SDNode *N);
271     SDValue visitBSWAP(SDNode *N);
272     SDValue visitBITREVERSE(SDNode *N);
273     SDValue visitCTLZ(SDNode *N);
274     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
275     SDValue visitCTTZ(SDNode *N);
276     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
277     SDValue visitCTPOP(SDNode *N);
278     SDValue visitSELECT(SDNode *N);
279     SDValue visitVSELECT(SDNode *N);
280     SDValue visitSELECT_CC(SDNode *N);
281     SDValue visitSETCC(SDNode *N);
282     SDValue visitSETCCE(SDNode *N);
283     SDValue visitSIGN_EXTEND(SDNode *N);
284     SDValue visitZERO_EXTEND(SDNode *N);
285     SDValue visitANY_EXTEND(SDNode *N);
286     SDValue visitAssertZext(SDNode *N);
287     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
288     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
289     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
290     SDValue visitTRUNCATE(SDNode *N);
291     SDValue visitBITCAST(SDNode *N);
292     SDValue visitBUILD_PAIR(SDNode *N);
293     SDValue visitFADD(SDNode *N);
294     SDValue visitFSUB(SDNode *N);
295     SDValue visitFMUL(SDNode *N);
296     SDValue visitFMA(SDNode *N);
297     SDValue visitFDIV(SDNode *N);
298     SDValue visitFREM(SDNode *N);
299     SDValue visitFSQRT(SDNode *N);
300     SDValue visitFCOPYSIGN(SDNode *N);
301     SDValue visitSINT_TO_FP(SDNode *N);
302     SDValue visitUINT_TO_FP(SDNode *N);
303     SDValue visitFP_TO_SINT(SDNode *N);
304     SDValue visitFP_TO_UINT(SDNode *N);
305     SDValue visitFP_ROUND(SDNode *N);
306     SDValue visitFP_ROUND_INREG(SDNode *N);
307     SDValue visitFP_EXTEND(SDNode *N);
308     SDValue visitFNEG(SDNode *N);
309     SDValue visitFABS(SDNode *N);
310     SDValue visitFCEIL(SDNode *N);
311     SDValue visitFTRUNC(SDNode *N);
312     SDValue visitFFLOOR(SDNode *N);
313     SDValue visitFMINNUM(SDNode *N);
314     SDValue visitFMAXNUM(SDNode *N);
315     SDValue visitBRCOND(SDNode *N);
316     SDValue visitBR_CC(SDNode *N);
317     SDValue visitLOAD(SDNode *N);
318
319     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
320     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
321
322     SDValue visitSTORE(SDNode *N);
323     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
324     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
325     SDValue visitBUILD_VECTOR(SDNode *N);
326     SDValue visitCONCAT_VECTORS(SDNode *N);
327     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
328     SDValue visitVECTOR_SHUFFLE(SDNode *N);
329     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
330     SDValue visitINSERT_SUBVECTOR(SDNode *N);
331     SDValue visitMLOAD(SDNode *N);
332     SDValue visitMSTORE(SDNode *N);
333     SDValue visitMGATHER(SDNode *N);
334     SDValue visitMSCATTER(SDNode *N);
335     SDValue visitFP_TO_FP16(SDNode *N);
336     SDValue visitFP16_TO_FP(SDNode *N);
337
338     SDValue visitFADDForFMACombine(SDNode *N);
339     SDValue visitFSUBForFMACombine(SDNode *N);
340     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
341
342     SDValue XformToShuffleWithZero(SDNode *N);
343     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
344                            SDValue RHS);
345
346     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
347
348     SDValue foldSelectOfConstants(SDNode *N);
349     SDValue foldBinOpIntoSelect(SDNode *BO);
350     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
351     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
352     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
353     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
354                              SDValue N2, SDValue N3, ISD::CondCode CC,
355                              bool NotExtCompare = false);
356     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
357                                    SDValue N2, SDValue N3, ISD::CondCode CC);
358     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
359                               const SDLoc &DL);
360     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
361                           const SDLoc &DL, bool foldBooleans = true);
362
363     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
364                            SDValue &CC) const;
365     bool isOneUseSetCC(SDValue N) const;
366
367     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
368                                          unsigned HiOp);
369     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
370     SDValue CombineExtLoad(SDNode *N);
371     SDValue combineRepeatedFPDivisors(SDNode *N);
372     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
373     SDValue BuildSDIV(SDNode *N);
374     SDValue BuildSDIVPow2(SDNode *N);
375     SDValue BuildUDIV(SDNode *N);
376     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
377     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
378     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
379     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
380     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
381     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
382                                 SDNodeFlags Flags, bool Reciprocal);
383     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
384                                 SDNodeFlags Flags, bool Reciprocal);
385     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
386                                bool DemandHighBits = true);
387     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
388     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
389                               SDValue InnerPos, SDValue InnerNeg,
390                               unsigned PosOpcode, unsigned NegOpcode,
391                               const SDLoc &DL);
392     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
393     SDValue MatchLoadCombine(SDNode *N);
394     SDValue ReduceLoadWidth(SDNode *N);
395     SDValue ReduceLoadOpStoreWidth(SDNode *N);
396     SDValue splitMergedValStore(StoreSDNode *ST);
397     SDValue TransformFPLoadStorePair(SDNode *N);
398     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
399     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
400     SDValue reduceBuildVecToShuffle(SDNode *N);
401     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
402                                   ArrayRef<int> VectorMask, SDValue VecIn1,
403                                   SDValue VecIn2, unsigned LeftIdx);
404     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
405
406     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
407
408     /// Walk up chain skipping non-aliasing memory nodes,
409     /// looking for aliasing nodes and adding them to the Aliases vector.
410     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
411                           SmallVectorImpl<SDValue> &Aliases);
412
413     /// Return true if there is any possibility that the two addresses overlap.
414     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
415
416     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
417     /// chain (aliasing node.)
418     SDValue FindBetterChain(SDNode *N, SDValue Chain);
419
420     /// Try to replace a store and any possibly adjacent stores on
421     /// consecutive chains with better chains. Return true only if St is
422     /// replaced.
423     ///
424     /// Notice that other chains may still be replaced even if the function
425     /// returns false.
426     bool findBetterNeighborChains(StoreSDNode *St);
427
428     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
429     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
430
431     /// Holds a pointer to an LSBaseSDNode as well as information on where it
432     /// is located in a sequence of memory operations connected by a chain.
433     struct MemOpLink {
434       MemOpLink(LSBaseSDNode *N, int64_t Offset)
435           : MemNode(N), OffsetFromBase(Offset) {}
436       // Ptr to the mem node.
437       LSBaseSDNode *MemNode;
438       // Offset from the base ptr.
439       int64_t OffsetFromBase;
440     };
441
442     /// This is a helper function for visitMUL to check the profitability
443     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
444     /// MulNode is the original multiply, AddNode is (add x, c1),
445     /// and ConstNode is c2.
446     bool isMulAddWithConstProfitable(SDNode *MulNode,
447                                      SDValue &AddNode,
448                                      SDValue &ConstNode);
449
450
451     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
452     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
453     /// the type of the loaded value to be extended.  LoadedVT returns the type
454     /// of the original loaded value.  NarrowLoad returns whether the load would
455     /// need to be narrowed in order to match.
456     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
457                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
458                           bool &NarrowLoad);
459
460     /// Helper function for MergeConsecutiveStores which merges the
461     /// component store chains.
462     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
463                                 unsigned NumStores);
464
465     /// This is a helper function for MergeConsecutiveStores. When the source
466     /// elements of the consecutive stores are all constants or all extracted
467     /// vector elements, try to merge them into one larger store.
468     /// \return True if a merged store was created.
469     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
470                                          EVT MemVT, unsigned NumStores,
471                                          bool IsConstantSrc, bool UseVector);
472
473     /// This is a helper function for MergeConsecutiveStores.
474     /// Stores that may be merged are placed in StoreNodes.
475     void getStoreMergeCandidates(StoreSDNode *St,
476                                  SmallVectorImpl<MemOpLink> &StoreNodes);
477
478     /// Helper function for MergeConsecutiveStores. Checks if
479     /// Candidate stores have indirect dependency through their
480     /// operands. \return True if safe to merge
481     bool checkMergeStoreCandidatesForDependencies(
482         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
483
484     /// Merge consecutive store operations into a wide store.
485     /// This optimization uses wide integers or vectors when possible.
486     /// \return number of stores that were merged into a merged store (the
487     /// affected nodes are stored as a prefix in \p StoreNodes).
488     bool MergeConsecutiveStores(StoreSDNode *N);
489
490     /// \brief Try to transform a truncation where C is a constant:
491     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
492     ///
493     /// \p N needs to be a truncation and its first operand an AND. Other
494     /// requirements are checked by the function (e.g. that trunc is
495     /// single-use) and if missed an empty SDValue is returned.
496     SDValue distributeTruncateThroughAnd(SDNode *N);
497
498   public:
499     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
500         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
501           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
502       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
503
504       MaximumLegalStoreInBits = 0;
505       for (MVT VT : MVT::all_valuetypes())
506         if (EVT(VT).isSimple() && VT != MVT::Other &&
507             TLI.isTypeLegal(EVT(VT)) &&
508             VT.getSizeInBits() >= MaximumLegalStoreInBits)
509           MaximumLegalStoreInBits = VT.getSizeInBits();
510     }
511
512     /// Runs the dag combiner on all nodes in the work list
513     void Run(CombineLevel AtLevel);
514
515     SelectionDAG &getDAG() const { return DAG; }
516
517     /// Returns a type large enough to hold any valid shift amount - before type
518     /// legalization these can be huge.
519     EVT getShiftAmountTy(EVT LHSTy) {
520       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
521       if (LHSTy.isVector())
522         return LHSTy;
523       auto &DL = DAG.getDataLayout();
524       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
525                         : TLI.getPointerTy(DL);
526     }
527
528     /// This method returns true if we are running before type legalization or
529     /// if the specified VT is legal.
530     bool isTypeLegal(const EVT &VT) {
531       if (!LegalTypes) return true;
532       return TLI.isTypeLegal(VT);
533     }
534
535     /// Convenience wrapper around TargetLowering::getSetCCResultType
536     EVT getSetCCResultType(EVT VT) const {
537       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
538     }
539   };
540 }
541
542
543 namespace {
544 /// This class is a DAGUpdateListener that removes any deleted
545 /// nodes from the worklist.
546 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
547   DAGCombiner &DC;
548 public:
549   explicit WorklistRemover(DAGCombiner &dc)
550     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
551
552   void NodeDeleted(SDNode *N, SDNode *E) override {
553     DC.removeFromWorklist(N);
554   }
555 };
556 }
557
558 //===----------------------------------------------------------------------===//
559 //  TargetLowering::DAGCombinerInfo implementation
560 //===----------------------------------------------------------------------===//
561
562 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
563   ((DAGCombiner*)DC)->AddToWorklist(N);
564 }
565
566 SDValue TargetLowering::DAGCombinerInfo::
567 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
568   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
569 }
570
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
573   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
574 }
575
576
577 SDValue TargetLowering::DAGCombinerInfo::
578 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
579   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
580 }
581
582 void TargetLowering::DAGCombinerInfo::
583 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
584   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
585 }
586
587 //===----------------------------------------------------------------------===//
588 // Helper Functions
589 //===----------------------------------------------------------------------===//
590
591 void DAGCombiner::deleteAndRecombine(SDNode *N) {
592   removeFromWorklist(N);
593
594   // If the operands of this node are only used by the node, they will now be
595   // dead. Make sure to re-visit them and recursively delete dead nodes.
596   for (const SDValue &Op : N->ops())
597     // For an operand generating multiple values, one of the values may
598     // become dead allowing further simplification (e.g. split index
599     // arithmetic from an indexed load).
600     if (Op->hasOneUse() || Op->getNumValues() > 1)
601       AddToWorklist(Op.getNode());
602
603   DAG.DeleteNode(N);
604 }
605
606 /// Return 1 if we can compute the negated form of the specified expression for
607 /// the same cost as the expression itself, or 2 if we can compute the negated
608 /// form more cheaply than the expression itself.
609 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
610                                const TargetLowering &TLI,
611                                const TargetOptions *Options,
612                                unsigned Depth = 0) {
613   // fneg is removable even if it has multiple uses.
614   if (Op.getOpcode() == ISD::FNEG) return 2;
615
616   // Don't allow anything with multiple uses.
617   if (!Op.hasOneUse()) return 0;
618
619   // Don't recurse exponentially.
620   if (Depth > 6) return 0;
621
622   switch (Op.getOpcode()) {
623   default: return false;
624   case ISD::ConstantFP: {
625     if (!LegalOperations)
626       return 1;
627
628     // Don't invert constant FP values after legalization unless the target says
629     // the negated constant is legal.
630     EVT VT = Op.getValueType();
631     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
632       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
633   }
634   case ISD::FADD:
635     // FIXME: determine better conditions for this xform.
636     if (!Options->UnsafeFPMath) return 0;
637
638     // After operation legalization, it might not be legal to create new FSUBs.
639     if (LegalOperations &&
640         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
641       return 0;
642
643     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
644     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
645                                     Options, Depth + 1))
646       return V;
647     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
648     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
649                               Depth + 1);
650   case ISD::FSUB:
651     // We can't turn -(A-B) into B-A when we honor signed zeros.
652     if (!Options->NoSignedZerosFPMath &&
653         !Op.getNode()->getFlags().hasNoSignedZeros())
654       return 0;
655
656     // fold (fneg (fsub A, B)) -> (fsub B, A)
657     return 1;
658
659   case ISD::FMUL:
660   case ISD::FDIV:
661     if (Options->HonorSignDependentRoundingFPMath()) return 0;
662
663     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
664     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
665                                     Options, Depth + 1))
666       return V;
667
668     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
669                               Depth + 1);
670
671   case ISD::FP_EXTEND:
672   case ISD::FP_ROUND:
673   case ISD::FSIN:
674     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
675                               Depth + 1);
676   }
677 }
678
679 /// If isNegatibleForFree returns true, return the newly negated expression.
680 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
681                                     bool LegalOperations, unsigned Depth = 0) {
682   const TargetOptions &Options = DAG.getTarget().Options;
683   // fneg is removable even if it has multiple uses.
684   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
685
686   // Don't allow anything with multiple uses.
687   assert(Op.hasOneUse() && "Unknown reuse!");
688
689   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
690
691   const SDNodeFlags Flags = Op.getNode()->getFlags();
692
693   switch (Op.getOpcode()) {
694   default: llvm_unreachable("Unknown code");
695   case ISD::ConstantFP: {
696     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
697     V.changeSign();
698     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
699   }
700   case ISD::FADD:
701     // FIXME: determine better conditions for this xform.
702     assert(Options.UnsafeFPMath);
703
704     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
705     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
706                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
707       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
708                          GetNegatedExpression(Op.getOperand(0), DAG,
709                                               LegalOperations, Depth+1),
710                          Op.getOperand(1), Flags);
711     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
712     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
713                        GetNegatedExpression(Op.getOperand(1), DAG,
714                                             LegalOperations, Depth+1),
715                        Op.getOperand(0), Flags);
716   case ISD::FSUB:
717     // fold (fneg (fsub 0, B)) -> B
718     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
719       if (N0CFP->isZero())
720         return Op.getOperand(1);
721
722     // fold (fneg (fsub A, B)) -> (fsub B, A)
723     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
724                        Op.getOperand(1), Op.getOperand(0), Flags);
725
726   case ISD::FMUL:
727   case ISD::FDIV:
728     assert(!Options.HonorSignDependentRoundingFPMath());
729
730     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
731     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
732                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
733       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
734                          GetNegatedExpression(Op.getOperand(0), DAG,
735                                               LegalOperations, Depth+1),
736                          Op.getOperand(1), Flags);
737
738     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
739     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
740                        Op.getOperand(0),
741                        GetNegatedExpression(Op.getOperand(1), DAG,
742                                             LegalOperations, Depth+1), Flags);
743
744   case ISD::FP_EXTEND:
745   case ISD::FSIN:
746     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
747                        GetNegatedExpression(Op.getOperand(0), DAG,
748                                             LegalOperations, Depth+1));
749   case ISD::FP_ROUND:
750       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
751                          GetNegatedExpression(Op.getOperand(0), DAG,
752                                               LegalOperations, Depth+1),
753                          Op.getOperand(1));
754   }
755 }
756
757 // APInts must be the same size for most operations, this helper
758 // function zero extends the shorter of the pair so that they match.
759 // We provide an Offset so that we can create bitwidths that won't overflow.
760 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
761   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
762   LHS = LHS.zextOrSelf(Bits);
763   RHS = RHS.zextOrSelf(Bits);
764 }
765
766 // Return true if this node is a setcc, or is a select_cc
767 // that selects between the target values used for true and false, making it
768 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
769 // the appropriate nodes based on the type of node we are checking. This
770 // simplifies life a bit for the callers.
771 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
772                                     SDValue &CC) const {
773   if (N.getOpcode() == ISD::SETCC) {
774     LHS = N.getOperand(0);
775     RHS = N.getOperand(1);
776     CC  = N.getOperand(2);
777     return true;
778   }
779
780   if (N.getOpcode() != ISD::SELECT_CC ||
781       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
782       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
783     return false;
784
785   if (TLI.getBooleanContents(N.getValueType()) ==
786       TargetLowering::UndefinedBooleanContent)
787     return false;
788
789   LHS = N.getOperand(0);
790   RHS = N.getOperand(1);
791   CC  = N.getOperand(4);
792   return true;
793 }
794
795 /// Return true if this is a SetCC-equivalent operation with only one use.
796 /// If this is true, it allows the users to invert the operation for free when
797 /// it is profitable to do so.
798 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
799   SDValue N0, N1, N2;
800   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
801     return true;
802   return false;
803 }
804
805 // \brief Returns the SDNode if it is a constant float BuildVector
806 // or constant float.
807 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
808   if (isa<ConstantFPSDNode>(N))
809     return N.getNode();
810   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
811     return N.getNode();
812   return nullptr;
813 }
814
815 // Determines if it is a constant integer or a build vector of constant
816 // integers (and undefs).
817 // Do not permit build vector implicit truncation.
818 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
819   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
820     return !(Const->isOpaque() && NoOpaques);
821   if (N.getOpcode() != ISD::BUILD_VECTOR)
822     return false;
823   unsigned BitWidth = N.getScalarValueSizeInBits();
824   for (const SDValue &Op : N->op_values()) {
825     if (Op.isUndef())
826       continue;
827     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
828     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
829         (Const->isOpaque() && NoOpaques))
830       return false;
831   }
832   return true;
833 }
834
835 // Determines if it is a constant null integer or a splatted vector of a
836 // constant null integer (with no undefs).
837 // Build vector implicit truncation is not an issue for null values.
838 static bool isNullConstantOrNullSplatConstant(SDValue N) {
839   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
840     return Splat->isNullValue();
841   return false;
842 }
843
844 // Determines if it is a constant integer of one or a splatted vector of a
845 // constant integer of one (with no undefs).
846 // Do not permit build vector implicit truncation.
847 static bool isOneConstantOrOneSplatConstant(SDValue N) {
848   unsigned BitWidth = N.getScalarValueSizeInBits();
849   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
850     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
851   return false;
852 }
853
854 // Determines if it is a constant integer of all ones or a splatted vector of a
855 // constant integer of all ones (with no undefs).
856 // Do not permit build vector implicit truncation.
857 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
858   unsigned BitWidth = N.getScalarValueSizeInBits();
859   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
860     return Splat->isAllOnesValue() &&
861            Splat->getAPIntValue().getBitWidth() == BitWidth;
862   return false;
863 }
864
865 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
866 // undef's.
867 static bool isAnyConstantBuildVector(const SDNode *N) {
868   return ISD::isBuildVectorOfConstantSDNodes(N) ||
869          ISD::isBuildVectorOfConstantFPSDNodes(N);
870 }
871
872 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
873                                     SDValue N1) {
874   EVT VT = N0.getValueType();
875   if (N0.getOpcode() == Opc) {
876     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
877       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
878         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
879         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
880           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
881         return SDValue();
882       }
883       if (N0.hasOneUse()) {
884         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
885         // use
886         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
887         if (!OpNode.getNode())
888           return SDValue();
889         AddToWorklist(OpNode.getNode());
890         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
891       }
892     }
893   }
894
895   if (N1.getOpcode() == Opc) {
896     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
897       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
898         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
899         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
900           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
901         return SDValue();
902       }
903       if (N1.hasOneUse()) {
904         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
905         // use
906         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
907         if (!OpNode.getNode())
908           return SDValue();
909         AddToWorklist(OpNode.getNode());
910         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
911       }
912     }
913   }
914
915   return SDValue();
916 }
917
918 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
919                                bool AddTo) {
920   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
921   ++NodesCombined;
922   DEBUG(dbgs() << "\nReplacing.1 ";
923         N->dump(&DAG);
924         dbgs() << "\nWith: ";
925         To[0].getNode()->dump(&DAG);
926         dbgs() << " and " << NumTo-1 << " other values\n");
927   for (unsigned i = 0, e = NumTo; i != e; ++i)
928     assert((!To[i].getNode() ||
929             N->getValueType(i) == To[i].getValueType()) &&
930            "Cannot combine value to value of different type!");
931
932   WorklistRemover DeadNodes(*this);
933   DAG.ReplaceAllUsesWith(N, To);
934   if (AddTo) {
935     // Push the new nodes and any users onto the worklist
936     for (unsigned i = 0, e = NumTo; i != e; ++i) {
937       if (To[i].getNode()) {
938         AddToWorklist(To[i].getNode());
939         AddUsersToWorklist(To[i].getNode());
940       }
941     }
942   }
943
944   // Finally, if the node is now dead, remove it from the graph.  The node
945   // may not be dead if the replacement process recursively simplified to
946   // something else needing this node.
947   if (N->use_empty())
948     deleteAndRecombine(N);
949   return SDValue(N, 0);
950 }
951
952 void DAGCombiner::
953 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
954   // Replace all uses.  If any nodes become isomorphic to other nodes and
955   // are deleted, make sure to remove them from our worklist.
956   WorklistRemover DeadNodes(*this);
957   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
958
959   // Push the new node and any (possibly new) users onto the worklist.
960   AddToWorklist(TLO.New.getNode());
961   AddUsersToWorklist(TLO.New.getNode());
962
963   // Finally, if the node is now dead, remove it from the graph.  The node
964   // may not be dead if the replacement process recursively simplified to
965   // something else needing this node.
966   if (TLO.Old.getNode()->use_empty())
967     deleteAndRecombine(TLO.Old.getNode());
968 }
969
970 /// Check the specified integer node value to see if it can be simplified or if
971 /// things it uses can be simplified by bit propagation. If so, return true.
972 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
973   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
974   KnownBits Known;
975   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
976     return false;
977
978   // Revisit the node.
979   AddToWorklist(Op.getNode());
980
981   // Replace the old value with the new one.
982   ++NodesCombined;
983   DEBUG(dbgs() << "\nReplacing.2 ";
984         TLO.Old.getNode()->dump(&DAG);
985         dbgs() << "\nWith: ";
986         TLO.New.getNode()->dump(&DAG);
987         dbgs() << '\n');
988
989   CommitTargetLoweringOpt(TLO);
990   return true;
991 }
992
993 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
994   SDLoc DL(Load);
995   EVT VT = Load->getValueType(0);
996   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
997
998   DEBUG(dbgs() << "\nReplacing.9 ";
999         Load->dump(&DAG);
1000         dbgs() << "\nWith: ";
1001         Trunc.getNode()->dump(&DAG);
1002         dbgs() << '\n');
1003   WorklistRemover DeadNodes(*this);
1004   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1005   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1006   deleteAndRecombine(Load);
1007   AddToWorklist(Trunc.getNode());
1008 }
1009
1010 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1011   Replace = false;
1012   SDLoc DL(Op);
1013   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1014     LoadSDNode *LD = cast<LoadSDNode>(Op);
1015     EVT MemVT = LD->getMemoryVT();
1016     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1017       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1018                                                        : ISD::EXTLOAD)
1019       : LD->getExtensionType();
1020     Replace = true;
1021     return DAG.getExtLoad(ExtType, DL, PVT,
1022                           LD->getChain(), LD->getBasePtr(),
1023                           MemVT, LD->getMemOperand());
1024   }
1025
1026   unsigned Opc = Op.getOpcode();
1027   switch (Opc) {
1028   default: break;
1029   case ISD::AssertSext:
1030     return DAG.getNode(ISD::AssertSext, DL, PVT,
1031                        SExtPromoteOperand(Op.getOperand(0), PVT),
1032                        Op.getOperand(1));
1033   case ISD::AssertZext:
1034     return DAG.getNode(ISD::AssertZext, DL, PVT,
1035                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1036                        Op.getOperand(1));
1037   case ISD::Constant: {
1038     unsigned ExtOpc =
1039       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1040     return DAG.getNode(ExtOpc, DL, PVT, Op);
1041   }
1042   }
1043
1044   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1045     return SDValue();
1046   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1047 }
1048
1049 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1050   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1051     return SDValue();
1052   EVT OldVT = Op.getValueType();
1053   SDLoc DL(Op);
1054   bool Replace = false;
1055   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1056   if (!NewOp.getNode())
1057     return SDValue();
1058   AddToWorklist(NewOp.getNode());
1059
1060   if (Replace)
1061     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1062   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1063                      DAG.getValueType(OldVT));
1064 }
1065
1066 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1067   EVT OldVT = Op.getValueType();
1068   SDLoc DL(Op);
1069   bool Replace = false;
1070   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1071   if (!NewOp.getNode())
1072     return SDValue();
1073   AddToWorklist(NewOp.getNode());
1074
1075   if (Replace)
1076     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1077   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1078 }
1079
1080 /// Promote the specified integer binary operation if the target indicates it is
1081 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1082 /// i32 since i16 instructions are longer.
1083 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1084   if (!LegalOperations)
1085     return SDValue();
1086
1087   EVT VT = Op.getValueType();
1088   if (VT.isVector() || !VT.isInteger())
1089     return SDValue();
1090
1091   // If operation type is 'undesirable', e.g. i16 on x86, consider
1092   // promoting it.
1093   unsigned Opc = Op.getOpcode();
1094   if (TLI.isTypeDesirableForOp(Opc, VT))
1095     return SDValue();
1096
1097   EVT PVT = VT;
1098   // Consult target whether it is a good idea to promote this operation and
1099   // what's the right type to promote it to.
1100   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1101     assert(PVT != VT && "Don't know what type to promote to!");
1102
1103     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1104
1105     bool Replace0 = false;
1106     SDValue N0 = Op.getOperand(0);
1107     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1108
1109     bool Replace1 = false;
1110     SDValue N1 = Op.getOperand(1);
1111     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1112     SDLoc DL(Op);
1113
1114     SDValue RV =
1115         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1116
1117     // New replace instances of N0 and N1
1118     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1119         NN0.getOpcode() != ISD::DELETED_NODE) {
1120       AddToWorklist(NN0.getNode());
1121       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1122     }
1123
1124     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1125         NN1.getOpcode() != ISD::DELETED_NODE) {
1126       AddToWorklist(NN1.getNode());
1127       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1128     }
1129
1130     // Deal with Op being deleted.
1131     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1132       return RV;
1133   }
1134   return SDValue();
1135 }
1136
1137 /// Promote the specified integer shift operation if the target indicates it is
1138 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1139 /// i32 since i16 instructions are longer.
1140 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1141   if (!LegalOperations)
1142     return SDValue();
1143
1144   EVT VT = Op.getValueType();
1145   if (VT.isVector() || !VT.isInteger())
1146     return SDValue();
1147
1148   // If operation type is 'undesirable', e.g. i16 on x86, consider
1149   // promoting it.
1150   unsigned Opc = Op.getOpcode();
1151   if (TLI.isTypeDesirableForOp(Opc, VT))
1152     return SDValue();
1153
1154   EVT PVT = VT;
1155   // Consult target whether it is a good idea to promote this operation and
1156   // what's the right type to promote it to.
1157   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1158     assert(PVT != VT && "Don't know what type to promote to!");
1159
1160     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1161
1162     bool Replace = false;
1163     SDValue N0 = Op.getOperand(0);
1164     SDValue N1 = Op.getOperand(1);
1165     if (Opc == ISD::SRA)
1166       N0 = SExtPromoteOperand(N0, PVT);
1167     else if (Opc == ISD::SRL)
1168       N0 = ZExtPromoteOperand(N0, PVT);
1169     else
1170       N0 = PromoteOperand(N0, PVT, Replace);
1171
1172     if (!N0.getNode())
1173       return SDValue();
1174
1175     SDLoc DL(Op);
1176     SDValue RV =
1177         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1178
1179     AddToWorklist(N0.getNode());
1180     if (Replace)
1181       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1182
1183     // Deal with Op being deleted.
1184     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1185       return RV;
1186   }
1187   return SDValue();
1188 }
1189
1190 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1191   if (!LegalOperations)
1192     return SDValue();
1193
1194   EVT VT = Op.getValueType();
1195   if (VT.isVector() || !VT.isInteger())
1196     return SDValue();
1197
1198   // If operation type is 'undesirable', e.g. i16 on x86, consider
1199   // promoting it.
1200   unsigned Opc = Op.getOpcode();
1201   if (TLI.isTypeDesirableForOp(Opc, VT))
1202     return SDValue();
1203
1204   EVT PVT = VT;
1205   // Consult target whether it is a good idea to promote this operation and
1206   // what's the right type to promote it to.
1207   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1208     assert(PVT != VT && "Don't know what type to promote to!");
1209     // fold (aext (aext x)) -> (aext x)
1210     // fold (aext (zext x)) -> (zext x)
1211     // fold (aext (sext x)) -> (sext x)
1212     DEBUG(dbgs() << "\nPromoting ";
1213           Op.getNode()->dump(&DAG));
1214     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1215   }
1216   return SDValue();
1217 }
1218
1219 bool DAGCombiner::PromoteLoad(SDValue Op) {
1220   if (!LegalOperations)
1221     return false;
1222
1223   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1224     return false;
1225
1226   EVT VT = Op.getValueType();
1227   if (VT.isVector() || !VT.isInteger())
1228     return false;
1229
1230   // If operation type is 'undesirable', e.g. i16 on x86, consider
1231   // promoting it.
1232   unsigned Opc = Op.getOpcode();
1233   if (TLI.isTypeDesirableForOp(Opc, VT))
1234     return false;
1235
1236   EVT PVT = VT;
1237   // Consult target whether it is a good idea to promote this operation and
1238   // what's the right type to promote it to.
1239   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1240     assert(PVT != VT && "Don't know what type to promote to!");
1241
1242     SDLoc DL(Op);
1243     SDNode *N = Op.getNode();
1244     LoadSDNode *LD = cast<LoadSDNode>(N);
1245     EVT MemVT = LD->getMemoryVT();
1246     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1247       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1248                                                        : ISD::EXTLOAD)
1249       : LD->getExtensionType();
1250     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1251                                    LD->getChain(), LD->getBasePtr(),
1252                                    MemVT, LD->getMemOperand());
1253     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1254
1255     DEBUG(dbgs() << "\nPromoting ";
1256           N->dump(&DAG);
1257           dbgs() << "\nTo: ";
1258           Result.getNode()->dump(&DAG);
1259           dbgs() << '\n');
1260     WorklistRemover DeadNodes(*this);
1261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1262     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1263     deleteAndRecombine(N);
1264     AddToWorklist(Result.getNode());
1265     return true;
1266   }
1267   return false;
1268 }
1269
1270 /// \brief Recursively delete a node which has no uses and any operands for
1271 /// which it is the only use.
1272 ///
1273 /// Note that this both deletes the nodes and removes them from the worklist.
1274 /// It also adds any nodes who have had a user deleted to the worklist as they
1275 /// may now have only one use and subject to other combines.
1276 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1277   if (!N->use_empty())
1278     return false;
1279
1280   SmallSetVector<SDNode *, 16> Nodes;
1281   Nodes.insert(N);
1282   do {
1283     N = Nodes.pop_back_val();
1284     if (!N)
1285       continue;
1286
1287     if (N->use_empty()) {
1288       for (const SDValue &ChildN : N->op_values())
1289         Nodes.insert(ChildN.getNode());
1290
1291       removeFromWorklist(N);
1292       DAG.DeleteNode(N);
1293     } else {
1294       AddToWorklist(N);
1295     }
1296   } while (!Nodes.empty());
1297   return true;
1298 }
1299
1300 //===----------------------------------------------------------------------===//
1301 //  Main DAG Combiner implementation
1302 //===----------------------------------------------------------------------===//
1303
1304 void DAGCombiner::Run(CombineLevel AtLevel) {
1305   // set the instance variables, so that the various visit routines may use it.
1306   Level = AtLevel;
1307   LegalOperations = Level >= AfterLegalizeVectorOps;
1308   LegalTypes = Level >= AfterLegalizeTypes;
1309
1310   // Add all the dag nodes to the worklist.
1311   for (SDNode &Node : DAG.allnodes())
1312     AddToWorklist(&Node);
1313
1314   // Create a dummy node (which is not added to allnodes), that adds a reference
1315   // to the root node, preventing it from being deleted, and tracking any
1316   // changes of the root.
1317   HandleSDNode Dummy(DAG.getRoot());
1318
1319   // While the worklist isn't empty, find a node and try to combine it.
1320   while (!WorklistMap.empty()) {
1321     SDNode *N;
1322     // The Worklist holds the SDNodes in order, but it may contain null entries.
1323     do {
1324       N = Worklist.pop_back_val();
1325     } while (!N);
1326
1327     bool GoodWorklistEntry = WorklistMap.erase(N);
1328     (void)GoodWorklistEntry;
1329     assert(GoodWorklistEntry &&
1330            "Found a worklist entry without a corresponding map entry!");
1331
1332     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1333     // N is deleted from the DAG, since they too may now be dead or may have a
1334     // reduced number of uses, allowing other xforms.
1335     if (recursivelyDeleteUnusedNodes(N))
1336       continue;
1337
1338     WorklistRemover DeadNodes(*this);
1339
1340     // If this combine is running after legalizing the DAG, re-legalize any
1341     // nodes pulled off the worklist.
1342     if (Level == AfterLegalizeDAG) {
1343       SmallSetVector<SDNode *, 16> UpdatedNodes;
1344       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1345
1346       for (SDNode *LN : UpdatedNodes) {
1347         AddToWorklist(LN);
1348         AddUsersToWorklist(LN);
1349       }
1350       if (!NIsValid)
1351         continue;
1352     }
1353
1354     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1355
1356     // Add any operands of the new node which have not yet been combined to the
1357     // worklist as well. Because the worklist uniques things already, this
1358     // won't repeatedly process the same operand.
1359     CombinedNodes.insert(N);
1360     for (const SDValue &ChildN : N->op_values())
1361       if (!CombinedNodes.count(ChildN.getNode()))
1362         AddToWorklist(ChildN.getNode());
1363
1364     SDValue RV = combine(N);
1365
1366     if (!RV.getNode())
1367       continue;
1368
1369     ++NodesCombined;
1370
1371     // If we get back the same node we passed in, rather than a new node or
1372     // zero, we know that the node must have defined multiple values and
1373     // CombineTo was used.  Since CombineTo takes care of the worklist
1374     // mechanics for us, we have no work to do in this case.
1375     if (RV.getNode() == N)
1376       continue;
1377
1378     assert(N->getOpcode() != ISD::DELETED_NODE &&
1379            RV.getOpcode() != ISD::DELETED_NODE &&
1380            "Node was deleted but visit returned new node!");
1381
1382     DEBUG(dbgs() << " ... into: ";
1383           RV.getNode()->dump(&DAG));
1384
1385     if (N->getNumValues() == RV.getNode()->getNumValues())
1386       DAG.ReplaceAllUsesWith(N, RV.getNode());
1387     else {
1388       assert(N->getValueType(0) == RV.getValueType() &&
1389              N->getNumValues() == 1 && "Type mismatch");
1390       DAG.ReplaceAllUsesWith(N, &RV);
1391     }
1392
1393     // Push the new node and any users onto the worklist
1394     AddToWorklist(RV.getNode());
1395     AddUsersToWorklist(RV.getNode());
1396
1397     // Finally, if the node is now dead, remove it from the graph.  The node
1398     // may not be dead if the replacement process recursively simplified to
1399     // something else needing this node. This will also take care of adding any
1400     // operands which have lost a user to the worklist.
1401     recursivelyDeleteUnusedNodes(N);
1402   }
1403
1404   // If the root changed (e.g. it was a dead load, update the root).
1405   DAG.setRoot(Dummy.getValue());
1406   DAG.RemoveDeadNodes();
1407 }
1408
1409 SDValue DAGCombiner::visit(SDNode *N) {
1410   switch (N->getOpcode()) {
1411   default: break;
1412   case ISD::TokenFactor:        return visitTokenFactor(N);
1413   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1414   case ISD::ADD:                return visitADD(N);
1415   case ISD::SUB:                return visitSUB(N);
1416   case ISD::ADDC:               return visitADDC(N);
1417   case ISD::UADDO:              return visitUADDO(N);
1418   case ISD::SUBC:               return visitSUBC(N);
1419   case ISD::USUBO:              return visitUSUBO(N);
1420   case ISD::ADDE:               return visitADDE(N);
1421   case ISD::ADDCARRY:           return visitADDCARRY(N);
1422   case ISD::SUBE:               return visitSUBE(N);
1423   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1424   case ISD::MUL:                return visitMUL(N);
1425   case ISD::SDIV:               return visitSDIV(N);
1426   case ISD::UDIV:               return visitUDIV(N);
1427   case ISD::SREM:
1428   case ISD::UREM:               return visitREM(N);
1429   case ISD::MULHU:              return visitMULHU(N);
1430   case ISD::MULHS:              return visitMULHS(N);
1431   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1432   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1433   case ISD::SMULO:              return visitSMULO(N);
1434   case ISD::UMULO:              return visitUMULO(N);
1435   case ISD::SMIN:
1436   case ISD::SMAX:
1437   case ISD::UMIN:
1438   case ISD::UMAX:               return visitIMINMAX(N);
1439   case ISD::AND:                return visitAND(N);
1440   case ISD::OR:                 return visitOR(N);
1441   case ISD::XOR:                return visitXOR(N);
1442   case ISD::SHL:                return visitSHL(N);
1443   case ISD::SRA:                return visitSRA(N);
1444   case ISD::SRL:                return visitSRL(N);
1445   case ISD::ROTR:
1446   case ISD::ROTL:               return visitRotate(N);
1447   case ISD::ABS:                return visitABS(N);
1448   case ISD::BSWAP:              return visitBSWAP(N);
1449   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1450   case ISD::CTLZ:               return visitCTLZ(N);
1451   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1452   case ISD::CTTZ:               return visitCTTZ(N);
1453   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1454   case ISD::CTPOP:              return visitCTPOP(N);
1455   case ISD::SELECT:             return visitSELECT(N);
1456   case ISD::VSELECT:            return visitVSELECT(N);
1457   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1458   case ISD::SETCC:              return visitSETCC(N);
1459   case ISD::SETCCE:             return visitSETCCE(N);
1460   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1461   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1462   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1463   case ISD::AssertZext:         return visitAssertZext(N);
1464   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1465   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1466   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1467   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1468   case ISD::BITCAST:            return visitBITCAST(N);
1469   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1470   case ISD::FADD:               return visitFADD(N);
1471   case ISD::FSUB:               return visitFSUB(N);
1472   case ISD::FMUL:               return visitFMUL(N);
1473   case ISD::FMA:                return visitFMA(N);
1474   case ISD::FDIV:               return visitFDIV(N);
1475   case ISD::FREM:               return visitFREM(N);
1476   case ISD::FSQRT:              return visitFSQRT(N);
1477   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1478   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1479   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1480   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1481   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1482   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1483   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1484   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1485   case ISD::FNEG:               return visitFNEG(N);
1486   case ISD::FABS:               return visitFABS(N);
1487   case ISD::FFLOOR:             return visitFFLOOR(N);
1488   case ISD::FMINNUM:            return visitFMINNUM(N);
1489   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1490   case ISD::FCEIL:              return visitFCEIL(N);
1491   case ISD::FTRUNC:             return visitFTRUNC(N);
1492   case ISD::BRCOND:             return visitBRCOND(N);
1493   case ISD::BR_CC:              return visitBR_CC(N);
1494   case ISD::LOAD:               return visitLOAD(N);
1495   case ISD::STORE:              return visitSTORE(N);
1496   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1497   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1498   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1499   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1500   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1501   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1502   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1503   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1504   case ISD::MGATHER:            return visitMGATHER(N);
1505   case ISD::MLOAD:              return visitMLOAD(N);
1506   case ISD::MSCATTER:           return visitMSCATTER(N);
1507   case ISD::MSTORE:             return visitMSTORE(N);
1508   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1509   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1510   }
1511   return SDValue();
1512 }
1513
1514 SDValue DAGCombiner::combine(SDNode *N) {
1515   SDValue RV = visit(N);
1516
1517   // If nothing happened, try a target-specific DAG combine.
1518   if (!RV.getNode()) {
1519     assert(N->getOpcode() != ISD::DELETED_NODE &&
1520            "Node was deleted but visit returned NULL!");
1521
1522     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1523         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1524
1525       // Expose the DAG combiner to the target combiner impls.
1526       TargetLowering::DAGCombinerInfo
1527         DagCombineInfo(DAG, Level, false, this);
1528
1529       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1530     }
1531   }
1532
1533   // If nothing happened still, try promoting the operation.
1534   if (!RV.getNode()) {
1535     switch (N->getOpcode()) {
1536     default: break;
1537     case ISD::ADD:
1538     case ISD::SUB:
1539     case ISD::MUL:
1540     case ISD::AND:
1541     case ISD::OR:
1542     case ISD::XOR:
1543       RV = PromoteIntBinOp(SDValue(N, 0));
1544       break;
1545     case ISD::SHL:
1546     case ISD::SRA:
1547     case ISD::SRL:
1548       RV = PromoteIntShiftOp(SDValue(N, 0));
1549       break;
1550     case ISD::SIGN_EXTEND:
1551     case ISD::ZERO_EXTEND:
1552     case ISD::ANY_EXTEND:
1553       RV = PromoteExtend(SDValue(N, 0));
1554       break;
1555     case ISD::LOAD:
1556       if (PromoteLoad(SDValue(N, 0)))
1557         RV = SDValue(N, 0);
1558       break;
1559     }
1560   }
1561
1562   // If N is a commutative binary node, try commuting it to enable more
1563   // sdisel CSE.
1564   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1565       N->getNumValues() == 1) {
1566     SDValue N0 = N->getOperand(0);
1567     SDValue N1 = N->getOperand(1);
1568
1569     // Constant operands are canonicalized to RHS.
1570     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1571       SDValue Ops[] = {N1, N0};
1572       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1573                                             N->getFlags());
1574       if (CSENode)
1575         return SDValue(CSENode, 0);
1576     }
1577   }
1578
1579   return RV;
1580 }
1581
1582 /// Given a node, return its input chain if it has one, otherwise return a null
1583 /// sd operand.
1584 static SDValue getInputChainForNode(SDNode *N) {
1585   if (unsigned NumOps = N->getNumOperands()) {
1586     if (N->getOperand(0).getValueType() == MVT::Other)
1587       return N->getOperand(0);
1588     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1589       return N->getOperand(NumOps-1);
1590     for (unsigned i = 1; i < NumOps-1; ++i)
1591       if (N->getOperand(i).getValueType() == MVT::Other)
1592         return N->getOperand(i);
1593   }
1594   return SDValue();
1595 }
1596
1597 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1598   // If N has two operands, where one has an input chain equal to the other,
1599   // the 'other' chain is redundant.
1600   if (N->getNumOperands() == 2) {
1601     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1602       return N->getOperand(0);
1603     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1604       return N->getOperand(1);
1605   }
1606
1607   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1608   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1609   SmallPtrSet<SDNode*, 16> SeenOps;
1610   bool Changed = false;             // If we should replace this token factor.
1611
1612   // Start out with this token factor.
1613   TFs.push_back(N);
1614
1615   // Iterate through token factors.  The TFs grows when new token factors are
1616   // encountered.
1617   for (unsigned i = 0; i < TFs.size(); ++i) {
1618     SDNode *TF = TFs[i];
1619
1620     // Check each of the operands.
1621     for (const SDValue &Op : TF->op_values()) {
1622
1623       switch (Op.getOpcode()) {
1624       case ISD::EntryToken:
1625         // Entry tokens don't need to be added to the list. They are
1626         // redundant.
1627         Changed = true;
1628         break;
1629
1630       case ISD::TokenFactor:
1631         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1632           // Queue up for processing.
1633           TFs.push_back(Op.getNode());
1634           // Clean up in case the token factor is removed.
1635           AddToWorklist(Op.getNode());
1636           Changed = true;
1637           break;
1638         }
1639         LLVM_FALLTHROUGH;
1640
1641       default:
1642         // Only add if it isn't already in the list.
1643         if (SeenOps.insert(Op.getNode()).second)
1644           Ops.push_back(Op);
1645         else
1646           Changed = true;
1647         break;
1648       }
1649     }
1650   }
1651
1652   // Remove Nodes that are chained to another node in the list. Do so
1653   // by walking up chains breath-first stopping when we've seen
1654   // another operand. In general we must climb to the EntryNode, but we can exit
1655   // early if we find all remaining work is associated with just one operand as
1656   // no further pruning is possible.
1657
1658   // List of nodes to search through and original Ops from which they originate.
1659   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1660   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1661   SmallPtrSet<SDNode *, 16> SeenChains;
1662   bool DidPruneOps = false;
1663
1664   unsigned NumLeftToConsider = 0;
1665   for (const SDValue &Op : Ops) {
1666     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1667     OpWorkCount.push_back(1);
1668   }
1669
1670   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1671     // If this is an Op, we can remove the op from the list. Remark any
1672     // search associated with it as from the current OpNumber.
1673     if (SeenOps.count(Op) != 0) {
1674       Changed = true;
1675       DidPruneOps = true;
1676       unsigned OrigOpNumber = 0;
1677       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1678         OrigOpNumber++;
1679       assert((OrigOpNumber != Ops.size()) &&
1680              "expected to find TokenFactor Operand");
1681       // Re-mark worklist from OrigOpNumber to OpNumber
1682       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1683         if (Worklist[i].second == OrigOpNumber) {
1684           Worklist[i].second = OpNumber;
1685         }
1686       }
1687       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1688       OpWorkCount[OrigOpNumber] = 0;
1689       NumLeftToConsider--;
1690     }
1691     // Add if it's a new chain
1692     if (SeenChains.insert(Op).second) {
1693       OpWorkCount[OpNumber]++;
1694       Worklist.push_back(std::make_pair(Op, OpNumber));
1695     }
1696   };
1697
1698   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1699     // We need at least be consider at least 2 Ops to prune.
1700     if (NumLeftToConsider <= 1)
1701       break;
1702     auto CurNode = Worklist[i].first;
1703     auto CurOpNumber = Worklist[i].second;
1704     assert((OpWorkCount[CurOpNumber] > 0) &&
1705            "Node should not appear in worklist");
1706     switch (CurNode->getOpcode()) {
1707     case ISD::EntryToken:
1708       // Hitting EntryToken is the only way for the search to terminate without
1709       // hitting
1710       // another operand's search. Prevent us from marking this operand
1711       // considered.
1712       NumLeftToConsider++;
1713       break;
1714     case ISD::TokenFactor:
1715       for (const SDValue &Op : CurNode->op_values())
1716         AddToWorklist(i, Op.getNode(), CurOpNumber);
1717       break;
1718     case ISD::CopyFromReg:
1719     case ISD::CopyToReg:
1720       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1721       break;
1722     default:
1723       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1724         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1725       break;
1726     }
1727     OpWorkCount[CurOpNumber]--;
1728     if (OpWorkCount[CurOpNumber] == 0)
1729       NumLeftToConsider--;
1730   }
1731
1732   SDValue Result;
1733
1734   // If we've changed things around then replace token factor.
1735   if (Changed) {
1736     if (Ops.empty()) {
1737       // The entry token is the only possible outcome.
1738       Result = DAG.getEntryNode();
1739     } else {
1740       if (DidPruneOps) {
1741         SmallVector<SDValue, 8> PrunedOps;
1742         //
1743         for (const SDValue &Op : Ops) {
1744           if (SeenChains.count(Op.getNode()) == 0)
1745             PrunedOps.push_back(Op);
1746         }
1747         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1748       } else {
1749         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1750       }
1751     }
1752
1753     // Add users to worklist, since we may introduce a lot of new
1754     // chained token factors while removing memory deps.
1755     return CombineTo(N, Result, true /*add to worklist*/);
1756   }
1757
1758   return Result;
1759 }
1760
1761 /// MERGE_VALUES can always be eliminated.
1762 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1763   WorklistRemover DeadNodes(*this);
1764   // Replacing results may cause a different MERGE_VALUES to suddenly
1765   // be CSE'd with N, and carry its uses with it. Iterate until no
1766   // uses remain, to ensure that the node can be safely deleted.
1767   // First add the users of this node to the work list so that they
1768   // can be tried again once they have new operands.
1769   AddUsersToWorklist(N);
1770   do {
1771     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1772       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1773   } while (!N->use_empty());
1774   deleteAndRecombine(N);
1775   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1776 }
1777
1778 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1779 /// ConstantSDNode pointer else nullptr.
1780 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1781   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1782   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1783 }
1784
1785 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1786   auto BinOpcode = BO->getOpcode();
1787   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1788           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1789           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1790           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1791           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1792           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1793           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1794           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1795           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1796          "Unexpected binary operator");
1797
1798   // Bail out if any constants are opaque because we can't constant fold those.
1799   SDValue C1 = BO->getOperand(1);
1800   if (!isConstantOrConstantVector(C1, true) &&
1801       !isConstantFPBuildVectorOrConstantFP(C1))
1802     return SDValue();
1803
1804   // Don't do this unless the old select is going away. We want to eliminate the
1805   // binary operator, not replace a binop with a select.
1806   // TODO: Handle ISD::SELECT_CC.
1807   SDValue Sel = BO->getOperand(0);
1808   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1809     return SDValue();
1810
1811   SDValue CT = Sel.getOperand(1);
1812   if (!isConstantOrConstantVector(CT, true) &&
1813       !isConstantFPBuildVectorOrConstantFP(CT))
1814     return SDValue();
1815
1816   SDValue CF = Sel.getOperand(2);
1817   if (!isConstantOrConstantVector(CF, true) &&
1818       !isConstantFPBuildVectorOrConstantFP(CF))
1819     return SDValue();
1820
1821   // We have a select-of-constants followed by a binary operator with a
1822   // constant. Eliminate the binop by pulling the constant math into the select.
1823   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1824   EVT VT = Sel.getValueType();
1825   SDLoc DL(Sel);
1826   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1827   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1828           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1829          "Failed to constant fold a binop with constant operands");
1830
1831   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1832   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1833           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1834          "Failed to constant fold a binop with constant operands");
1835
1836   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1837 }
1838
1839 SDValue DAGCombiner::visitADD(SDNode *N) {
1840   SDValue N0 = N->getOperand(0);
1841   SDValue N1 = N->getOperand(1);
1842   EVT VT = N0.getValueType();
1843   SDLoc DL(N);
1844
1845   // fold vector ops
1846   if (VT.isVector()) {
1847     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1848       return FoldedVOp;
1849
1850     // fold (add x, 0) -> x, vector edition
1851     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1852       return N0;
1853     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1854       return N1;
1855   }
1856
1857   // fold (add x, undef) -> undef
1858   if (N0.isUndef())
1859     return N0;
1860
1861   if (N1.isUndef())
1862     return N1;
1863
1864   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1865     // canonicalize constant to RHS
1866     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1867       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1868     // fold (add c1, c2) -> c1+c2
1869     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1870                                       N1.getNode());
1871   }
1872
1873   // fold (add x, 0) -> x
1874   if (isNullConstant(N1))
1875     return N0;
1876
1877   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1878     // fold ((c1-A)+c2) -> (c1+c2)-A
1879     if (N0.getOpcode() == ISD::SUB &&
1880         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1881       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1882       return DAG.getNode(ISD::SUB, DL, VT,
1883                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1884                          N0.getOperand(1));
1885     }
1886
1887     // add (sext i1 X), 1 -> zext (not i1 X)
1888     // We don't transform this pattern:
1889     //   add (zext i1 X), -1 -> sext (not i1 X)
1890     // because most (?) targets generate better code for the zext form.
1891     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1892         isOneConstantOrOneSplatConstant(N1)) {
1893       SDValue X = N0.getOperand(0);
1894       if ((!LegalOperations ||
1895            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1896             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1897           X.getScalarValueSizeInBits() == 1) {
1898         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1899         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1900       }
1901     }
1902   }
1903
1904   if (SDValue NewSel = foldBinOpIntoSelect(N))
1905     return NewSel;
1906
1907   // reassociate add
1908   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1909     return RADD;
1910
1911   // fold ((0-A) + B) -> B-A
1912   if (N0.getOpcode() == ISD::SUB &&
1913       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1914     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1915
1916   // fold (A + (0-B)) -> A-B
1917   if (N1.getOpcode() == ISD::SUB &&
1918       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1919     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1920
1921   // fold (A+(B-A)) -> B
1922   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1923     return N1.getOperand(0);
1924
1925   // fold ((B-A)+A) -> B
1926   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1927     return N0.getOperand(0);
1928
1929   // fold (A+(B-(A+C))) to (B-C)
1930   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1931       N0 == N1.getOperand(1).getOperand(0))
1932     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1933                        N1.getOperand(1).getOperand(1));
1934
1935   // fold (A+(B-(C+A))) to (B-C)
1936   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1937       N0 == N1.getOperand(1).getOperand(1))
1938     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1939                        N1.getOperand(1).getOperand(0));
1940
1941   // fold (A+((B-A)+or-C)) to (B+or-C)
1942   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1943       N1.getOperand(0).getOpcode() == ISD::SUB &&
1944       N0 == N1.getOperand(0).getOperand(1))
1945     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1946                        N1.getOperand(1));
1947
1948   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1949   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1950     SDValue N00 = N0.getOperand(0);
1951     SDValue N01 = N0.getOperand(1);
1952     SDValue N10 = N1.getOperand(0);
1953     SDValue N11 = N1.getOperand(1);
1954
1955     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1956       return DAG.getNode(ISD::SUB, DL, VT,
1957                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1958                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1959   }
1960
1961   if (SimplifyDemandedBits(SDValue(N, 0)))
1962     return SDValue(N, 0);
1963
1964   // fold (a+b) -> (a|b) iff a and b share no bits.
1965   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1966       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1967     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1968
1969   if (SDValue Combined = visitADDLike(N0, N1, N))
1970     return Combined;
1971
1972   if (SDValue Combined = visitADDLike(N1, N0, N))
1973     return Combined;
1974
1975   return SDValue();
1976 }
1977
1978 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1979   EVT VT = N0.getValueType();
1980   SDLoc DL(LocReference);
1981
1982   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1983   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1984       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1985     return DAG.getNode(ISD::SUB, DL, VT, N0,
1986                        DAG.getNode(ISD::SHL, DL, VT,
1987                                    N1.getOperand(0).getOperand(1),
1988                                    N1.getOperand(1)));
1989
1990   if (N1.getOpcode() == ISD::AND) {
1991     SDValue AndOp0 = N1.getOperand(0);
1992     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1993     unsigned DestBits = VT.getScalarSizeInBits();
1994
1995     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1996     // and similar xforms where the inner op is either ~0 or 0.
1997     if (NumSignBits == DestBits &&
1998         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1999       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2000   }
2001
2002   // add (sext i1), X -> sub X, (zext i1)
2003   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2004       N0.getOperand(0).getValueType() == MVT::i1 &&
2005       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2006     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2007     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2008   }
2009
2010   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2011   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2012     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2013     if (TN->getVT() == MVT::i1) {
2014       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2015                                  DAG.getConstant(1, DL, VT));
2016       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2017     }
2018   }
2019
2020   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2021   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2022     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2023                        N0, N1.getOperand(0), N1.getOperand(2));
2024
2025   return SDValue();
2026 }
2027
2028 SDValue DAGCombiner::visitADDC(SDNode *N) {
2029   SDValue N0 = N->getOperand(0);
2030   SDValue N1 = N->getOperand(1);
2031   EVT VT = N0.getValueType();
2032   SDLoc DL(N);
2033
2034   // If the flag result is dead, turn this into an ADD.
2035   if (!N->hasAnyUseOfValue(1))
2036     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2037                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2038
2039   // canonicalize constant to RHS.
2040   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2041   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2042   if (N0C && !N1C)
2043     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2044
2045   // fold (addc x, 0) -> x + no carry out
2046   if (isNullConstant(N1))
2047     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2048                                         DL, MVT::Glue));
2049
2050   // If it cannot overflow, transform into an add.
2051   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2052     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2053                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2054
2055   return SDValue();
2056 }
2057
2058 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2059   SDValue N0 = N->getOperand(0);
2060   SDValue N1 = N->getOperand(1);
2061   EVT VT = N0.getValueType();
2062   if (VT.isVector())
2063     return SDValue();
2064
2065   EVT CarryVT = N->getValueType(1);
2066   SDLoc DL(N);
2067
2068   // If the flag result is dead, turn this into an ADD.
2069   if (!N->hasAnyUseOfValue(1))
2070     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2071                      DAG.getUNDEF(CarryVT));
2072
2073   // canonicalize constant to RHS.
2074   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2075   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2076   if (N0C && !N1C)
2077     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2078
2079   // fold (uaddo x, 0) -> x + no carry out
2080   if (isNullConstant(N1))
2081     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2082
2083   // If it cannot overflow, transform into an add.
2084   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2085     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2086                      DAG.getConstant(0, DL, CarryVT));
2087
2088   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2089     return Combined;
2090
2091   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2092     return Combined;
2093
2094   return SDValue();
2095 }
2096
2097 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2098   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2099   // If Y + 1 cannot overflow.
2100   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2101     SDValue Y = N1.getOperand(0);
2102     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2103     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2104       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2105                          N1.getOperand(2));
2106   }
2107
2108   return SDValue();
2109 }
2110
2111 SDValue DAGCombiner::visitADDE(SDNode *N) {
2112   SDValue N0 = N->getOperand(0);
2113   SDValue N1 = N->getOperand(1);
2114   SDValue CarryIn = N->getOperand(2);
2115
2116   // canonicalize constant to RHS
2117   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2118   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2119   if (N0C && !N1C)
2120     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2121                        N1, N0, CarryIn);
2122
2123   // fold (adde x, y, false) -> (addc x, y)
2124   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2125     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2126
2127   return SDValue();
2128 }
2129
2130 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2131   SDValue N0 = N->getOperand(0);
2132   SDValue N1 = N->getOperand(1);
2133   SDValue CarryIn = N->getOperand(2);
2134
2135   // canonicalize constant to RHS
2136   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2137   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2138   if (N0C && !N1C)
2139     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2140                        N1, N0, CarryIn);
2141
2142   // fold (addcarry x, y, false) -> (uaddo x, y)
2143   if (isNullConstant(CarryIn))
2144     return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), N0, N1);
2145
2146   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2147     return Combined;
2148
2149   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2150     return Combined;
2151
2152   return SDValue();
2153 }
2154
2155 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2156                                        SDNode *N) {
2157   // Iff the flag result is dead:
2158   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2159   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) &&
2160       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2161     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2162                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2163
2164   return SDValue();
2165 }
2166
2167 // Since it may not be valid to emit a fold to zero for vector initializers
2168 // check if we can before folding.
2169 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2170                              SelectionDAG &DAG, bool LegalOperations,
2171                              bool LegalTypes) {
2172   if (!VT.isVector())
2173     return DAG.getConstant(0, DL, VT);
2174   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2175     return DAG.getConstant(0, DL, VT);
2176   return SDValue();
2177 }
2178
2179 SDValue DAGCombiner::visitSUB(SDNode *N) {
2180   SDValue N0 = N->getOperand(0);
2181   SDValue N1 = N->getOperand(1);
2182   EVT VT = N0.getValueType();
2183   SDLoc DL(N);
2184
2185   // fold vector ops
2186   if (VT.isVector()) {
2187     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2188       return FoldedVOp;
2189
2190     // fold (sub x, 0) -> x, vector edition
2191     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2192       return N0;
2193   }
2194
2195   // fold (sub x, x) -> 0
2196   // FIXME: Refactor this and xor and other similar operations together.
2197   if (N0 == N1)
2198     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2199   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2200       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2201     // fold (sub c1, c2) -> c1-c2
2202     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2203                                       N1.getNode());
2204   }
2205
2206   if (SDValue NewSel = foldBinOpIntoSelect(N))
2207     return NewSel;
2208
2209   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2210
2211   // fold (sub x, c) -> (add x, -c)
2212   if (N1C) {
2213     return DAG.getNode(ISD::ADD, DL, VT, N0,
2214                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2215   }
2216
2217   if (isNullConstantOrNullSplatConstant(N0)) {
2218     unsigned BitWidth = VT.getScalarSizeInBits();
2219     // Right-shifting everything out but the sign bit followed by negation is
2220     // the same as flipping arithmetic/logical shift type without the negation:
2221     // -(X >>u 31) -> (X >>s 31)
2222     // -(X >>s 31) -> (X >>u 31)
2223     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2224       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2225       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2226         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2227         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2228           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2229       }
2230     }
2231
2232     // 0 - X --> 0 if the sub is NUW.
2233     if (N->getFlags().hasNoUnsignedWrap())
2234       return N0;
2235
2236     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2237       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2238       // N1 must be 0 because negating the minimum signed value is undefined.
2239       if (N->getFlags().hasNoSignedWrap())
2240         return N0;
2241
2242       // 0 - X --> X if X is 0 or the minimum signed value.
2243       return N1;
2244     }
2245   }
2246
2247   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2248   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2249     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2250
2251   // fold A-(A-B) -> B
2252   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2253     return N1.getOperand(1);
2254
2255   // fold (A+B)-A -> B
2256   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2257     return N0.getOperand(1);
2258
2259   // fold (A+B)-B -> A
2260   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2261     return N0.getOperand(0);
2262
2263   // fold C2-(A+C1) -> (C2-C1)-A
2264   if (N1.getOpcode() == ISD::ADD) {
2265     SDValue N11 = N1.getOperand(1);
2266     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2267         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2268       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2269       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2270     }
2271   }
2272
2273   // fold ((A+(B+or-C))-B) -> A+or-C
2274   if (N0.getOpcode() == ISD::ADD &&
2275       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2276        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2277       N0.getOperand(1).getOperand(0) == N1)
2278     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2279                        N0.getOperand(1).getOperand(1));
2280
2281   // fold ((A+(C+B))-B) -> A+C
2282   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2283       N0.getOperand(1).getOperand(1) == N1)
2284     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2285                        N0.getOperand(1).getOperand(0));
2286
2287   // fold ((A-(B-C))-C) -> A-B
2288   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2289       N0.getOperand(1).getOperand(1) == N1)
2290     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2291                        N0.getOperand(1).getOperand(0));
2292
2293   // If either operand of a sub is undef, the result is undef
2294   if (N0.isUndef())
2295     return N0;
2296   if (N1.isUndef())
2297     return N1;
2298
2299   // If the relocation model supports it, consider symbol offsets.
2300   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2301     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2302       // fold (sub Sym, c) -> Sym-c
2303       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2304         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2305                                     GA->getOffset() -
2306                                         (uint64_t)N1C->getSExtValue());
2307       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2308       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2309         if (GA->getGlobal() == GB->getGlobal())
2310           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2311                                  DL, VT);
2312     }
2313
2314   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2315   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2316     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2317     if (TN->getVT() == MVT::i1) {
2318       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2319                                  DAG.getConstant(1, DL, VT));
2320       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2321     }
2322   }
2323
2324   return SDValue();
2325 }
2326
2327 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2328   SDValue N0 = N->getOperand(0);
2329   SDValue N1 = N->getOperand(1);
2330   EVT VT = N0.getValueType();
2331   SDLoc DL(N);
2332
2333   // If the flag result is dead, turn this into an SUB.
2334   if (!N->hasAnyUseOfValue(1))
2335     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2336                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2337
2338   // fold (subc x, x) -> 0 + no borrow
2339   if (N0 == N1)
2340     return CombineTo(N, DAG.getConstant(0, DL, VT),
2341                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2342
2343   // fold (subc x, 0) -> x + no borrow
2344   if (isNullConstant(N1))
2345     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2346
2347   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2348   if (isAllOnesConstant(N0))
2349     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2350                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2351
2352   return SDValue();
2353 }
2354
2355 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2356   SDValue N0 = N->getOperand(0);
2357   SDValue N1 = N->getOperand(1);
2358   EVT VT = N0.getValueType();
2359   if (VT.isVector())
2360     return SDValue();
2361
2362   EVT CarryVT = N->getValueType(1);
2363   SDLoc DL(N);
2364
2365   // If the flag result is dead, turn this into an SUB.
2366   if (!N->hasAnyUseOfValue(1))
2367     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2368                      DAG.getUNDEF(CarryVT));
2369
2370   // fold (usubo x, x) -> 0 + no borrow
2371   if (N0 == N1)
2372     return CombineTo(N, DAG.getConstant(0, DL, VT),
2373                      DAG.getConstant(0, DL, CarryVT));
2374
2375   // fold (usubo x, 0) -> x + no borrow
2376   if (isNullConstant(N1))
2377     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2378
2379   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2380   if (isAllOnesConstant(N0))
2381     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2382                      DAG.getConstant(0, DL, CarryVT));
2383
2384   return SDValue();
2385 }
2386
2387 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2388   SDValue N0 = N->getOperand(0);
2389   SDValue N1 = N->getOperand(1);
2390   SDValue CarryIn = N->getOperand(2);
2391
2392   // fold (sube x, y, false) -> (subc x, y)
2393   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2394     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2395
2396   return SDValue();
2397 }
2398
2399 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2400   SDValue N0 = N->getOperand(0);
2401   SDValue N1 = N->getOperand(1);
2402   SDValue CarryIn = N->getOperand(2);
2403
2404   // fold (subcarry x, y, false) -> (usubo x, y)
2405   if (isNullConstant(CarryIn))
2406     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2407
2408   return SDValue();
2409 }
2410
2411 SDValue DAGCombiner::visitMUL(SDNode *N) {
2412   SDValue N0 = N->getOperand(0);
2413   SDValue N1 = N->getOperand(1);
2414   EVT VT = N0.getValueType();
2415
2416   // fold (mul x, undef) -> 0
2417   if (N0.isUndef() || N1.isUndef())
2418     return DAG.getConstant(0, SDLoc(N), VT);
2419
2420   bool N0IsConst = false;
2421   bool N1IsConst = false;
2422   bool N1IsOpaqueConst = false;
2423   bool N0IsOpaqueConst = false;
2424   APInt ConstValue0, ConstValue1;
2425   // fold vector ops
2426   if (VT.isVector()) {
2427     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2428       return FoldedVOp;
2429
2430     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2431     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2432   } else {
2433     N0IsConst = isa<ConstantSDNode>(N0);
2434     if (N0IsConst) {
2435       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2436       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2437     }
2438     N1IsConst = isa<ConstantSDNode>(N1);
2439     if (N1IsConst) {
2440       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2441       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2442     }
2443   }
2444
2445   // fold (mul c1, c2) -> c1*c2
2446   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2447     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2448                                       N0.getNode(), N1.getNode());
2449
2450   // canonicalize constant to RHS (vector doesn't have to splat)
2451   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2452      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2453     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2454   // fold (mul x, 0) -> 0
2455   if (N1IsConst && ConstValue1 == 0)
2456     return N1;
2457   // We require a splat of the entire scalar bit width for non-contiguous
2458   // bit patterns.
2459   bool IsFullSplat =
2460     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2461   // fold (mul x, 1) -> x
2462   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2463     return N0;
2464
2465   if (SDValue NewSel = foldBinOpIntoSelect(N))
2466     return NewSel;
2467
2468   // fold (mul x, -1) -> 0-x
2469   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2470     SDLoc DL(N);
2471     return DAG.getNode(ISD::SUB, DL, VT,
2472                        DAG.getConstant(0, DL, VT), N0);
2473   }
2474   // fold (mul x, (1 << c)) -> x << c
2475   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2476       IsFullSplat) {
2477     SDLoc DL(N);
2478     return DAG.getNode(ISD::SHL, DL, VT, N0,
2479                        DAG.getConstant(ConstValue1.logBase2(), DL,
2480                                        getShiftAmountTy(N0.getValueType())));
2481   }
2482   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2483   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2484       IsFullSplat) {
2485     unsigned Log2Val = (-ConstValue1).logBase2();
2486     SDLoc DL(N);
2487     // FIXME: If the input is something that is easily negated (e.g. a
2488     // single-use add), we should put the negate there.
2489     return DAG.getNode(ISD::SUB, DL, VT,
2490                        DAG.getConstant(0, DL, VT),
2491                        DAG.getNode(ISD::SHL, DL, VT, N0,
2492                             DAG.getConstant(Log2Val, DL,
2493                                       getShiftAmountTy(N0.getValueType()))));
2494   }
2495
2496   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2497   if (N0.getOpcode() == ISD::SHL &&
2498       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2499       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2500     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2501     if (isConstantOrConstantVector(C3))
2502       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2503   }
2504
2505   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2506   // use.
2507   {
2508     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2509
2510     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2511     if (N0.getOpcode() == ISD::SHL &&
2512         isConstantOrConstantVector(N0.getOperand(1)) &&
2513         N0.getNode()->hasOneUse()) {
2514       Sh = N0; Y = N1;
2515     } else if (N1.getOpcode() == ISD::SHL &&
2516                isConstantOrConstantVector(N1.getOperand(1)) &&
2517                N1.getNode()->hasOneUse()) {
2518       Sh = N1; Y = N0;
2519     }
2520
2521     if (Sh.getNode()) {
2522       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2523       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2524     }
2525   }
2526
2527   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2528   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2529       N0.getOpcode() == ISD::ADD &&
2530       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2531       isMulAddWithConstProfitable(N, N0, N1))
2532       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2533                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2534                                      N0.getOperand(0), N1),
2535                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2536                                      N0.getOperand(1), N1));
2537
2538   // reassociate mul
2539   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2540     return RMUL;
2541
2542   return SDValue();
2543 }
2544
2545 /// Return true if divmod libcall is available.
2546 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2547                                      const TargetLowering &TLI) {
2548   RTLIB::Libcall LC;
2549   EVT NodeType = Node->getValueType(0);
2550   if (!NodeType.isSimple())
2551     return false;
2552   switch (NodeType.getSimpleVT().SimpleTy) {
2553   default: return false; // No libcall for vector types.
2554   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2555   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2556   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2557   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2558   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2559   }
2560
2561   return TLI.getLibcallName(LC) != nullptr;
2562 }
2563
2564 /// Issue divrem if both quotient and remainder are needed.
2565 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2566   if (Node->use_empty())
2567     return SDValue(); // This is a dead node, leave it alone.
2568
2569   unsigned Opcode = Node->getOpcode();
2570   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2571   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2572
2573   // DivMod lib calls can still work on non-legal types if using lib-calls.
2574   EVT VT = Node->getValueType(0);
2575   if (VT.isVector() || !VT.isInteger())
2576     return SDValue();
2577
2578   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2579     return SDValue();
2580
2581   // If DIVREM is going to get expanded into a libcall,
2582   // but there is no libcall available, then don't combine.
2583   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2584       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2585     return SDValue();
2586
2587   // If div is legal, it's better to do the normal expansion
2588   unsigned OtherOpcode = 0;
2589   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2590     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2591     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2592       return SDValue();
2593   } else {
2594     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2595     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2596       return SDValue();
2597   }
2598
2599   SDValue Op0 = Node->getOperand(0);
2600   SDValue Op1 = Node->getOperand(1);
2601   SDValue combined;
2602   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2603          UE = Op0.getNode()->use_end(); UI != UE;) {
2604     SDNode *User = *UI++;
2605     if (User == Node || User->use_empty())
2606       continue;
2607     // Convert the other matching node(s), too;
2608     // otherwise, the DIVREM may get target-legalized into something
2609     // target-specific that we won't be able to recognize.
2610     unsigned UserOpc = User->getOpcode();
2611     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2612         User->getOperand(0) == Op0 &&
2613         User->getOperand(1) == Op1) {
2614       if (!combined) {
2615         if (UserOpc == OtherOpcode) {
2616           SDVTList VTs = DAG.getVTList(VT, VT);
2617           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2618         } else if (UserOpc == DivRemOpc) {
2619           combined = SDValue(User, 0);
2620         } else {
2621           assert(UserOpc == Opcode);
2622           continue;
2623         }
2624       }
2625       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2626         CombineTo(User, combined);
2627       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2628         CombineTo(User, combined.getValue(1));
2629     }
2630   }
2631   return combined;
2632 }
2633
2634 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2635   SDValue N0 = N->getOperand(0);
2636   SDValue N1 = N->getOperand(1);
2637   EVT VT = N->getValueType(0);
2638   SDLoc DL(N);
2639
2640   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2641     return DAG.getUNDEF(VT);
2642
2643   // undef / X -> 0
2644   // undef % X -> 0
2645   if (N0.isUndef())
2646     return DAG.getConstant(0, DL, VT);
2647
2648   return SDValue();
2649 }
2650
2651 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2652   SDValue N0 = N->getOperand(0);
2653   SDValue N1 = N->getOperand(1);
2654   EVT VT = N->getValueType(0);
2655
2656   // fold vector ops
2657   if (VT.isVector())
2658     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2659       return FoldedVOp;
2660
2661   SDLoc DL(N);
2662
2663   // fold (sdiv c1, c2) -> c1/c2
2664   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2665   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2666   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2667     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2668   // fold (sdiv X, 1) -> X
2669   if (N1C && N1C->isOne())
2670     return N0;
2671   // fold (sdiv X, -1) -> 0-X
2672   if (N1C && N1C->isAllOnesValue())
2673     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2674
2675   if (SDValue V = simplifyDivRem(N, DAG))
2676     return V;
2677
2678   if (SDValue NewSel = foldBinOpIntoSelect(N))
2679     return NewSel;
2680
2681   // If we know the sign bits of both operands are zero, strength reduce to a
2682   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2683   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2684     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2685
2686   // fold (sdiv X, pow2) -> simple ops after legalize
2687   // FIXME: We check for the exact bit here because the generic lowering gives
2688   // better results in that case. The target-specific lowering should learn how
2689   // to handle exact sdivs efficiently.
2690   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2691       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2692                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2693     // Target-specific implementation of sdiv x, pow2.
2694     if (SDValue Res = BuildSDIVPow2(N))
2695       return Res;
2696
2697     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2698
2699     // Splat the sign bit into the register
2700     SDValue SGN =
2701         DAG.getNode(ISD::SRA, DL, VT, N0,
2702                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2703                                     getShiftAmountTy(N0.getValueType())));
2704     AddToWorklist(SGN.getNode());
2705
2706     // Add (N0 < 0) ? abs2 - 1 : 0;
2707     SDValue SRL =
2708         DAG.getNode(ISD::SRL, DL, VT, SGN,
2709                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2710                                     getShiftAmountTy(SGN.getValueType())));
2711     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2712     AddToWorklist(SRL.getNode());
2713     AddToWorklist(ADD.getNode());    // Divide by pow2
2714     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2715                   DAG.getConstant(lg2, DL,
2716                                   getShiftAmountTy(ADD.getValueType())));
2717
2718     // If we're dividing by a positive value, we're done.  Otherwise, we must
2719     // negate the result.
2720     if (N1C->getAPIntValue().isNonNegative())
2721       return SRA;
2722
2723     AddToWorklist(SRA.getNode());
2724     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2725   }
2726
2727   // If integer divide is expensive and we satisfy the requirements, emit an
2728   // alternate sequence.  Targets may check function attributes for size/speed
2729   // trade-offs.
2730   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2731   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2732     if (SDValue Op = BuildSDIV(N))
2733       return Op;
2734
2735   // sdiv, srem -> sdivrem
2736   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2737   // true.  Otherwise, we break the simplification logic in visitREM().
2738   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2739     if (SDValue DivRem = useDivRem(N))
2740         return DivRem;
2741
2742   return SDValue();
2743 }
2744
2745 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2746   SDValue N0 = N->getOperand(0);
2747   SDValue N1 = N->getOperand(1);
2748   EVT VT = N->getValueType(0);
2749
2750   // fold vector ops
2751   if (VT.isVector())
2752     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2753       return FoldedVOp;
2754
2755   SDLoc DL(N);
2756
2757   // fold (udiv c1, c2) -> c1/c2
2758   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2759   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2760   if (N0C && N1C)
2761     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2762                                                     N0C, N1C))
2763       return Folded;
2764
2765   if (SDValue V = simplifyDivRem(N, DAG))
2766     return V;
2767
2768   if (SDValue NewSel = foldBinOpIntoSelect(N))
2769     return NewSel;
2770
2771   // fold (udiv x, (1 << c)) -> x >>u c
2772   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2773       DAG.isKnownToBeAPowerOfTwo(N1)) {
2774     SDValue LogBase2 = BuildLogBase2(N1, DL);
2775     AddToWorklist(LogBase2.getNode());
2776
2777     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2778     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2779     AddToWorklist(Trunc.getNode());
2780     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2781   }
2782
2783   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2784   if (N1.getOpcode() == ISD::SHL) {
2785     SDValue N10 = N1.getOperand(0);
2786     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2787         DAG.isKnownToBeAPowerOfTwo(N10)) {
2788       SDValue LogBase2 = BuildLogBase2(N10, DL);
2789       AddToWorklist(LogBase2.getNode());
2790
2791       EVT ADDVT = N1.getOperand(1).getValueType();
2792       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2793       AddToWorklist(Trunc.getNode());
2794       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2795       AddToWorklist(Add.getNode());
2796       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2797     }
2798   }
2799
2800   // fold (udiv x, c) -> alternate
2801   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2802   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2803     if (SDValue Op = BuildUDIV(N))
2804       return Op;
2805
2806   // sdiv, srem -> sdivrem
2807   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2808   // true.  Otherwise, we break the simplification logic in visitREM().
2809   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2810     if (SDValue DivRem = useDivRem(N))
2811         return DivRem;
2812
2813   return SDValue();
2814 }
2815
2816 // handles ISD::SREM and ISD::UREM
2817 SDValue DAGCombiner::visitREM(SDNode *N) {
2818   unsigned Opcode = N->getOpcode();
2819   SDValue N0 = N->getOperand(0);
2820   SDValue N1 = N->getOperand(1);
2821   EVT VT = N->getValueType(0);
2822   bool isSigned = (Opcode == ISD::SREM);
2823   SDLoc DL(N);
2824
2825   // fold (rem c1, c2) -> c1%c2
2826   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2827   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2828   if (N0C && N1C)
2829     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2830       return Folded;
2831
2832   if (SDValue V = simplifyDivRem(N, DAG))
2833     return V;
2834
2835   if (SDValue NewSel = foldBinOpIntoSelect(N))
2836     return NewSel;
2837
2838   if (isSigned) {
2839     // If we know the sign bits of both operands are zero, strength reduce to a
2840     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2841     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2842       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2843   } else {
2844     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2845     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2846       // fold (urem x, pow2) -> (and x, pow2-1)
2847       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2848       AddToWorklist(Add.getNode());
2849       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2850     }
2851     if (N1.getOpcode() == ISD::SHL &&
2852         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2853       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2854       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2855       AddToWorklist(Add.getNode());
2856       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2857     }
2858   }
2859
2860   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2861
2862   // If X/C can be simplified by the division-by-constant logic, lower
2863   // X%C to the equivalent of X-X/C*C.
2864   // To avoid mangling nodes, this simplification requires that the combine()
2865   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2866   // against this by skipping the simplification if isIntDivCheap().  When
2867   // div is not cheap, combine will not return a DIVREM.  Regardless,
2868   // checking cheapness here makes sense since the simplification results in
2869   // fatter code.
2870   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2871     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2872     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2873     AddToWorklist(Div.getNode());
2874     SDValue OptimizedDiv = combine(Div.getNode());
2875     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2876       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2877              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2878       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2879       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2880       AddToWorklist(Mul.getNode());
2881       return Sub;
2882     }
2883   }
2884
2885   // sdiv, srem -> sdivrem
2886   if (SDValue DivRem = useDivRem(N))
2887     return DivRem.getValue(1);
2888
2889   return SDValue();
2890 }
2891
2892 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2893   SDValue N0 = N->getOperand(0);
2894   SDValue N1 = N->getOperand(1);
2895   EVT VT = N->getValueType(0);
2896   SDLoc DL(N);
2897
2898   // fold (mulhs x, 0) -> 0
2899   if (isNullConstant(N1))
2900     return N1;
2901   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2902   if (isOneConstant(N1)) {
2903     SDLoc DL(N);
2904     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2905                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2906                                        getShiftAmountTy(N0.getValueType())));
2907   }
2908   // fold (mulhs x, undef) -> 0
2909   if (N0.isUndef() || N1.isUndef())
2910     return DAG.getConstant(0, SDLoc(N), VT);
2911
2912   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2913   // plus a shift.
2914   if (VT.isSimple() && !VT.isVector()) {
2915     MVT Simple = VT.getSimpleVT();
2916     unsigned SimpleSize = Simple.getSizeInBits();
2917     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2918     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2919       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2920       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2921       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2922       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2923             DAG.getConstant(SimpleSize, DL,
2924                             getShiftAmountTy(N1.getValueType())));
2925       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2926     }
2927   }
2928
2929   return SDValue();
2930 }
2931
2932 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2933   SDValue N0 = N->getOperand(0);
2934   SDValue N1 = N->getOperand(1);
2935   EVT VT = N->getValueType(0);
2936   SDLoc DL(N);
2937
2938   // fold (mulhu x, 0) -> 0
2939   if (isNullConstant(N1))
2940     return N1;
2941   // fold (mulhu x, 1) -> 0
2942   if (isOneConstant(N1))
2943     return DAG.getConstant(0, DL, N0.getValueType());
2944   // fold (mulhu x, undef) -> 0
2945   if (N0.isUndef() || N1.isUndef())
2946     return DAG.getConstant(0, DL, VT);
2947
2948   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2949   // plus a shift.
2950   if (VT.isSimple() && !VT.isVector()) {
2951     MVT Simple = VT.getSimpleVT();
2952     unsigned SimpleSize = Simple.getSizeInBits();
2953     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2954     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2955       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2956       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2957       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2958       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2959             DAG.getConstant(SimpleSize, DL,
2960                             getShiftAmountTy(N1.getValueType())));
2961       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2962     }
2963   }
2964
2965   return SDValue();
2966 }
2967
2968 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2969 /// give the opcodes for the two computations that are being performed. Return
2970 /// true if a simplification was made.
2971 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2972                                                 unsigned HiOp) {
2973   // If the high half is not needed, just compute the low half.
2974   bool HiExists = N->hasAnyUseOfValue(1);
2975   if (!HiExists &&
2976       (!LegalOperations ||
2977        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2978     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2979     return CombineTo(N, Res, Res);
2980   }
2981
2982   // If the low half is not needed, just compute the high half.
2983   bool LoExists = N->hasAnyUseOfValue(0);
2984   if (!LoExists &&
2985       (!LegalOperations ||
2986        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2987     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2988     return CombineTo(N, Res, Res);
2989   }
2990
2991   // If both halves are used, return as it is.
2992   if (LoExists && HiExists)
2993     return SDValue();
2994
2995   // If the two computed results can be simplified separately, separate them.
2996   if (LoExists) {
2997     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2998     AddToWorklist(Lo.getNode());
2999     SDValue LoOpt = combine(Lo.getNode());
3000     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3001         (!LegalOperations ||
3002          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3003       return CombineTo(N, LoOpt, LoOpt);
3004   }
3005
3006   if (HiExists) {
3007     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3008     AddToWorklist(Hi.getNode());
3009     SDValue HiOpt = combine(Hi.getNode());
3010     if (HiOpt.getNode() && HiOpt != Hi &&
3011         (!LegalOperations ||
3012          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3013       return CombineTo(N, HiOpt, HiOpt);
3014   }
3015
3016   return SDValue();
3017 }
3018
3019 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3020   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3021     return Res;
3022
3023   EVT VT = N->getValueType(0);
3024   SDLoc DL(N);
3025
3026   // If the type is twice as wide is legal, transform the mulhu to a wider
3027   // multiply plus a shift.
3028   if (VT.isSimple() && !VT.isVector()) {
3029     MVT Simple = VT.getSimpleVT();
3030     unsigned SimpleSize = Simple.getSizeInBits();
3031     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3032     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3033       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3034       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3035       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3036       // Compute the high part as N1.
3037       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3038             DAG.getConstant(SimpleSize, DL,
3039                             getShiftAmountTy(Lo.getValueType())));
3040       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3041       // Compute the low part as N0.
3042       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3043       return CombineTo(N, Lo, Hi);
3044     }
3045   }
3046
3047   return SDValue();
3048 }
3049
3050 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3051   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3052     return Res;
3053
3054   EVT VT = N->getValueType(0);
3055   SDLoc DL(N);
3056
3057   // If the type is twice as wide is legal, transform the mulhu to a wider
3058   // multiply plus a shift.
3059   if (VT.isSimple() && !VT.isVector()) {
3060     MVT Simple = VT.getSimpleVT();
3061     unsigned SimpleSize = Simple.getSizeInBits();
3062     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3063     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3064       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3065       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3066       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3067       // Compute the high part as N1.
3068       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3069             DAG.getConstant(SimpleSize, DL,
3070                             getShiftAmountTy(Lo.getValueType())));
3071       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3072       // Compute the low part as N0.
3073       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3074       return CombineTo(N, Lo, Hi);
3075     }
3076   }
3077
3078   return SDValue();
3079 }
3080
3081 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3082   // (smulo x, 2) -> (saddo x, x)
3083   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3084     if (C2->getAPIntValue() == 2)
3085       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3086                          N->getOperand(0), N->getOperand(0));
3087
3088   return SDValue();
3089 }
3090
3091 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3092   // (umulo x, 2) -> (uaddo x, x)
3093   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3094     if (C2->getAPIntValue() == 2)
3095       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3096                          N->getOperand(0), N->getOperand(0));
3097
3098   return SDValue();
3099 }
3100
3101 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3102   SDValue N0 = N->getOperand(0);
3103   SDValue N1 = N->getOperand(1);
3104   EVT VT = N0.getValueType();
3105
3106   // fold vector ops
3107   if (VT.isVector())
3108     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3109       return FoldedVOp;
3110
3111   // fold (add c1, c2) -> c1+c2
3112   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3113   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3114   if (N0C && N1C)
3115     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3116
3117   // canonicalize constant to RHS
3118   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3119      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3120     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3121
3122   return SDValue();
3123 }
3124
3125 /// If this is a binary operator with two operands of the same opcode, try to
3126 /// simplify it.
3127 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3128   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3129   EVT VT = N0.getValueType();
3130   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3131
3132   // Bail early if none of these transforms apply.
3133   if (N0.getNumOperands() == 0) return SDValue();
3134
3135   // For each of OP in AND/OR/XOR:
3136   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3137   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3138   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3139   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3140   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3141   //
3142   // do not sink logical op inside of a vector extend, since it may combine
3143   // into a vsetcc.
3144   EVT Op0VT = N0.getOperand(0).getValueType();
3145   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3146        N0.getOpcode() == ISD::SIGN_EXTEND ||
3147        N0.getOpcode() == ISD::BSWAP ||
3148        // Avoid infinite looping with PromoteIntBinOp.
3149        (N0.getOpcode() == ISD::ANY_EXTEND &&
3150         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3151        (N0.getOpcode() == ISD::TRUNCATE &&
3152         (!TLI.isZExtFree(VT, Op0VT) ||
3153          !TLI.isTruncateFree(Op0VT, VT)) &&
3154         TLI.isTypeLegal(Op0VT))) &&
3155       !VT.isVector() &&
3156       Op0VT == N1.getOperand(0).getValueType() &&
3157       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3158     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3159                                  N0.getOperand(0).getValueType(),
3160                                  N0.getOperand(0), N1.getOperand(0));
3161     AddToWorklist(ORNode.getNode());
3162     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3163   }
3164
3165   // For each of OP in SHL/SRL/SRA/AND...
3166   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3167   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3168   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3169   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3170        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3171       N0.getOperand(1) == N1.getOperand(1)) {
3172     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3173                                  N0.getOperand(0).getValueType(),
3174                                  N0.getOperand(0), N1.getOperand(0));
3175     AddToWorklist(ORNode.getNode());
3176     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3177                        ORNode, N0.getOperand(1));
3178   }
3179
3180   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3181   // Only perform this optimization up until type legalization, before
3182   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3183   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3184   // we don't want to undo this promotion.
3185   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3186   // on scalars.
3187   if ((N0.getOpcode() == ISD::BITCAST ||
3188        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3189        Level <= AfterLegalizeTypes) {
3190     SDValue In0 = N0.getOperand(0);
3191     SDValue In1 = N1.getOperand(0);
3192     EVT In0Ty = In0.getValueType();
3193     EVT In1Ty = In1.getValueType();
3194     SDLoc DL(N);
3195     // If both incoming values are integers, and the original types are the
3196     // same.
3197     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3198       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3199       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3200       AddToWorklist(Op.getNode());
3201       return BC;
3202     }
3203   }
3204
3205   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3206   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3207   // If both shuffles use the same mask, and both shuffle within a single
3208   // vector, then it is worthwhile to move the swizzle after the operation.
3209   // The type-legalizer generates this pattern when loading illegal
3210   // vector types from memory. In many cases this allows additional shuffle
3211   // optimizations.
3212   // There are other cases where moving the shuffle after the xor/and/or
3213   // is profitable even if shuffles don't perform a swizzle.
3214   // If both shuffles use the same mask, and both shuffles have the same first
3215   // or second operand, then it might still be profitable to move the shuffle
3216   // after the xor/and/or operation.
3217   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3218     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3219     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3220
3221     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3222            "Inputs to shuffles are not the same type");
3223
3224     // Check that both shuffles use the same mask. The masks are known to be of
3225     // the same length because the result vector type is the same.
3226     // Check also that shuffles have only one use to avoid introducing extra
3227     // instructions.
3228     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3229         SVN0->getMask().equals(SVN1->getMask())) {
3230       SDValue ShOp = N0->getOperand(1);
3231
3232       // Don't try to fold this node if it requires introducing a
3233       // build vector of all zeros that might be illegal at this stage.
3234       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3235         if (!LegalTypes)
3236           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3237         else
3238           ShOp = SDValue();
3239       }
3240
3241       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3242       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3243       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3244       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3245         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3246                                       N0->getOperand(0), N1->getOperand(0));
3247         AddToWorklist(NewNode.getNode());
3248         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3249                                     SVN0->getMask());
3250       }
3251
3252       // Don't try to fold this node if it requires introducing a
3253       // build vector of all zeros that might be illegal at this stage.
3254       ShOp = N0->getOperand(0);
3255       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3256         if (!LegalTypes)
3257           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3258         else
3259           ShOp = SDValue();
3260       }
3261
3262       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3263       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3264       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3265       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3266         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3267                                       N0->getOperand(1), N1->getOperand(1));
3268         AddToWorklist(NewNode.getNode());
3269         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3270                                     SVN0->getMask());
3271       }
3272     }
3273   }
3274
3275   return SDValue();
3276 }
3277
3278 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3279 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3280                                        const SDLoc &DL) {
3281   SDValue LL, LR, RL, RR, N0CC, N1CC;
3282   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3283       !isSetCCEquivalent(N1, RL, RR, N1CC))
3284     return SDValue();
3285
3286   assert(N0.getValueType() == N1.getValueType() &&
3287          "Unexpected operand types for bitwise logic op");
3288   assert(LL.getValueType() == LR.getValueType() &&
3289          RL.getValueType() == RR.getValueType() &&
3290          "Unexpected operand types for setcc");
3291
3292   // If we're here post-legalization or the logic op type is not i1, the logic
3293   // op type must match a setcc result type. Also, all folds require new
3294   // operations on the left and right operands, so those types must match.
3295   EVT VT = N0.getValueType();
3296   EVT OpVT = LL.getValueType();
3297   if (LegalOperations || VT != MVT::i1)
3298     if (VT != getSetCCResultType(OpVT))
3299       return SDValue();
3300   if (OpVT != RL.getValueType())
3301     return SDValue();
3302
3303   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3304   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3305   bool IsInteger = OpVT.isInteger();
3306   if (LR == RR && CC0 == CC1 && IsInteger) {
3307     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3308     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3309
3310     // All bits clear?
3311     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3312     // All sign bits clear?
3313     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3314     // Any bits set?
3315     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3316     // Any sign bits set?
3317     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3318
3319     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3320     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3321     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3322     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3323     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3324       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3325       AddToWorklist(Or.getNode());
3326       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3327     }
3328
3329     // All bits set?
3330     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3331     // All sign bits set?
3332     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3333     // Any bits clear?
3334     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3335     // Any sign bits clear?
3336     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3337
3338     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3339     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3340     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3341     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3342     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3343       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3344       AddToWorklist(And.getNode());
3345       return DAG.getSetCC(DL, VT, And, LR, CC1);
3346     }
3347   }
3348
3349   // TODO: What is the 'or' equivalent of this fold?
3350   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3351   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3352       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3353        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3354     SDValue One = DAG.getConstant(1, DL, OpVT);
3355     SDValue Two = DAG.getConstant(2, DL, OpVT);
3356     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3357     AddToWorklist(Add.getNode());
3358     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3359   }
3360
3361   // Try more general transforms if the predicates match and the only user of
3362   // the compares is the 'and' or 'or'.
3363   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3364       N0.hasOneUse() && N1.hasOneUse()) {
3365     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3366     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3367     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3368       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3369       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3370       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3371       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3372       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3373     }
3374   }
3375
3376   // Canonicalize equivalent operands to LL == RL.
3377   if (LL == RR && LR == RL) {
3378     CC1 = ISD::getSetCCSwappedOperands(CC1);
3379     std::swap(RL, RR);
3380   }
3381
3382   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3383   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3384   if (LL == RL && LR == RR) {
3385     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3386                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3387     if (NewCC != ISD::SETCC_INVALID &&
3388         (!LegalOperations ||
3389          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3390           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3391       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3392   }
3393
3394   return SDValue();
3395 }
3396
3397 /// This contains all DAGCombine rules which reduce two values combined by
3398 /// an And operation to a single value. This makes them reusable in the context
3399 /// of visitSELECT(). Rules involving constants are not included as
3400 /// visitSELECT() already handles those cases.
3401 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3402   EVT VT = N1.getValueType();
3403   SDLoc DL(N);
3404
3405   // fold (and x, undef) -> 0
3406   if (N0.isUndef() || N1.isUndef())
3407     return DAG.getConstant(0, DL, VT);
3408
3409   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3410     return V;
3411
3412   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3413       VT.getSizeInBits() <= 64) {
3414     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3415       APInt ADDC = ADDI->getAPIntValue();
3416       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3417         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3418         // immediate for an add, but it is legal if its top c2 bits are set,
3419         // transform the ADD so the immediate doesn't need to be materialized
3420         // in a register.
3421         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3422           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3423                                              SRLI->getZExtValue());
3424           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3425             ADDC |= Mask;
3426             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3427               SDLoc DL0(N0);
3428               SDValue NewAdd =
3429                 DAG.getNode(ISD::ADD, DL0, VT,
3430                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3431               CombineTo(N0.getNode(), NewAdd);
3432               // Return N so it doesn't get rechecked!
3433               return SDValue(N, 0);
3434             }
3435           }
3436         }
3437       }
3438     }
3439   }
3440
3441   // Reduce bit extract of low half of an integer to the narrower type.
3442   // (and (srl i64:x, K), KMask) ->
3443   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3444   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3445     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3446       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3447         unsigned Size = VT.getSizeInBits();
3448         const APInt &AndMask = CAnd->getAPIntValue();
3449         unsigned ShiftBits = CShift->getZExtValue();
3450
3451         // Bail out, this node will probably disappear anyway.
3452         if (ShiftBits == 0)
3453           return SDValue();
3454
3455         unsigned MaskBits = AndMask.countTrailingOnes();
3456         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3457
3458         if (AndMask.isMask() &&
3459             // Required bits must not span the two halves of the integer and
3460             // must fit in the half size type.
3461             (ShiftBits + MaskBits <= Size / 2) &&
3462             TLI.isNarrowingProfitable(VT, HalfVT) &&
3463             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3464             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3465             TLI.isTruncateFree(VT, HalfVT) &&
3466             TLI.isZExtFree(HalfVT, VT)) {
3467           // The isNarrowingProfitable is to avoid regressions on PPC and
3468           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3469           // on downstream users of this. Those patterns could probably be
3470           // extended to handle extensions mixed in.
3471
3472           SDValue SL(N0);
3473           assert(MaskBits <= Size);
3474
3475           // Extracting the highest bit of the low half.
3476           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3477           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3478                                       N0.getOperand(0));
3479
3480           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3481           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3482           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3483           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3484           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3485         }
3486       }
3487     }
3488   }
3489
3490   return SDValue();
3491 }
3492
3493 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3494                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3495                                    bool &NarrowLoad) {
3496   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3497
3498   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3499     return false;
3500
3501   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3502   LoadedVT = LoadN->getMemoryVT();
3503
3504   if (ExtVT == LoadedVT &&
3505       (!LegalOperations ||
3506        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3507     // ZEXTLOAD will match without needing to change the size of the value being
3508     // loaded.
3509     NarrowLoad = false;
3510     return true;
3511   }
3512
3513   // Do not change the width of a volatile load.
3514   if (LoadN->isVolatile())
3515     return false;
3516
3517   // Do not generate loads of non-round integer types since these can
3518   // be expensive (and would be wrong if the type is not byte sized).
3519   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3520     return false;
3521
3522   if (LegalOperations &&
3523       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3524     return false;
3525
3526   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3527     return false;
3528
3529   NarrowLoad = true;
3530   return true;
3531 }
3532
3533 SDValue DAGCombiner::visitAND(SDNode *N) {
3534   SDValue N0 = N->getOperand(0);
3535   SDValue N1 = N->getOperand(1);
3536   EVT VT = N1.getValueType();
3537
3538   // x & x --> x
3539   if (N0 == N1)
3540     return N0;
3541
3542   // fold vector ops
3543   if (VT.isVector()) {
3544     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3545       return FoldedVOp;
3546
3547     // fold (and x, 0) -> 0, vector edition
3548     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3549       // do not return N0, because undef node may exist in N0
3550       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3551                              SDLoc(N), N0.getValueType());
3552     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3553       // do not return N1, because undef node may exist in N1
3554       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3555                              SDLoc(N), N1.getValueType());
3556
3557     // fold (and x, -1) -> x, vector edition
3558     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3559       return N1;
3560     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3561       return N0;
3562   }
3563
3564   // fold (and c1, c2) -> c1&c2
3565   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3566   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3567   if (N0C && N1C && !N1C->isOpaque())
3568     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3569   // canonicalize constant to RHS
3570   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3571      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3572     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3573   // fold (and x, -1) -> x
3574   if (isAllOnesConstant(N1))
3575     return N0;
3576   // if (and x, c) is known to be zero, return 0
3577   unsigned BitWidth = VT.getScalarSizeInBits();
3578   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3579                                    APInt::getAllOnesValue(BitWidth)))
3580     return DAG.getConstant(0, SDLoc(N), VT);
3581
3582   if (SDValue NewSel = foldBinOpIntoSelect(N))
3583     return NewSel;
3584
3585   // reassociate and
3586   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3587     return RAND;
3588   // fold (and (or x, C), D) -> D if (C & D) == D
3589   if (N1C && N0.getOpcode() == ISD::OR)
3590     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3591       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3592         return N1;
3593   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3594   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3595     SDValue N0Op0 = N0.getOperand(0);
3596     APInt Mask = ~N1C->getAPIntValue();
3597     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3598     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3599       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3600                                  N0.getValueType(), N0Op0);
3601
3602       // Replace uses of the AND with uses of the Zero extend node.
3603       CombineTo(N, Zext);
3604
3605       // We actually want to replace all uses of the any_extend with the
3606       // zero_extend, to avoid duplicating things.  This will later cause this
3607       // AND to be folded.
3608       CombineTo(N0.getNode(), Zext);
3609       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3610     }
3611   }
3612   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3613   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3614   // already be zero by virtue of the width of the base type of the load.
3615   //
3616   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3617   // more cases.
3618   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3619        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3620        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3621        N0.getOperand(0).getResNo() == 0) ||
3622       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3623     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3624                                          N0 : N0.getOperand(0) );
3625
3626     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3627     // This can be a pure constant or a vector splat, in which case we treat the
3628     // vector as a scalar and use the splat value.
3629     APInt Constant = APInt::getNullValue(1);
3630     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3631       Constant = C->getAPIntValue();
3632     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3633       APInt SplatValue, SplatUndef;
3634       unsigned SplatBitSize;
3635       bool HasAnyUndefs;
3636       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3637                                              SplatBitSize, HasAnyUndefs);
3638       if (IsSplat) {
3639         // Undef bits can contribute to a possible optimisation if set, so
3640         // set them.
3641         SplatValue |= SplatUndef;
3642
3643         // The splat value may be something like "0x00FFFFFF", which means 0 for
3644         // the first vector value and FF for the rest, repeating. We need a mask
3645         // that will apply equally to all members of the vector, so AND all the
3646         // lanes of the constant together.
3647         EVT VT = Vector->getValueType(0);
3648         unsigned BitWidth = VT.getScalarSizeInBits();
3649
3650         // If the splat value has been compressed to a bitlength lower
3651         // than the size of the vector lane, we need to re-expand it to
3652         // the lane size.
3653         if (BitWidth > SplatBitSize)
3654           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3655                SplatBitSize < BitWidth;
3656                SplatBitSize = SplatBitSize * 2)
3657             SplatValue |= SplatValue.shl(SplatBitSize);
3658
3659         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3660         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3661         if (SplatBitSize % BitWidth == 0) {
3662           Constant = APInt::getAllOnesValue(BitWidth);
3663           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3664             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3665         }
3666       }
3667     }
3668
3669     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3670     // actually legal and isn't going to get expanded, else this is a false
3671     // optimisation.
3672     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3673                                                     Load->getValueType(0),
3674                                                     Load->getMemoryVT());
3675
3676     // Resize the constant to the same size as the original memory access before
3677     // extension. If it is still the AllOnesValue then this AND is completely
3678     // unneeded.
3679     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3680
3681     bool B;
3682     switch (Load->getExtensionType()) {
3683     default: B = false; break;
3684     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3685     case ISD::ZEXTLOAD:
3686     case ISD::NON_EXTLOAD: B = true; break;
3687     }
3688
3689     if (B && Constant.isAllOnesValue()) {
3690       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3691       // preserve semantics once we get rid of the AND.
3692       SDValue NewLoad(Load, 0);
3693
3694       // Fold the AND away. NewLoad may get replaced immediately.
3695       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3696
3697       if (Load->getExtensionType() == ISD::EXTLOAD) {
3698         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3699                               Load->getValueType(0), SDLoc(Load),
3700                               Load->getChain(), Load->getBasePtr(),
3701                               Load->getOffset(), Load->getMemoryVT(),
3702                               Load->getMemOperand());
3703         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3704         if (Load->getNumValues() == 3) {
3705           // PRE/POST_INC loads have 3 values.
3706           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3707                            NewLoad.getValue(2) };
3708           CombineTo(Load, To, 3, true);
3709         } else {
3710           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3711         }
3712       }
3713
3714       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3715     }
3716   }
3717
3718   // fold (and (load x), 255) -> (zextload x, i8)
3719   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3720   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3721   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3722                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3723                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3724     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3725     LoadSDNode *LN0 = HasAnyExt
3726       ? cast<LoadSDNode>(N0.getOperand(0))
3727       : cast<LoadSDNode>(N0);
3728     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3729         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3730       auto NarrowLoad = false;
3731       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3732       EVT ExtVT, LoadedVT;
3733       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3734                            NarrowLoad)) {
3735         if (!NarrowLoad) {
3736           SDValue NewLoad =
3737             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3738                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3739                            LN0->getMemOperand());
3740           AddToWorklist(N);
3741           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3742           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3743         } else {
3744           EVT PtrType = LN0->getOperand(1).getValueType();
3745
3746           unsigned Alignment = LN0->getAlignment();
3747           SDValue NewPtr = LN0->getBasePtr();
3748
3749           // For big endian targets, we need to add an offset to the pointer
3750           // to load the correct bytes.  For little endian systems, we merely
3751           // need to read fewer bytes from the same pointer.
3752           if (DAG.getDataLayout().isBigEndian()) {
3753             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3754             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3755             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3756             SDLoc DL(LN0);
3757             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3758                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3759             Alignment = MinAlign(Alignment, PtrOff);
3760           }
3761
3762           AddToWorklist(NewPtr.getNode());
3763
3764           SDValue Load = DAG.getExtLoad(
3765               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3766               LN0->getPointerInfo(), ExtVT, Alignment,
3767               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3768           AddToWorklist(N);
3769           CombineTo(LN0, Load, Load.getValue(1));
3770           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3771         }
3772       }
3773     }
3774   }
3775
3776   if (SDValue Combined = visitANDLike(N0, N1, N))
3777     return Combined;
3778
3779   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3780   if (N0.getOpcode() == N1.getOpcode())
3781     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3782       return Tmp;
3783
3784   // Masking the negated extension of a boolean is just the zero-extended
3785   // boolean:
3786   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3787   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3788   //
3789   // Note: the SimplifyDemandedBits fold below can make an information-losing
3790   // transform, and then we have no way to find this better fold.
3791   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3792     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3793     SDValue SubRHS = N0.getOperand(1);
3794     if (SubLHS && SubLHS->isNullValue()) {
3795       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3796           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3797         return SubRHS;
3798       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3799           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3800         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3801     }
3802   }
3803
3804   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3805   // fold (and (sra)) -> (and (srl)) when possible.
3806   if (SimplifyDemandedBits(SDValue(N, 0)))
3807     return SDValue(N, 0);
3808
3809   // fold (zext_inreg (extload x)) -> (zextload x)
3810   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3811     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3812     EVT MemVT = LN0->getMemoryVT();
3813     // If we zero all the possible extended bits, then we can turn this into
3814     // a zextload if we are running before legalize or the operation is legal.
3815     unsigned BitWidth = N1.getScalarValueSizeInBits();
3816     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3817                            BitWidth - MemVT.getScalarSizeInBits())) &&
3818         ((!LegalOperations && !LN0->isVolatile()) ||
3819          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3820       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3821                                        LN0->getChain(), LN0->getBasePtr(),
3822                                        MemVT, LN0->getMemOperand());
3823       AddToWorklist(N);
3824       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3825       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3826     }
3827   }
3828   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3829   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3830       N0.hasOneUse()) {
3831     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3832     EVT MemVT = LN0->getMemoryVT();
3833     // If we zero all the possible extended bits, then we can turn this into
3834     // a zextload if we are running before legalize or the operation is legal.
3835     unsigned BitWidth = N1.getScalarValueSizeInBits();
3836     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3837                            BitWidth - MemVT.getScalarSizeInBits())) &&
3838         ((!LegalOperations && !LN0->isVolatile()) ||
3839          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3840       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3841                                        LN0->getChain(), LN0->getBasePtr(),
3842                                        MemVT, LN0->getMemOperand());
3843       AddToWorklist(N);
3844       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3845       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3846     }
3847   }
3848   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3849   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3850     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3851                                            N0.getOperand(1), false))
3852       return BSwap;
3853   }
3854
3855   return SDValue();
3856 }
3857
3858 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3859 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3860                                         bool DemandHighBits) {
3861   if (!LegalOperations)
3862     return SDValue();
3863
3864   EVT VT = N->getValueType(0);
3865   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3866     return SDValue();
3867   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3868     return SDValue();
3869
3870   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3871   bool LookPassAnd0 = false;
3872   bool LookPassAnd1 = false;
3873   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3874       std::swap(N0, N1);
3875   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3876       std::swap(N0, N1);
3877   if (N0.getOpcode() == ISD::AND) {
3878     if (!N0.getNode()->hasOneUse())
3879       return SDValue();
3880     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3881     if (!N01C || N01C->getZExtValue() != 0xFF00)
3882       return SDValue();
3883     N0 = N0.getOperand(0);
3884     LookPassAnd0 = true;
3885   }
3886
3887   if (N1.getOpcode() == ISD::AND) {
3888     if (!N1.getNode()->hasOneUse())
3889       return SDValue();
3890     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3891     if (!N11C || N11C->getZExtValue() != 0xFF)
3892       return SDValue();
3893     N1 = N1.getOperand(0);
3894     LookPassAnd1 = true;
3895   }
3896
3897   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3898     std::swap(N0, N1);
3899   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3900     return SDValue();
3901   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3902     return SDValue();
3903
3904   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3905   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3906   if (!N01C || !N11C)
3907     return SDValue();
3908   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3909     return SDValue();
3910
3911   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3912   SDValue N00 = N0->getOperand(0);
3913   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3914     if (!N00.getNode()->hasOneUse())
3915       return SDValue();
3916     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3917     if (!N001C || N001C->getZExtValue() != 0xFF)
3918       return SDValue();
3919     N00 = N00.getOperand(0);
3920     LookPassAnd0 = true;
3921   }
3922
3923   SDValue N10 = N1->getOperand(0);
3924   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3925     if (!N10.getNode()->hasOneUse())
3926       return SDValue();
3927     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3928     if (!N101C || N101C->getZExtValue() != 0xFF00)
3929       return SDValue();
3930     N10 = N10.getOperand(0);
3931     LookPassAnd1 = true;
3932   }
3933
3934   if (N00 != N10)
3935     return SDValue();
3936
3937   // Make sure everything beyond the low halfword gets set to zero since the SRL
3938   // 16 will clear the top bits.
3939   unsigned OpSizeInBits = VT.getSizeInBits();
3940   if (DemandHighBits && OpSizeInBits > 16) {
3941     // If the left-shift isn't masked out then the only way this is a bswap is
3942     // if all bits beyond the low 8 are 0. In that case the entire pattern
3943     // reduces to a left shift anyway: leave it for other parts of the combiner.
3944     if (!LookPassAnd0)
3945       return SDValue();
3946
3947     // However, if the right shift isn't masked out then it might be because
3948     // it's not needed. See if we can spot that too.
3949     if (!LookPassAnd1 &&
3950         !DAG.MaskedValueIsZero(
3951             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3952       return SDValue();
3953   }
3954
3955   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3956   if (OpSizeInBits > 16) {
3957     SDLoc DL(N);
3958     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3959                       DAG.getConstant(OpSizeInBits - 16, DL,
3960                                       getShiftAmountTy(VT)));
3961   }
3962   return Res;
3963 }
3964
3965 /// Return true if the specified node is an element that makes up a 32-bit
3966 /// packed halfword byteswap.
3967 /// ((x & 0x000000ff) << 8) |
3968 /// ((x & 0x0000ff00) >> 8) |
3969 /// ((x & 0x00ff0000) << 8) |
3970 /// ((x & 0xff000000) >> 8)
3971 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3972   if (!N.getNode()->hasOneUse())
3973     return false;
3974
3975   unsigned Opc = N.getOpcode();
3976   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3977     return false;
3978
3979   SDValue N0 = N.getOperand(0);
3980   unsigned Opc0 = N0.getOpcode();
3981   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
3982     return false;
3983
3984   ConstantSDNode *N1C = nullptr;
3985   // SHL or SRL: look upstream for AND mask operand
3986   if (Opc == ISD::AND)
3987     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3988   else if (Opc0 == ISD::AND)
3989     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3990   if (!N1C)
3991     return false;
3992
3993   unsigned MaskByteOffset;
3994   switch (N1C->getZExtValue()) {
3995   default:
3996     return false;
3997   case 0xFF:       MaskByteOffset = 0; break;
3998   case 0xFF00:     MaskByteOffset = 1; break;
3999   case 0xFF0000:   MaskByteOffset = 2; break;
4000   case 0xFF000000: MaskByteOffset = 3; break;
4001   }
4002
4003   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4004   if (Opc == ISD::AND) {
4005     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4006       // (x >> 8) & 0xff
4007       // (x >> 8) & 0xff0000
4008       if (Opc0 != ISD::SRL)
4009         return false;
4010       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4011       if (!C || C->getZExtValue() != 8)
4012         return false;
4013     } else {
4014       // (x << 8) & 0xff00
4015       // (x << 8) & 0xff000000
4016       if (Opc0 != ISD::SHL)
4017         return false;
4018       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4019       if (!C || C->getZExtValue() != 8)
4020         return false;
4021     }
4022   } else if (Opc == ISD::SHL) {
4023     // (x & 0xff) << 8
4024     // (x & 0xff0000) << 8
4025     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4026       return false;
4027     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4028     if (!C || C->getZExtValue() != 8)
4029       return false;
4030   } else { // Opc == ISD::SRL
4031     // (x & 0xff00) >> 8
4032     // (x & 0xff000000) >> 8
4033     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4034       return false;
4035     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4036     if (!C || C->getZExtValue() != 8)
4037       return false;
4038   }
4039
4040   if (Parts[MaskByteOffset])
4041     return false;
4042
4043   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4044   return true;
4045 }
4046
4047 /// Match a 32-bit packed halfword bswap. That is
4048 /// ((x & 0x000000ff) << 8) |
4049 /// ((x & 0x0000ff00) >> 8) |
4050 /// ((x & 0x00ff0000) << 8) |
4051 /// ((x & 0xff000000) >> 8)
4052 /// => (rotl (bswap x), 16)
4053 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4054   if (!LegalOperations)
4055     return SDValue();
4056
4057   EVT VT = N->getValueType(0);
4058   if (VT != MVT::i32)
4059     return SDValue();
4060   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4061     return SDValue();
4062
4063   // Look for either
4064   // (or (or (and), (and)), (or (and), (and)))
4065   // (or (or (or (and), (and)), (and)), (and))
4066   if (N0.getOpcode() != ISD::OR)
4067     return SDValue();
4068   SDValue N00 = N0.getOperand(0);
4069   SDValue N01 = N0.getOperand(1);
4070   SDNode *Parts[4] = {};
4071
4072   if (N1.getOpcode() == ISD::OR &&
4073       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4074     // (or (or (and), (and)), (or (and), (and)))
4075     if (!isBSwapHWordElement(N00, Parts))
4076       return SDValue();
4077
4078     if (!isBSwapHWordElement(N01, Parts))
4079       return SDValue();
4080     SDValue N10 = N1.getOperand(0);
4081     if (!isBSwapHWordElement(N10, Parts))
4082       return SDValue();
4083     SDValue N11 = N1.getOperand(1);
4084     if (!isBSwapHWordElement(N11, Parts))
4085       return SDValue();
4086   } else {
4087     // (or (or (or (and), (and)), (and)), (and))
4088     if (!isBSwapHWordElement(N1, Parts))
4089       return SDValue();
4090     if (!isBSwapHWordElement(N01, Parts))
4091       return SDValue();
4092     if (N00.getOpcode() != ISD::OR)
4093       return SDValue();
4094     SDValue N000 = N00.getOperand(0);
4095     if (!isBSwapHWordElement(N000, Parts))
4096       return SDValue();
4097     SDValue N001 = N00.getOperand(1);
4098     if (!isBSwapHWordElement(N001, Parts))
4099       return SDValue();
4100   }
4101
4102   // Make sure the parts are all coming from the same node.
4103   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4104     return SDValue();
4105
4106   SDLoc DL(N);
4107   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4108                               SDValue(Parts[0], 0));
4109
4110   // Result of the bswap should be rotated by 16. If it's not legal, then
4111   // do  (x << 16) | (x >> 16).
4112   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4113   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4114     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4115   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4116     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4117   return DAG.getNode(ISD::OR, DL, VT,
4118                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4119                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4120 }
4121
4122 /// This contains all DAGCombine rules which reduce two values combined by
4123 /// an Or operation to a single value \see visitANDLike().
4124 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4125   EVT VT = N1.getValueType();
4126   SDLoc DL(N);
4127
4128   // fold (or x, undef) -> -1
4129   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4130     return DAG.getAllOnesConstant(DL, VT);
4131
4132   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4133     return V;
4134
4135   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4136   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4137       // Don't increase # computations.
4138       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4139     // We can only do this xform if we know that bits from X that are set in C2
4140     // but not in C1 are already zero.  Likewise for Y.
4141     if (const ConstantSDNode *N0O1C =
4142         getAsNonOpaqueConstant(N0.getOperand(1))) {
4143       if (const ConstantSDNode *N1O1C =
4144           getAsNonOpaqueConstant(N1.getOperand(1))) {
4145         // We can only do this xform if we know that bits from X that are set in
4146         // C2 but not in C1 are already zero.  Likewise for Y.
4147         const APInt &LHSMask = N0O1C->getAPIntValue();
4148         const APInt &RHSMask = N1O1C->getAPIntValue();
4149
4150         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4151             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4152           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4153                                   N0.getOperand(0), N1.getOperand(0));
4154           return DAG.getNode(ISD::AND, DL, VT, X,
4155                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4156         }
4157       }
4158     }
4159   }
4160
4161   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4162   if (N0.getOpcode() == ISD::AND &&
4163       N1.getOpcode() == ISD::AND &&
4164       N0.getOperand(0) == N1.getOperand(0) &&
4165       // Don't increase # computations.
4166       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4167     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4168                             N0.getOperand(1), N1.getOperand(1));
4169     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4170   }
4171
4172   return SDValue();
4173 }
4174
4175 SDValue DAGCombiner::visitOR(SDNode *N) {
4176   SDValue N0 = N->getOperand(0);
4177   SDValue N1 = N->getOperand(1);
4178   EVT VT = N1.getValueType();
4179
4180   // x | x --> x
4181   if (N0 == N1)
4182     return N0;
4183
4184   // fold vector ops
4185   if (VT.isVector()) {
4186     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4187       return FoldedVOp;
4188
4189     // fold (or x, 0) -> x, vector edition
4190     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4191       return N1;
4192     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4193       return N0;
4194
4195     // fold (or x, -1) -> -1, vector edition
4196     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4197       // do not return N0, because undef node may exist in N0
4198       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4199     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4200       // do not return N1, because undef node may exist in N1
4201       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4202
4203     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4204     // Do this only if the resulting shuffle is legal.
4205     if (isa<ShuffleVectorSDNode>(N0) &&
4206         isa<ShuffleVectorSDNode>(N1) &&
4207         // Avoid folding a node with illegal type.
4208         TLI.isTypeLegal(VT)) {
4209       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4210       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4211       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4212       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4213       // Ensure both shuffles have a zero input.
4214       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4215         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4216         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4217         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4218         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4219         bool CanFold = true;
4220         int NumElts = VT.getVectorNumElements();
4221         SmallVector<int, 4> Mask(NumElts);
4222
4223         for (int i = 0; i != NumElts; ++i) {
4224           int M0 = SV0->getMaskElt(i);
4225           int M1 = SV1->getMaskElt(i);
4226
4227           // Determine if either index is pointing to a zero vector.
4228           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4229           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4230
4231           // If one element is zero and the otherside is undef, keep undef.
4232           // This also handles the case that both are undef.
4233           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4234             Mask[i] = -1;
4235             continue;
4236           }
4237
4238           // Make sure only one of the elements is zero.
4239           if (M0Zero == M1Zero) {
4240             CanFold = false;
4241             break;
4242           }
4243
4244           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4245
4246           // We have a zero and non-zero element. If the non-zero came from
4247           // SV0 make the index a LHS index. If it came from SV1, make it
4248           // a RHS index. We need to mod by NumElts because we don't care
4249           // which operand it came from in the original shuffles.
4250           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4251         }
4252
4253         if (CanFold) {
4254           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4255           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4256
4257           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4258           if (!LegalMask) {
4259             std::swap(NewLHS, NewRHS);
4260             ShuffleVectorSDNode::commuteMask(Mask);
4261             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4262           }
4263
4264           if (LegalMask)
4265             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4266         }
4267       }
4268     }
4269   }
4270
4271   // fold (or c1, c2) -> c1|c2
4272   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4273   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4274   if (N0C && N1C && !N1C->isOpaque())
4275     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4276   // canonicalize constant to RHS
4277   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4278      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4279     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4280   // fold (or x, 0) -> x
4281   if (isNullConstant(N1))
4282     return N0;
4283   // fold (or x, -1) -> -1
4284   if (isAllOnesConstant(N1))
4285     return N1;
4286
4287   if (SDValue NewSel = foldBinOpIntoSelect(N))
4288     return NewSel;
4289
4290   // fold (or x, c) -> c iff (x & ~c) == 0
4291   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4292     return N1;
4293
4294   if (SDValue Combined = visitORLike(N0, N1, N))
4295     return Combined;
4296
4297   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4298   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4299     return BSwap;
4300   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4301     return BSwap;
4302
4303   // reassociate or
4304   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4305     return ROR;
4306
4307   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4308   // iff (c1 & c2) != 0.
4309   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4310     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4311       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4312         if (SDValue COR =
4313                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4314           return DAG.getNode(
4315               ISD::AND, SDLoc(N), VT,
4316               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4317         return SDValue();
4318       }
4319     }
4320   }
4321
4322   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4323   if (N0.getOpcode() == N1.getOpcode())
4324     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4325       return Tmp;
4326
4327   // See if this is some rotate idiom.
4328   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4329     return SDValue(Rot, 0);
4330
4331   if (SDValue Load = MatchLoadCombine(N))
4332     return Load;
4333
4334   // Simplify the operands using demanded-bits information.
4335   if (SimplifyDemandedBits(SDValue(N, 0)))
4336     return SDValue(N, 0);
4337
4338   return SDValue();
4339 }
4340
4341 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4342 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4343   if (Op.getOpcode() == ISD::AND) {
4344     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4345       Mask = Op.getOperand(1);
4346       Op = Op.getOperand(0);
4347     } else {
4348       return false;
4349     }
4350   }
4351
4352   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4353     Shift = Op;
4354     return true;
4355   }
4356
4357   return false;
4358 }
4359
4360 // Return true if we can prove that, whenever Neg and Pos are both in the
4361 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4362 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4363 //
4364 //     (or (shift1 X, Neg), (shift2 X, Pos))
4365 //
4366 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4367 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4368 // to consider shift amounts with defined behavior.
4369 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4370   // If EltSize is a power of 2 then:
4371   //
4372   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4373   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4374   //
4375   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4376   // for the stronger condition:
4377   //
4378   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4379   //
4380   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4381   // we can just replace Neg with Neg' for the rest of the function.
4382   //
4383   // In other cases we check for the even stronger condition:
4384   //
4385   //     Neg == EltSize - Pos                                    [B]
4386   //
4387   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4388   // behavior if Pos == 0 (and consequently Neg == EltSize).
4389   //
4390   // We could actually use [A] whenever EltSize is a power of 2, but the
4391   // only extra cases that it would match are those uninteresting ones
4392   // where Neg and Pos are never in range at the same time.  E.g. for
4393   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4394   // as well as (sub 32, Pos), but:
4395   //
4396   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4397   //
4398   // always invokes undefined behavior for 32-bit X.
4399   //
4400   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4401   unsigned MaskLoBits = 0;
4402   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4403     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4404       if (NegC->getAPIntValue() == EltSize - 1) {
4405         Neg = Neg.getOperand(0);
4406         MaskLoBits = Log2_64(EltSize);
4407       }
4408     }
4409   }
4410
4411   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4412   if (Neg.getOpcode() != ISD::SUB)
4413     return false;
4414   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4415   if (!NegC)
4416     return false;
4417   SDValue NegOp1 = Neg.getOperand(1);
4418
4419   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4420   // Pos'.  The truncation is redundant for the purpose of the equality.
4421   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4422     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4423       if (PosC->getAPIntValue() == EltSize - 1)
4424         Pos = Pos.getOperand(0);
4425
4426   // The condition we need is now:
4427   //
4428   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4429   //
4430   // If NegOp1 == Pos then we need:
4431   //
4432   //              EltSize & Mask == NegC & Mask
4433   //
4434   // (because "x & Mask" is a truncation and distributes through subtraction).
4435   APInt Width;
4436   if (Pos == NegOp1)
4437     Width = NegC->getAPIntValue();
4438
4439   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4440   // Then the condition we want to prove becomes:
4441   //
4442   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4443   //
4444   // which, again because "x & Mask" is a truncation, becomes:
4445   //
4446   //                NegC & Mask == (EltSize - PosC) & Mask
4447   //             EltSize & Mask == (NegC + PosC) & Mask
4448   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4449     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4450       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4451     else
4452       return false;
4453   } else
4454     return false;
4455
4456   // Now we just need to check that EltSize & Mask == Width & Mask.
4457   if (MaskLoBits)
4458     // EltSize & Mask is 0 since Mask is EltSize - 1.
4459     return Width.getLoBits(MaskLoBits) == 0;
4460   return Width == EltSize;
4461 }
4462
4463 // A subroutine of MatchRotate used once we have found an OR of two opposite
4464 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4465 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4466 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4467 // Neg with outer conversions stripped away.
4468 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4469                                        SDValue Neg, SDValue InnerPos,
4470                                        SDValue InnerNeg, unsigned PosOpcode,
4471                                        unsigned NegOpcode, const SDLoc &DL) {
4472   // fold (or (shl x, (*ext y)),
4473   //          (srl x, (*ext (sub 32, y)))) ->
4474   //   (rotl x, y) or (rotr x, (sub 32, y))
4475   //
4476   // fold (or (shl x, (*ext (sub 32, y))),
4477   //          (srl x, (*ext y))) ->
4478   //   (rotr x, y) or (rotl x, (sub 32, y))
4479   EVT VT = Shifted.getValueType();
4480   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4481     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4482     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4483                        HasPos ? Pos : Neg).getNode();
4484   }
4485
4486   return nullptr;
4487 }
4488
4489 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4490 // idioms for rotate, and if the target supports rotation instructions, generate
4491 // a rot[lr].
4492 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4493   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4494   EVT VT = LHS.getValueType();
4495   if (!TLI.isTypeLegal(VT)) return nullptr;
4496
4497   // The target must have at least one rotate flavor.
4498   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4499   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4500   if (!HasROTL && !HasROTR) return nullptr;
4501
4502   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4503   SDValue LHSShift;   // The shift.
4504   SDValue LHSMask;    // AND value if any.
4505   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4506     return nullptr; // Not part of a rotate.
4507
4508   SDValue RHSShift;   // The shift.
4509   SDValue RHSMask;    // AND value if any.
4510   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4511     return nullptr; // Not part of a rotate.
4512
4513   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4514     return nullptr;   // Not shifting the same value.
4515
4516   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4517     return nullptr;   // Shifts must disagree.
4518
4519   // Canonicalize shl to left side in a shl/srl pair.
4520   if (RHSShift.getOpcode() == ISD::SHL) {
4521     std::swap(LHS, RHS);
4522     std::swap(LHSShift, RHSShift);
4523     std::swap(LHSMask, RHSMask);
4524   }
4525
4526   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4527   SDValue LHSShiftArg = LHSShift.getOperand(0);
4528   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4529   SDValue RHSShiftArg = RHSShift.getOperand(0);
4530   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4531
4532   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4533   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4534   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4535     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4536     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4537     if ((LShVal + RShVal) != EltSizeInBits)
4538       return nullptr;
4539
4540     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4541                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4542
4543     // If there is an AND of either shifted operand, apply it to the result.
4544     if (LHSMask.getNode() || RHSMask.getNode()) {
4545       SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4546
4547       if (LHSMask.getNode()) {
4548         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4549         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4550                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4551                                        DAG.getConstant(RHSBits, DL, VT)));
4552       }
4553       if (RHSMask.getNode()) {
4554         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4555         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4556                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4557                                        DAG.getConstant(LHSBits, DL, VT)));
4558       }
4559
4560       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4561     }
4562
4563     return Rot.getNode();
4564   }
4565
4566   // If there is a mask here, and we have a variable shift, we can't be sure
4567   // that we're masking out the right stuff.
4568   if (LHSMask.getNode() || RHSMask.getNode())
4569     return nullptr;
4570
4571   // If the shift amount is sign/zext/any-extended just peel it off.
4572   SDValue LExtOp0 = LHSShiftAmt;
4573   SDValue RExtOp0 = RHSShiftAmt;
4574   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4575        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4576        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4577        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4578       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4579        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4580        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4581        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4582     LExtOp0 = LHSShiftAmt.getOperand(0);
4583     RExtOp0 = RHSShiftAmt.getOperand(0);
4584   }
4585
4586   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4587                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4588   if (TryL)
4589     return TryL;
4590
4591   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4592                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4593   if (TryR)
4594     return TryR;
4595
4596   return nullptr;
4597 }
4598
4599 namespace {
4600 /// Helper struct to parse and store a memory address as base + index + offset.
4601 /// We ignore sign extensions when it is safe to do so.
4602 /// The following two expressions are not equivalent. To differentiate we need
4603 /// to store whether there was a sign extension involved in the index
4604 /// computation.
4605 ///  (load (i64 add (i64 copyfromreg %c)
4606 ///                 (i64 signextend (add (i8 load %index)
4607 ///                                      (i8 1))))
4608 /// vs
4609 ///
4610 /// (load (i64 add (i64 copyfromreg %c)
4611 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
4612 ///                                         (i32 1)))))
4613 struct BaseIndexOffset {
4614   SDValue Base;
4615   SDValue Index;
4616   int64_t Offset;
4617   bool IsIndexSignExt;
4618
4619   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4620
4621   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4622                   bool IsIndexSignExt) :
4623     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4624
4625   bool equalBaseIndex(const BaseIndexOffset &Other) {
4626     return Other.Base == Base && Other.Index == Index &&
4627       Other.IsIndexSignExt == IsIndexSignExt;
4628   }
4629
4630   /// Parses tree in Ptr for base, index, offset addresses.
4631   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4632                                int64_t PartialOffset = 0) {
4633     bool IsIndexSignExt = false;
4634
4635     // Split up a folded GlobalAddress+Offset into its component parts.
4636     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4637       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4638         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4639                                                     SDLoc(GA),
4640                                                     GA->getValueType(0),
4641                                                     /*Offset=*/PartialOffset,
4642                                                     /*isTargetGA=*/false,
4643                                                     GA->getTargetFlags()),
4644                                SDValue(),
4645                                GA->getOffset(),
4646                                IsIndexSignExt);
4647       }
4648
4649     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4650     // instruction, then it could be just the BASE or everything else we don't
4651     // know how to handle. Just use Ptr as BASE and give up.
4652     if (Ptr->getOpcode() != ISD::ADD)
4653       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4654
4655     // We know that we have at least an ADD instruction. Try to pattern match
4656     // the simple case of BASE + OFFSET.
4657     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4658       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4659       return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4660     }
4661
4662     // Inside a loop the current BASE pointer is calculated using an ADD and a
4663     // MUL instruction. In this case Ptr is the actual BASE pointer.
4664     // (i64 add (i64 %array_ptr)
4665     //          (i64 mul (i64 %induction_var)
4666     //                   (i64 %element_size)))
4667     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4668       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4669
4670     // Look at Base + Index + Offset cases.
4671     SDValue Base = Ptr->getOperand(0);
4672     SDValue IndexOffset = Ptr->getOperand(1);
4673
4674     // Skip signextends.
4675     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4676       IndexOffset = IndexOffset->getOperand(0);
4677       IsIndexSignExt = true;
4678     }
4679
4680     // Either the case of Base + Index (no offset) or something else.
4681     if (IndexOffset->getOpcode() != ISD::ADD)
4682       return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4683
4684     // Now we have the case of Base + Index + offset.
4685     SDValue Index = IndexOffset->getOperand(0);
4686     SDValue Offset = IndexOffset->getOperand(1);
4687
4688     if (!isa<ConstantSDNode>(Offset))
4689       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4690
4691     // Ignore signextends.
4692     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4693       Index = Index->getOperand(0);
4694       IsIndexSignExt = true;
4695     } else IsIndexSignExt = false;
4696
4697     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4698     return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4699   }
4700 };
4701 } // namespace
4702
4703 namespace {
4704 /// Represents known origin of an individual byte in load combine pattern. The
4705 /// value of the byte is either constant zero or comes from memory.
4706 struct ByteProvider {
4707   // For constant zero providers Load is set to nullptr. For memory providers
4708   // Load represents the node which loads the byte from memory.
4709   // ByteOffset is the offset of the byte in the value produced by the load.
4710   LoadSDNode *Load;
4711   unsigned ByteOffset;
4712
4713   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4714
4715   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4716     return ByteProvider(Load, ByteOffset);
4717   }
4718   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4719
4720   bool isConstantZero() const { return !Load; }
4721   bool isMemory() const { return Load; }
4722
4723   bool operator==(const ByteProvider &Other) const {
4724     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4725   }
4726
4727 private:
4728   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4729       : Load(Load), ByteOffset(ByteOffset) {}
4730 };
4731
4732 /// Recursively traverses the expression calculating the origin of the requested
4733 /// byte of the given value. Returns None if the provider can't be calculated.
4734 ///
4735 /// For all the values except the root of the expression verifies that the value
4736 /// has exactly one use and if it's not true return None. This way if the origin
4737 /// of the byte is returned it's guaranteed that the values which contribute to
4738 /// the byte are not used outside of this expression.
4739 ///
4740 /// Because the parts of the expression are not allowed to have more than one
4741 /// use this function iterates over trees, not DAGs. So it never visits the same
4742 /// node more than once.
4743 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4744                                                    unsigned Depth,
4745                                                    bool Root = false) {
4746   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4747   if (Depth == 10)
4748     return None;
4749
4750   if (!Root && !Op.hasOneUse())
4751     return None;
4752
4753   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4754   unsigned BitWidth = Op.getValueSizeInBits();
4755   if (BitWidth % 8 != 0)
4756     return None;
4757   unsigned ByteWidth = BitWidth / 8;
4758   assert(Index < ByteWidth && "invalid index requested");
4759   (void) ByteWidth;
4760
4761   switch (Op.getOpcode()) {
4762   case ISD::OR: {
4763     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4764     if (!LHS)
4765       return None;
4766     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4767     if (!RHS)
4768       return None;
4769
4770     if (LHS->isConstantZero())
4771       return RHS;
4772     if (RHS->isConstantZero())
4773       return LHS;
4774     return None;
4775   }
4776   case ISD::SHL: {
4777     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4778     if (!ShiftOp)
4779       return None;
4780
4781     uint64_t BitShift = ShiftOp->getZExtValue();
4782     if (BitShift % 8 != 0)
4783       return None;
4784     uint64_t ByteShift = BitShift / 8;
4785
4786     return Index < ByteShift
4787                ? ByteProvider::getConstantZero()
4788                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4789                                        Depth + 1);
4790   }
4791   case ISD::ANY_EXTEND:
4792   case ISD::SIGN_EXTEND:
4793   case ISD::ZERO_EXTEND: {
4794     SDValue NarrowOp = Op->getOperand(0);
4795     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4796     if (NarrowBitWidth % 8 != 0)
4797       return None;
4798     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4799
4800     if (Index >= NarrowByteWidth)
4801       return Op.getOpcode() == ISD::ZERO_EXTEND
4802                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4803                  : None;
4804     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4805   }
4806   case ISD::BSWAP:
4807     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4808                                  Depth + 1);
4809   case ISD::LOAD: {
4810     auto L = cast<LoadSDNode>(Op.getNode());
4811     if (L->isVolatile() || L->isIndexed())
4812       return None;
4813
4814     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4815     if (NarrowBitWidth % 8 != 0)
4816       return None;
4817     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4818
4819     if (Index >= NarrowByteWidth)
4820       return L->getExtensionType() == ISD::ZEXTLOAD
4821                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4822                  : None;
4823     return ByteProvider::getMemory(L, Index);
4824   }
4825   }
4826
4827   return None;
4828 }
4829 } // namespace
4830
4831 /// Match a pattern where a wide type scalar value is loaded by several narrow
4832 /// loads and combined by shifts and ors. Fold it into a single load or a load
4833 /// and a BSWAP if the targets supports it.
4834 ///
4835 /// Assuming little endian target:
4836 ///  i8 *a = ...
4837 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4838 /// =>
4839 ///  i32 val = *((i32)a)
4840 ///
4841 ///  i8 *a = ...
4842 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4843 /// =>
4844 ///  i32 val = BSWAP(*((i32)a))
4845 ///
4846 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4847 /// interact well with the worklist mechanism. When a part of the pattern is
4848 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4849 /// but the root node of the pattern which triggers the load combine is not
4850 /// necessarily a direct user of the changed node. For example, once the address
4851 /// of t28 load is reassociated load combine won't be triggered:
4852 ///             t25: i32 = add t4, Constant:i32<2>
4853 ///           t26: i64 = sign_extend t25
4854 ///        t27: i64 = add t2, t26
4855 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4856 ///     t29: i32 = zero_extend t28
4857 ///   t32: i32 = shl t29, Constant:i8<8>
4858 /// t33: i32 = or t23, t32
4859 /// As a possible fix visitLoad can check if the load can be a part of a load
4860 /// combine pattern and add corresponding OR roots to the worklist.
4861 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4862   assert(N->getOpcode() == ISD::OR &&
4863          "Can only match load combining against OR nodes");
4864
4865   // Handles simple types only
4866   EVT VT = N->getValueType(0);
4867   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4868     return SDValue();
4869   unsigned ByteWidth = VT.getSizeInBits() / 8;
4870
4871   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4872   // Before legalize we can introduce too wide illegal loads which will be later
4873   // split into legal sized loads. This enables us to combine i64 load by i8
4874   // patterns to a couple of i32 loads on 32 bit targets.
4875   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4876     return SDValue();
4877
4878   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4879     unsigned BW, unsigned i) { return i; };
4880   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4881     unsigned BW, unsigned i) { return BW - i - 1; };
4882
4883   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4884   auto MemoryByteOffset = [&] (ByteProvider P) {
4885     assert(P.isMemory() && "Must be a memory byte provider");
4886     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4887     assert(LoadBitWidth % 8 == 0 &&
4888            "can only analyze providers for individual bytes not bit");
4889     unsigned LoadByteWidth = LoadBitWidth / 8;
4890     return IsBigEndianTarget
4891             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4892             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4893   };
4894
4895   Optional<BaseIndexOffset> Base;
4896   SDValue Chain;
4897
4898   SmallSet<LoadSDNode *, 8> Loads;
4899   Optional<ByteProvider> FirstByteProvider;
4900   int64_t FirstOffset = INT64_MAX;
4901
4902   // Check if all the bytes of the OR we are looking at are loaded from the same
4903   // base address. Collect bytes offsets from Base address in ByteOffsets.
4904   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4905   for (unsigned i = 0; i < ByteWidth; i++) {
4906     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4907     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4908       return SDValue();
4909
4910     LoadSDNode *L = P->Load;
4911     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4912            "Must be enforced by calculateByteProvider");
4913     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4914
4915     // All loads must share the same chain
4916     SDValue LChain = L->getChain();
4917     if (!Chain)
4918       Chain = LChain;
4919     else if (Chain != LChain)
4920       return SDValue();
4921
4922     // Loads must share the same base address
4923     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4924     if (!Base)
4925       Base = Ptr;
4926     else if (!Base->equalBaseIndex(Ptr))
4927       return SDValue();
4928
4929     // Calculate the offset of the current byte from the base address
4930     int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4931     ByteOffsets[i] = ByteOffsetFromBase;
4932
4933     // Remember the first byte load
4934     if (ByteOffsetFromBase < FirstOffset) {
4935       FirstByteProvider = P;
4936       FirstOffset = ByteOffsetFromBase;
4937     }
4938
4939     Loads.insert(L);
4940   }
4941   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4942          "memory, so there must be at least one load which produces the value");
4943   assert(Base && "Base address of the accessed memory location must be set");
4944   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4945
4946   // Check if the bytes of the OR we are looking at match with either big or
4947   // little endian value load
4948   bool BigEndian = true, LittleEndian = true;
4949   for (unsigned i = 0; i < ByteWidth; i++) {
4950     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4951     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4952     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4953     if (!BigEndian && !LittleEndian)
4954       return SDValue();
4955   }
4956   assert((BigEndian != LittleEndian) && "should be either or");
4957   assert(FirstByteProvider && "must be set");
4958
4959   // Ensure that the first byte is loaded from zero offset of the first load.
4960   // So the combined value can be loaded from the first load address.
4961   if (MemoryByteOffset(*FirstByteProvider) != 0)
4962     return SDValue();
4963   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4964
4965   // The node we are looking at matches with the pattern, check if we can
4966   // replace it with a single load and bswap if needed.
4967
4968   // If the load needs byte swap check if the target supports it
4969   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4970
4971   // Before legalize we can introduce illegal bswaps which will be later
4972   // converted to an explicit bswap sequence. This way we end up with a single
4973   // load and byte shuffling instead of several loads and byte shuffling.
4974   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4975     return SDValue();
4976
4977   // Check that a load of the wide type is both allowed and fast on the target
4978   bool Fast = false;
4979   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4980                                         VT, FirstLoad->getAddressSpace(),
4981                                         FirstLoad->getAlignment(), &Fast);
4982   if (!Allowed || !Fast)
4983     return SDValue();
4984
4985   SDValue NewLoad =
4986       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4987                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4988
4989   // Transfer chain users from old loads to the new load.
4990   for (LoadSDNode *L : Loads)
4991     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4992
4993   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4994 }
4995
4996 SDValue DAGCombiner::visitXOR(SDNode *N) {
4997   SDValue N0 = N->getOperand(0);
4998   SDValue N1 = N->getOperand(1);
4999   EVT VT = N0.getValueType();
5000
5001   // fold vector ops
5002   if (VT.isVector()) {
5003     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5004       return FoldedVOp;
5005
5006     // fold (xor x, 0) -> x, vector edition
5007     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5008       return N1;
5009     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5010       return N0;
5011   }
5012
5013   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5014   if (N0.isUndef() && N1.isUndef())
5015     return DAG.getConstant(0, SDLoc(N), VT);
5016   // fold (xor x, undef) -> undef
5017   if (N0.isUndef())
5018     return N0;
5019   if (N1.isUndef())
5020     return N1;
5021   // fold (xor c1, c2) -> c1^c2
5022   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5023   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5024   if (N0C && N1C)
5025     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5026   // canonicalize constant to RHS
5027   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5028      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5029     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5030   // fold (xor x, 0) -> x
5031   if (isNullConstant(N1))
5032     return N0;
5033
5034   if (SDValue NewSel = foldBinOpIntoSelect(N))
5035     return NewSel;
5036
5037   // reassociate xor
5038   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5039     return RXOR;
5040
5041   // fold !(x cc y) -> (x !cc y)
5042   SDValue LHS, RHS, CC;
5043   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5044     bool isInt = LHS.getValueType().isInteger();
5045     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5046                                                isInt);
5047
5048     if (!LegalOperations ||
5049         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5050       switch (N0.getOpcode()) {
5051       default:
5052         llvm_unreachable("Unhandled SetCC Equivalent!");
5053       case ISD::SETCC:
5054         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5055       case ISD::SELECT_CC:
5056         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5057                                N0.getOperand(3), NotCC);
5058       }
5059     }
5060   }
5061
5062   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5063   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5064       N0.getNode()->hasOneUse() &&
5065       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5066     SDValue V = N0.getOperand(0);
5067     SDLoc DL(N0);
5068     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5069                     DAG.getConstant(1, DL, V.getValueType()));
5070     AddToWorklist(V.getNode());
5071     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5072   }
5073
5074   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5075   if (isOneConstant(N1) && VT == MVT::i1 &&
5076       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5077     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5078     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5079       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5080       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5081       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5082       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5083       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5084     }
5085   }
5086   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5087   if (isAllOnesConstant(N1) &&
5088       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5089     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5090     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5091       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5092       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5093       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5094       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5095       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5096     }
5097   }
5098   // fold (xor (and x, y), y) -> (and (not x), y)
5099   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5100       N0->getOperand(1) == N1) {
5101     SDValue X = N0->getOperand(0);
5102     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5103     AddToWorklist(NotX.getNode());
5104     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5105   }
5106   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5107   if (N1C && N0.getOpcode() == ISD::XOR) {
5108     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5109       SDLoc DL(N);
5110       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5111                          DAG.getConstant(N1C->getAPIntValue() ^
5112                                          N00C->getAPIntValue(), DL, VT));
5113     }
5114     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5115       SDLoc DL(N);
5116       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5117                          DAG.getConstant(N1C->getAPIntValue() ^
5118                                          N01C->getAPIntValue(), DL, VT));
5119     }
5120   }
5121
5122   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5123   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5124   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5125       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5126       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5127     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5128       if (C->getAPIntValue() == (OpSizeInBits - 1))
5129         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5130   }
5131
5132   // fold (xor x, x) -> 0
5133   if (N0 == N1)
5134     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5135
5136   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5137   // Here is a concrete example of this equivalence:
5138   // i16   x ==  14
5139   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5140   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5141   //
5142   // =>
5143   //
5144   // i16     ~1      == 0b1111111111111110
5145   // i16 rol(~1, 14) == 0b1011111111111111
5146   //
5147   // Some additional tips to help conceptualize this transform:
5148   // - Try to see the operation as placing a single zero in a value of all ones.
5149   // - There exists no value for x which would allow the result to contain zero.
5150   // - Values of x larger than the bitwidth are undefined and do not require a
5151   //   consistent result.
5152   // - Pushing the zero left requires shifting one bits in from the right.
5153   // A rotate left of ~1 is a nice way of achieving the desired result.
5154   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5155       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5156     SDLoc DL(N);
5157     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5158                        N0.getOperand(1));
5159   }
5160
5161   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5162   if (N0.getOpcode() == N1.getOpcode())
5163     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5164       return Tmp;
5165
5166   // Simplify the expression using non-local knowledge.
5167   if (SimplifyDemandedBits(SDValue(N, 0)))
5168     return SDValue(N, 0);
5169
5170   return SDValue();
5171 }
5172
5173 /// Handle transforms common to the three shifts, when the shift amount is a
5174 /// constant.
5175 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5176   SDNode *LHS = N->getOperand(0).getNode();
5177   if (!LHS->hasOneUse()) return SDValue();
5178
5179   // We want to pull some binops through shifts, so that we have (and (shift))
5180   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5181   // thing happens with address calculations, so it's important to canonicalize
5182   // it.
5183   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5184
5185   switch (LHS->getOpcode()) {
5186   default: return SDValue();
5187   case ISD::OR:
5188   case ISD::XOR:
5189     HighBitSet = false; // We can only transform sra if the high bit is clear.
5190     break;
5191   case ISD::AND:
5192     HighBitSet = true;  // We can only transform sra if the high bit is set.
5193     break;
5194   case ISD::ADD:
5195     if (N->getOpcode() != ISD::SHL)
5196       return SDValue(); // only shl(add) not sr[al](add).
5197     HighBitSet = false; // We can only transform sra if the high bit is clear.
5198     break;
5199   }
5200
5201   // We require the RHS of the binop to be a constant and not opaque as well.
5202   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5203   if (!BinOpCst) return SDValue();
5204
5205   // FIXME: disable this unless the input to the binop is a shift by a constant
5206   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5207   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5208   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5209                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5210                  BinOpLHSVal->getOpcode() == ISD::SRL;
5211   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5212                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5213
5214   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5215       !isCopyOrSelect)
5216     return SDValue();
5217
5218   if (isCopyOrSelect && N->hasOneUse())
5219     return SDValue();
5220
5221   EVT VT = N->getValueType(0);
5222
5223   // If this is a signed shift right, and the high bit is modified by the
5224   // logical operation, do not perform the transformation. The highBitSet
5225   // boolean indicates the value of the high bit of the constant which would
5226   // cause it to be modified for this operation.
5227   if (N->getOpcode() == ISD::SRA) {
5228     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5229     if (BinOpRHSSignSet != HighBitSet)
5230       return SDValue();
5231   }
5232
5233   if (!TLI.isDesirableToCommuteWithShift(LHS))
5234     return SDValue();
5235
5236   // Fold the constants, shifting the binop RHS by the shift amount.
5237   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5238                                N->getValueType(0),
5239                                LHS->getOperand(1), N->getOperand(1));
5240   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5241
5242   // Create the new shift.
5243   SDValue NewShift = DAG.getNode(N->getOpcode(),
5244                                  SDLoc(LHS->getOperand(0)),
5245                                  VT, LHS->getOperand(0), N->getOperand(1));
5246
5247   // Create the new binop.
5248   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5249 }
5250
5251 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5252   assert(N->getOpcode() == ISD::TRUNCATE);
5253   assert(N->getOperand(0).getOpcode() == ISD::AND);
5254
5255   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5256   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5257     SDValue N01 = N->getOperand(0).getOperand(1);
5258     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5259       SDLoc DL(N);
5260       EVT TruncVT = N->getValueType(0);
5261       SDValue N00 = N->getOperand(0).getOperand(0);
5262       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5263       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5264       AddToWorklist(Trunc00.getNode());
5265       AddToWorklist(Trunc01.getNode());
5266       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5267     }
5268   }
5269
5270   return SDValue();
5271 }
5272
5273 SDValue DAGCombiner::visitRotate(SDNode *N) {
5274   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5275   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5276       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5277     if (SDValue NewOp1 =
5278             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5279       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5280                          N->getOperand(0), NewOp1);
5281   }
5282   return SDValue();
5283 }
5284
5285 SDValue DAGCombiner::visitSHL(SDNode *N) {
5286   SDValue N0 = N->getOperand(0);
5287   SDValue N1 = N->getOperand(1);
5288   EVT VT = N0.getValueType();
5289   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5290
5291   // fold vector ops
5292   if (VT.isVector()) {
5293     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5294       return FoldedVOp;
5295
5296     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5297     // If setcc produces all-one true value then:
5298     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5299     if (N1CV && N1CV->isConstant()) {
5300       if (N0.getOpcode() == ISD::AND) {
5301         SDValue N00 = N0->getOperand(0);
5302         SDValue N01 = N0->getOperand(1);
5303         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5304
5305         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5306             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5307                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5308           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5309                                                      N01CV, N1CV))
5310             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5311         }
5312       }
5313     }
5314   }
5315
5316   // If the target supports masking y in (shl, y),
5317   // fold (shl x, (and y, ((1 << numbits(x)) - 1))) -> (shl x, y)
5318   if (TLI.isOperationLegal(ISD::SHL, VT) &&
5319       TLI.supportsModuloShift(ISD::SHL, VT) && N1->getOpcode() == ISD::AND) {
5320     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) {
5321       if (Mask->getZExtValue() == OpSizeInBits - 1) {
5322         return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N1->getOperand(0));
5323       }
5324     }
5325   }
5326
5327   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5328
5329   // fold (shl c1, c2) -> c1<<c2
5330   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5331   if (N0C && N1C && !N1C->isOpaque())
5332     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5333   // fold (shl 0, x) -> 0
5334   if (isNullConstant(N0))
5335     return N0;
5336   // fold (shl x, c >= size(x)) -> undef
5337   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5338     return DAG.getUNDEF(VT);
5339   // fold (shl x, 0) -> x
5340   if (N1C && N1C->isNullValue())
5341     return N0;
5342   // fold (shl undef, x) -> 0
5343   if (N0.isUndef())
5344     return DAG.getConstant(0, SDLoc(N), VT);
5345
5346   if (SDValue NewSel = foldBinOpIntoSelect(N))
5347     return NewSel;
5348
5349   // if (shl x, c) is known to be zero, return 0
5350   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5351                             APInt::getAllOnesValue(OpSizeInBits)))
5352     return DAG.getConstant(0, SDLoc(N), VT);
5353   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5354   if (N1.getOpcode() == ISD::TRUNCATE &&
5355       N1.getOperand(0).getOpcode() == ISD::AND) {
5356     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5357       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5358   }
5359
5360   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5361     return SDValue(N, 0);
5362
5363   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5364   if (N1C && N0.getOpcode() == ISD::SHL) {
5365     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5366       SDLoc DL(N);
5367       APInt c1 = N0C1->getAPIntValue();
5368       APInt c2 = N1C->getAPIntValue();
5369       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5370
5371       APInt Sum = c1 + c2;
5372       if (Sum.uge(OpSizeInBits))
5373         return DAG.getConstant(0, DL, VT);
5374
5375       return DAG.getNode(
5376           ISD::SHL, DL, VT, N0.getOperand(0),
5377           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5378     }
5379   }
5380
5381   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5382   // For this to be valid, the second form must not preserve any of the bits
5383   // that are shifted out by the inner shift in the first form.  This means
5384   // the outer shift size must be >= the number of bits added by the ext.
5385   // As a corollary, we don't care what kind of ext it is.
5386   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5387               N0.getOpcode() == ISD::ANY_EXTEND ||
5388               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5389       N0.getOperand(0).getOpcode() == ISD::SHL) {
5390     SDValue N0Op0 = N0.getOperand(0);
5391     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5392       APInt c1 = N0Op0C1->getAPIntValue();
5393       APInt c2 = N1C->getAPIntValue();
5394       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5395
5396       EVT InnerShiftVT = N0Op0.getValueType();
5397       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5398       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5399         SDLoc DL(N0);
5400         APInt Sum = c1 + c2;
5401         if (Sum.uge(OpSizeInBits))
5402           return DAG.getConstant(0, DL, VT);
5403
5404         return DAG.getNode(
5405             ISD::SHL, DL, VT,
5406             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5407             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5408       }
5409     }
5410   }
5411
5412   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5413   // Only fold this if the inner zext has no other uses to avoid increasing
5414   // the total number of instructions.
5415   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5416       N0.getOperand(0).getOpcode() == ISD::SRL) {
5417     SDValue N0Op0 = N0.getOperand(0);
5418     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5419       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5420         uint64_t c1 = N0Op0C1->getZExtValue();
5421         uint64_t c2 = N1C->getZExtValue();
5422         if (c1 == c2) {
5423           SDValue NewOp0 = N0.getOperand(0);
5424           EVT CountVT = NewOp0.getOperand(1).getValueType();
5425           SDLoc DL(N);
5426           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5427                                        NewOp0,
5428                                        DAG.getConstant(c2, DL, CountVT));
5429           AddToWorklist(NewSHL.getNode());
5430           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5431         }
5432       }
5433     }
5434   }
5435
5436   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5437   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5438   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5439       N0->getFlags().hasExact()) {
5440     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5441       uint64_t C1 = N0C1->getZExtValue();
5442       uint64_t C2 = N1C->getZExtValue();
5443       SDLoc DL(N);
5444       if (C1 <= C2)
5445         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5446                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5447       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5448                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5449     }
5450   }
5451
5452   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5453   //                               (and (srl x, (sub c1, c2), MASK)
5454   // Only fold this if the inner shift has no other uses -- if it does, folding
5455   // this will increase the total number of instructions.
5456   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5457     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5458       uint64_t c1 = N0C1->getZExtValue();
5459       if (c1 < OpSizeInBits) {
5460         uint64_t c2 = N1C->getZExtValue();
5461         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5462         SDValue Shift;
5463         if (c2 > c1) {
5464           Mask <<= c2 - c1;
5465           SDLoc DL(N);
5466           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5467                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5468         } else {
5469           Mask.lshrInPlace(c1 - c2);
5470           SDLoc DL(N);
5471           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5472                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5473         }
5474         SDLoc DL(N0);
5475         return DAG.getNode(ISD::AND, DL, VT, Shift,
5476                            DAG.getConstant(Mask, DL, VT));
5477       }
5478     }
5479   }
5480
5481   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5482   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5483       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5484     SDLoc DL(N);
5485     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5486     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5487     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5488   }
5489
5490   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5491   // Variant of version done on multiply, except mul by a power of 2 is turned
5492   // into a shift.
5493   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5494       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5495       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5496     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5497     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5498     AddToWorklist(Shl0.getNode());
5499     AddToWorklist(Shl1.getNode());
5500     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5501   }
5502
5503   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5504   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5505       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5506       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5507     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5508     if (isConstantOrConstantVector(Shl))
5509       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5510   }
5511
5512   if (N1C && !N1C->isOpaque())
5513     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5514       return NewSHL;
5515
5516   return SDValue();
5517 }
5518
5519 SDValue DAGCombiner::visitSRA(SDNode *N) {
5520   SDValue N0 = N->getOperand(0);
5521   SDValue N1 = N->getOperand(1);
5522   EVT VT = N0.getValueType();
5523   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5524
5525   // If the target supports masking y in (sra, y),
5526   // fold (sra x, (and y, ((1 << numbits(x)) - 1))) -> (sra x, y)
5527   if (TLI.isOperationLegal(ISD::SRA, VT) &&
5528       TLI.supportsModuloShift(ISD::SRA, VT) && N1->getOpcode() == ISD::AND) {
5529     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) {
5530       if (Mask->getZExtValue() == OpSizeInBits - 1) {
5531         return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, N1->getOperand(0));
5532       }
5533     }
5534   }
5535
5536   // Arithmetic shifting an all-sign-bit value is a no-op.
5537   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5538     return N0;
5539
5540   // fold vector ops
5541   if (VT.isVector())
5542     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5543       return FoldedVOp;
5544
5545   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5546
5547   // fold (sra c1, c2) -> (sra c1, c2)
5548   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5549   if (N0C && N1C && !N1C->isOpaque())
5550     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5551   // fold (sra 0, x) -> 0
5552   if (isNullConstant(N0))
5553     return N0;
5554   // fold (sra -1, x) -> -1
5555   if (isAllOnesConstant(N0))
5556     return N0;
5557   // fold (sra x, c >= size(x)) -> undef
5558   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5559     return DAG.getUNDEF(VT);
5560   // fold (sra x, 0) -> x
5561   if (N1C && N1C->isNullValue())
5562     return N0;
5563
5564   if (SDValue NewSel = foldBinOpIntoSelect(N))
5565     return NewSel;
5566
5567   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5568   // sext_inreg.
5569   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5570     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5571     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5572     if (VT.isVector())
5573       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5574                                ExtVT, VT.getVectorNumElements());
5575     if ((!LegalOperations ||
5576          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5577       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5578                          N0.getOperand(0), DAG.getValueType(ExtVT));
5579   }
5580
5581   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5582   if (N1C && N0.getOpcode() == ISD::SRA) {
5583     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5584       SDLoc DL(N);
5585       APInt c1 = N0C1->getAPIntValue();
5586       APInt c2 = N1C->getAPIntValue();
5587       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5588
5589       APInt Sum = c1 + c2;
5590       if (Sum.uge(OpSizeInBits))
5591         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5592
5593       return DAG.getNode(
5594           ISD::SRA, DL, VT, N0.getOperand(0),
5595           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5596     }
5597   }
5598
5599   // fold (sra (shl X, m), (sub result_size, n))
5600   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5601   // result_size - n != m.
5602   // If truncate is free for the target sext(shl) is likely to result in better
5603   // code.
5604   if (N0.getOpcode() == ISD::SHL && N1C) {
5605     // Get the two constanst of the shifts, CN0 = m, CN = n.
5606     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5607     if (N01C) {
5608       LLVMContext &Ctx = *DAG.getContext();
5609       // Determine what the truncate's result bitsize and type would be.
5610       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5611
5612       if (VT.isVector())
5613         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5614
5615       // Determine the residual right-shift amount.
5616       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5617
5618       // If the shift is not a no-op (in which case this should be just a sign
5619       // extend already), the truncated to type is legal, sign_extend is legal
5620       // on that type, and the truncate to that type is both legal and free,
5621       // perform the transform.
5622       if ((ShiftAmt > 0) &&
5623           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5624           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5625           TLI.isTruncateFree(VT, TruncVT)) {
5626
5627         SDLoc DL(N);
5628         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5629             getShiftAmountTy(N0.getOperand(0).getValueType()));
5630         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5631                                     N0.getOperand(0), Amt);
5632         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5633                                     Shift);
5634         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5635                            N->getValueType(0), Trunc);
5636       }
5637     }
5638   }
5639
5640   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5641   if (N1.getOpcode() == ISD::TRUNCATE &&
5642       N1.getOperand(0).getOpcode() == ISD::AND) {
5643     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5644       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5645   }
5646
5647   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5648   //      if c1 is equal to the number of bits the trunc removes
5649   if (N0.getOpcode() == ISD::TRUNCATE &&
5650       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5651        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5652       N0.getOperand(0).hasOneUse() &&
5653       N0.getOperand(0).getOperand(1).hasOneUse() &&
5654       N1C) {
5655     SDValue N0Op0 = N0.getOperand(0);
5656     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5657       unsigned LargeShiftVal = LargeShift->getZExtValue();
5658       EVT LargeVT = N0Op0.getValueType();
5659
5660       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5661         SDLoc DL(N);
5662         SDValue Amt =
5663           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5664                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5665         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5666                                   N0Op0.getOperand(0), Amt);
5667         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5668       }
5669     }
5670   }
5671
5672   // Simplify, based on bits shifted out of the LHS.
5673   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5674     return SDValue(N, 0);
5675
5676
5677   // If the sign bit is known to be zero, switch this to a SRL.
5678   if (DAG.SignBitIsZero(N0))
5679     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5680
5681   if (N1C && !N1C->isOpaque())
5682     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5683       return NewSRA;
5684
5685   return SDValue();
5686 }
5687
5688 SDValue DAGCombiner::visitSRL(SDNode *N) {
5689   SDValue N0 = N->getOperand(0);
5690   SDValue N1 = N->getOperand(1);
5691   EVT VT = N0.getValueType();
5692   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5693
5694   // If the target supports masking y in (srl, y),
5695   // fold (srl x, (and y, ((1 << numbits(x)) - 1))) -> (srl x, y)
5696   if (TLI.isOperationLegal(ISD::SRL, VT) &&
5697       TLI.supportsModuloShift(ISD::SRL, VT) && N1->getOpcode() == ISD::AND) {
5698     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) {
5699       if (Mask->getZExtValue() == OpSizeInBits - 1) {
5700         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1->getOperand(0));
5701       }
5702     }
5703   }
5704
5705   // fold vector ops
5706   if (VT.isVector())
5707     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5708       return FoldedVOp;
5709
5710   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5711
5712   // fold (srl c1, c2) -> c1 >>u c2
5713   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5714   if (N0C && N1C && !N1C->isOpaque())
5715     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5716   // fold (srl 0, x) -> 0
5717   if (isNullConstant(N0))
5718     return N0;
5719   // fold (srl x, c >= size(x)) -> undef
5720   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5721     return DAG.getUNDEF(VT);
5722   // fold (srl x, 0) -> x
5723   if (N1C && N1C->isNullValue())
5724     return N0;
5725
5726   if (SDValue NewSel = foldBinOpIntoSelect(N))
5727     return NewSel;
5728
5729   // if (srl x, c) is known to be zero, return 0
5730   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5731                                    APInt::getAllOnesValue(OpSizeInBits)))
5732     return DAG.getConstant(0, SDLoc(N), VT);
5733
5734   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5735   if (N1C && N0.getOpcode() == ISD::SRL) {
5736     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5737       SDLoc DL(N);
5738       APInt c1 = N0C1->getAPIntValue();
5739       APInt c2 = N1C->getAPIntValue();
5740       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5741
5742       APInt Sum = c1 + c2;
5743       if (Sum.uge(OpSizeInBits))
5744         return DAG.getConstant(0, DL, VT);
5745
5746       return DAG.getNode(
5747           ISD::SRL, DL, VT, N0.getOperand(0),
5748           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5749     }
5750   }
5751
5752   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5753   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5754       N0.getOperand(0).getOpcode() == ISD::SRL) {
5755     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5756       uint64_t c1 = N001C->getZExtValue();
5757       uint64_t c2 = N1C->getZExtValue();
5758       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5759       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5760       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5761       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5762       if (c1 + OpSizeInBits == InnerShiftSize) {
5763         SDLoc DL(N0);
5764         if (c1 + c2 >= InnerShiftSize)
5765           return DAG.getConstant(0, DL, VT);
5766         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5767                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5768                                        N0.getOperand(0).getOperand(0),
5769                                        DAG.getConstant(c1 + c2, DL,
5770                                                        ShiftCountVT)));
5771       }
5772     }
5773   }
5774
5775   // fold (srl (shl x, c), c) -> (and x, cst2)
5776   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5777       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5778     SDLoc DL(N);
5779     SDValue Mask =
5780         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5781     AddToWorklist(Mask.getNode());
5782     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5783   }
5784
5785   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5786   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5787     // Shifting in all undef bits?
5788     EVT SmallVT = N0.getOperand(0).getValueType();
5789     unsigned BitSize = SmallVT.getScalarSizeInBits();
5790     if (N1C->getZExtValue() >= BitSize)
5791       return DAG.getUNDEF(VT);
5792
5793     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5794       uint64_t ShiftAmt = N1C->getZExtValue();
5795       SDLoc DL0(N0);
5796       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5797                                        N0.getOperand(0),
5798                           DAG.getConstant(ShiftAmt, DL0,
5799                                           getShiftAmountTy(SmallVT)));
5800       AddToWorklist(SmallShift.getNode());
5801       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5802       SDLoc DL(N);
5803       return DAG.getNode(ISD::AND, DL, VT,
5804                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5805                          DAG.getConstant(Mask, DL, VT));
5806     }
5807   }
5808
5809   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5810   // bit, which is unmodified by sra.
5811   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5812     if (N0.getOpcode() == ISD::SRA)
5813       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5814   }
5815
5816   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5817   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5818       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5819     KnownBits Known;
5820     DAG.computeKnownBits(N0.getOperand(0), Known);
5821
5822     // If any of the input bits are KnownOne, then the input couldn't be all
5823     // zeros, thus the result of the srl will always be zero.
5824     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5825
5826     // If all of the bits input the to ctlz node are known to be zero, then
5827     // the result of the ctlz is "32" and the result of the shift is one.
5828     APInt UnknownBits = ~Known.Zero;
5829     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5830
5831     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5832     if (UnknownBits.isPowerOf2()) {
5833       // Okay, we know that only that the single bit specified by UnknownBits
5834       // could be set on input to the CTLZ node. If this bit is set, the SRL
5835       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5836       // to an SRL/XOR pair, which is likely to simplify more.
5837       unsigned ShAmt = UnknownBits.countTrailingZeros();
5838       SDValue Op = N0.getOperand(0);
5839
5840       if (ShAmt) {
5841         SDLoc DL(N0);
5842         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5843                   DAG.getConstant(ShAmt, DL,
5844                                   getShiftAmountTy(Op.getValueType())));
5845         AddToWorklist(Op.getNode());
5846       }
5847
5848       SDLoc DL(N);
5849       return DAG.getNode(ISD::XOR, DL, VT,
5850                          Op, DAG.getConstant(1, DL, VT));
5851     }
5852   }
5853
5854   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5855   if (N1.getOpcode() == ISD::TRUNCATE &&
5856       N1.getOperand(0).getOpcode() == ISD::AND) {
5857     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5858       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5859   }
5860
5861   // fold operands of srl based on knowledge that the low bits are not
5862   // demanded.
5863   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5864     return SDValue(N, 0);
5865
5866   if (N1C && !N1C->isOpaque())
5867     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5868       return NewSRL;
5869
5870   // Attempt to convert a srl of a load into a narrower zero-extending load.
5871   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5872     return NarrowLoad;
5873
5874   // Here is a common situation. We want to optimize:
5875   //
5876   //   %a = ...
5877   //   %b = and i32 %a, 2
5878   //   %c = srl i32 %b, 1
5879   //   brcond i32 %c ...
5880   //
5881   // into
5882   //
5883   //   %a = ...
5884   //   %b = and %a, 2
5885   //   %c = setcc eq %b, 0
5886   //   brcond %c ...
5887   //
5888   // However when after the source operand of SRL is optimized into AND, the SRL
5889   // itself may not be optimized further. Look for it and add the BRCOND into
5890   // the worklist.
5891   if (N->hasOneUse()) {
5892     SDNode *Use = *N->use_begin();
5893     if (Use->getOpcode() == ISD::BRCOND)
5894       AddToWorklist(Use);
5895     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5896       // Also look pass the truncate.
5897       Use = *Use->use_begin();
5898       if (Use->getOpcode() == ISD::BRCOND)
5899         AddToWorklist(Use);
5900     }
5901   }
5902
5903   return SDValue();
5904 }
5905
5906 SDValue DAGCombiner::visitABS(SDNode *N) {
5907   SDValue N0 = N->getOperand(0);
5908   EVT VT = N->getValueType(0);
5909
5910   // fold (abs c1) -> c2
5911   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5912     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5913   // fold (abs (abs x)) -> (abs x)
5914   if (N0.getOpcode() == ISD::ABS)
5915     return N0;
5916   // fold (abs x) -> x iff not-negative
5917   if (DAG.SignBitIsZero(N0))
5918     return N0;
5919   return SDValue();
5920 }
5921
5922 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5923   SDValue N0 = N->getOperand(0);
5924   EVT VT = N->getValueType(0);
5925
5926   // fold (bswap c1) -> c2
5927   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5928     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5929   // fold (bswap (bswap x)) -> x
5930   if (N0.getOpcode() == ISD::BSWAP)
5931     return N0->getOperand(0);
5932   return SDValue();
5933 }
5934
5935 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5936   SDValue N0 = N->getOperand(0);
5937   EVT VT = N->getValueType(0);
5938
5939   // fold (bitreverse c1) -> c2
5940   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5941     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5942   // fold (bitreverse (bitreverse x)) -> x
5943   if (N0.getOpcode() == ISD::BITREVERSE)
5944     return N0.getOperand(0);
5945   return SDValue();
5946 }
5947
5948 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5949   SDValue N0 = N->getOperand(0);
5950   EVT VT = N->getValueType(0);
5951
5952   // fold (ctlz c1) -> c2
5953   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5954     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5955   return SDValue();
5956 }
5957
5958 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5959   SDValue N0 = N->getOperand(0);
5960   EVT VT = N->getValueType(0);
5961
5962   // fold (ctlz_zero_undef c1) -> c2
5963   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5964     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5965   return SDValue();
5966 }
5967
5968 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5969   SDValue N0 = N->getOperand(0);
5970   EVT VT = N->getValueType(0);
5971
5972   // fold (cttz c1) -> c2
5973   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5974     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5975   return SDValue();
5976 }
5977
5978 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5979   SDValue N0 = N->getOperand(0);
5980   EVT VT = N->getValueType(0);
5981
5982   // fold (cttz_zero_undef c1) -> c2
5983   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5984     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5985   return SDValue();
5986 }
5987
5988 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5989   SDValue N0 = N->getOperand(0);
5990   EVT VT = N->getValueType(0);
5991
5992   // fold (ctpop c1) -> c2
5993   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5994     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5995   return SDValue();
5996 }
5997
5998
5999 /// \brief Generate Min/Max node
6000 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6001                                    SDValue RHS, SDValue True, SDValue False,
6002                                    ISD::CondCode CC, const TargetLowering &TLI,
6003                                    SelectionDAG &DAG) {
6004   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6005     return SDValue();
6006
6007   switch (CC) {
6008   case ISD::SETOLT:
6009   case ISD::SETOLE:
6010   case ISD::SETLT:
6011   case ISD::SETLE:
6012   case ISD::SETULT:
6013   case ISD::SETULE: {
6014     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6015     if (TLI.isOperationLegal(Opcode, VT))
6016       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6017     return SDValue();
6018   }
6019   case ISD::SETOGT:
6020   case ISD::SETOGE:
6021   case ISD::SETGT:
6022   case ISD::SETGE:
6023   case ISD::SETUGT:
6024   case ISD::SETUGE: {
6025     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6026     if (TLI.isOperationLegal(Opcode, VT))
6027       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6028     return SDValue();
6029   }
6030   default:
6031     return SDValue();
6032   }
6033 }
6034
6035 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6036   SDValue Cond = N->getOperand(0);
6037   SDValue N1 = N->getOperand(1);
6038   SDValue N2 = N->getOperand(2);
6039   EVT VT = N->getValueType(0);
6040   EVT CondVT = Cond.getValueType();
6041   SDLoc DL(N);
6042
6043   if (!VT.isInteger())
6044     return SDValue();
6045
6046   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6047   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6048   if (!C1 || !C2)
6049     return SDValue();
6050
6051   // Only do this before legalization to avoid conflicting with target-specific
6052   // transforms in the other direction (create a select from a zext/sext). There
6053   // is also a target-independent combine here in DAGCombiner in the other
6054   // direction for (select Cond, -1, 0) when the condition is not i1.
6055   if (CondVT == MVT::i1 && !LegalOperations) {
6056     if (C1->isNullValue() && C2->isOne()) {
6057       // select Cond, 0, 1 --> zext (!Cond)
6058       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6059       if (VT != MVT::i1)
6060         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6061       return NotCond;
6062     }
6063     if (C1->isNullValue() && C2->isAllOnesValue()) {
6064       // select Cond, 0, -1 --> sext (!Cond)
6065       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6066       if (VT != MVT::i1)
6067         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6068       return NotCond;
6069     }
6070     if (C1->isOne() && C2->isNullValue()) {
6071       // select Cond, 1, 0 --> zext (Cond)
6072       if (VT != MVT::i1)
6073         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6074       return Cond;
6075     }
6076     if (C1->isAllOnesValue() && C2->isNullValue()) {
6077       // select Cond, -1, 0 --> sext (Cond)
6078       if (VT != MVT::i1)
6079         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6080       return Cond;
6081     }
6082
6083     // For any constants that differ by 1, we can transform the select into an
6084     // extend and add. Use a target hook because some targets may prefer to
6085     // transform in the other direction.
6086     if (TLI.convertSelectOfConstantsToMath()) {
6087       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6088         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6089         if (VT != MVT::i1)
6090           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6091         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6092       }
6093       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6094         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6095         if (VT != MVT::i1)
6096           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6097         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6098       }
6099     }
6100
6101     return SDValue();
6102   }
6103
6104   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6105   // We can't do this reliably if integer based booleans have different contents
6106   // to floating point based booleans. This is because we can't tell whether we
6107   // have an integer-based boolean or a floating-point-based boolean unless we
6108   // can find the SETCC that produced it and inspect its operands. This is
6109   // fairly easy if C is the SETCC node, but it can potentially be
6110   // undiscoverable (or not reasonably discoverable). For example, it could be
6111   // in another basic block or it could require searching a complicated
6112   // expression.
6113   if (CondVT.isInteger() &&
6114       TLI.getBooleanContents(false, true) ==
6115           TargetLowering::ZeroOrOneBooleanContent &&
6116       TLI.getBooleanContents(false, false) ==
6117           TargetLowering::ZeroOrOneBooleanContent &&
6118       C1->isNullValue() && C2->isOne()) {
6119     SDValue NotCond =
6120         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6121     if (VT.bitsEq(CondVT))
6122       return NotCond;
6123     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6124   }
6125
6126   return SDValue();
6127 }
6128
6129 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6130   SDValue N0 = N->getOperand(0);
6131   SDValue N1 = N->getOperand(1);
6132   SDValue N2 = N->getOperand(2);
6133   EVT VT = N->getValueType(0);
6134   EVT VT0 = N0.getValueType();
6135
6136   // fold (select C, X, X) -> X
6137   if (N1 == N2)
6138     return N1;
6139   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6140     // fold (select true, X, Y) -> X
6141     // fold (select false, X, Y) -> Y
6142     return !N0C->isNullValue() ? N1 : N2;
6143   }
6144   // fold (select X, X, Y) -> (or X, Y)
6145   // fold (select X, 1, Y) -> (or C, Y)
6146   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6147     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6148
6149   if (SDValue V = foldSelectOfConstants(N))
6150     return V;
6151
6152   // fold (select C, 0, X) -> (and (not C), X)
6153   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6154     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6155     AddToWorklist(NOTNode.getNode());
6156     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6157   }
6158   // fold (select C, X, 1) -> (or (not C), X)
6159   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6160     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6161     AddToWorklist(NOTNode.getNode());
6162     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6163   }
6164   // fold (select X, Y, X) -> (and X, Y)
6165   // fold (select X, Y, 0) -> (and X, Y)
6166   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6167     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6168
6169   // If we can fold this based on the true/false value, do so.
6170   if (SimplifySelectOps(N, N1, N2))
6171     return SDValue(N, 0);  // Don't revisit N.
6172
6173   if (VT0 == MVT::i1) {
6174     // The code in this block deals with the following 2 equivalences:
6175     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6176     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6177     // The target can specify its preferred form with the
6178     // shouldNormalizeToSelectSequence() callback. However we always transform
6179     // to the right anyway if we find the inner select exists in the DAG anyway
6180     // and we always transform to the left side if we know that we can further
6181     // optimize the combination of the conditions.
6182     bool normalizeToSequence
6183       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6184     // select (and Cond0, Cond1), X, Y
6185     //   -> select Cond0, (select Cond1, X, Y), Y
6186     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6187       SDValue Cond0 = N0->getOperand(0);
6188       SDValue Cond1 = N0->getOperand(1);
6189       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6190                                         N1.getValueType(), Cond1, N1, N2);
6191       if (normalizeToSequence || !InnerSelect.use_empty())
6192         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6193                            InnerSelect, N2);
6194     }
6195     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6196     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6197       SDValue Cond0 = N0->getOperand(0);
6198       SDValue Cond1 = N0->getOperand(1);
6199       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6200                                         N1.getValueType(), Cond1, N1, N2);
6201       if (normalizeToSequence || !InnerSelect.use_empty())
6202         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6203                            InnerSelect);
6204     }
6205
6206     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6207     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6208       SDValue N1_0 = N1->getOperand(0);
6209       SDValue N1_1 = N1->getOperand(1);
6210       SDValue N1_2 = N1->getOperand(2);
6211       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6212         // Create the actual and node if we can generate good code for it.
6213         if (!normalizeToSequence) {
6214           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6215                                     N0, N1_0);
6216           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6217                              N1_1, N2);
6218         }
6219         // Otherwise see if we can optimize the "and" to a better pattern.
6220         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6221           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6222                              N1_1, N2);
6223       }
6224     }
6225     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6226     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6227       SDValue N2_0 = N2->getOperand(0);
6228       SDValue N2_1 = N2->getOperand(1);
6229       SDValue N2_2 = N2->getOperand(2);
6230       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6231         // Create the actual or node if we can generate good code for it.
6232         if (!normalizeToSequence) {
6233           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6234                                    N0, N2_0);
6235           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6236                              N1, N2_2);
6237         }
6238         // Otherwise see if we can optimize to a better pattern.
6239         if (SDValue Combined = visitORLike(N0, N2_0, N))
6240           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6241                              N1, N2_2);
6242       }
6243     }
6244   }
6245
6246   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6247   if (VT0 == MVT::i1) {
6248     if (N0->getOpcode() == ISD::XOR) {
6249       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6250         SDValue Cond0 = N0->getOperand(0);
6251         if (C->isOne())
6252           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6253                              Cond0, N2, N1);
6254       }
6255     }
6256   }
6257
6258   // fold selects based on a setcc into other things, such as min/max/abs
6259   if (N0.getOpcode() == ISD::SETCC) {
6260     // select x, y (fcmp lt x, y) -> fminnum x, y
6261     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6262     //
6263     // This is OK if we don't care about what happens if either operand is a
6264     // NaN.
6265     //
6266
6267     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6268     // no signed zeros as well as no nans.
6269     const TargetOptions &Options = DAG.getTarget().Options;
6270     if (Options.UnsafeFPMath &&
6271         VT.isFloatingPoint() && N0.hasOneUse() &&
6272         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6273       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6274
6275       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6276                                                 N0.getOperand(1), N1, N2, CC,
6277                                                 TLI, DAG))
6278         return FMinMax;
6279     }
6280
6281     if ((!LegalOperations &&
6282          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6283         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6284       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6285                          N0.getOperand(0), N0.getOperand(1),
6286                          N1, N2, N0.getOperand(2));
6287     return SimplifySelect(SDLoc(N), N0, N1, N2);
6288   }
6289
6290   return SDValue();
6291 }
6292
6293 static
6294 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6295   SDLoc DL(N);
6296   EVT LoVT, HiVT;
6297   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6298
6299   // Split the inputs.
6300   SDValue Lo, Hi, LL, LH, RL, RH;
6301   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6302   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6303
6304   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6305   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6306
6307   return std::make_pair(Lo, Hi);
6308 }
6309
6310 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6311 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6312 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6313   SDLoc DL(N);
6314   SDValue Cond = N->getOperand(0);
6315   SDValue LHS = N->getOperand(1);
6316   SDValue RHS = N->getOperand(2);
6317   EVT VT = N->getValueType(0);
6318   int NumElems = VT.getVectorNumElements();
6319   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6320          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6321          Cond.getOpcode() == ISD::BUILD_VECTOR);
6322
6323   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6324   // binary ones here.
6325   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6326     return SDValue();
6327
6328   // We're sure we have an even number of elements due to the
6329   // concat_vectors we have as arguments to vselect.
6330   // Skip BV elements until we find one that's not an UNDEF
6331   // After we find an UNDEF element, keep looping until we get to half the
6332   // length of the BV and see if all the non-undef nodes are the same.
6333   ConstantSDNode *BottomHalf = nullptr;
6334   for (int i = 0; i < NumElems / 2; ++i) {
6335     if (Cond->getOperand(i)->isUndef())
6336       continue;
6337
6338     if (BottomHalf == nullptr)
6339       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6340     else if (Cond->getOperand(i).getNode() != BottomHalf)
6341       return SDValue();
6342   }
6343
6344   // Do the same for the second half of the BuildVector
6345   ConstantSDNode *TopHalf = nullptr;
6346   for (int i = NumElems / 2; i < NumElems; ++i) {
6347     if (Cond->getOperand(i)->isUndef())
6348       continue;
6349
6350     if (TopHalf == nullptr)
6351       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6352     else if (Cond->getOperand(i).getNode() != TopHalf)
6353       return SDValue();
6354   }
6355
6356   assert(TopHalf && BottomHalf &&
6357          "One half of the selector was all UNDEFs and the other was all the "
6358          "same value. This should have been addressed before this function.");
6359   return DAG.getNode(
6360       ISD::CONCAT_VECTORS, DL, VT,
6361       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6362       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6363 }
6364
6365 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6366
6367   if (Level >= AfterLegalizeTypes)
6368     return SDValue();
6369
6370   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6371   SDValue Mask = MSC->getMask();
6372   SDValue Data  = MSC->getValue();
6373   SDLoc DL(N);
6374
6375   // If the MSCATTER data type requires splitting and the mask is provided by a
6376   // SETCC, then split both nodes and its operands before legalization. This
6377   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6378   // and enables future optimizations (e.g. min/max pattern matching on X86).
6379   if (Mask.getOpcode() != ISD::SETCC)
6380     return SDValue();
6381
6382   // Check if any splitting is required.
6383   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6384       TargetLowering::TypeSplitVector)
6385     return SDValue();
6386   SDValue MaskLo, MaskHi, Lo, Hi;
6387   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6388
6389   EVT LoVT, HiVT;
6390   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6391
6392   SDValue Chain = MSC->getChain();
6393
6394   EVT MemoryVT = MSC->getMemoryVT();
6395   unsigned Alignment = MSC->getOriginalAlignment();
6396
6397   EVT LoMemVT, HiMemVT;
6398   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6399
6400   SDValue DataLo, DataHi;
6401   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6402
6403   SDValue BasePtr = MSC->getBasePtr();
6404   SDValue IndexLo, IndexHi;
6405   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6406
6407   MachineMemOperand *MMO = DAG.getMachineFunction().
6408     getMachineMemOperand(MSC->getPointerInfo(),
6409                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6410                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6411
6412   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6413   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6414                             DL, OpsLo, MMO);
6415
6416   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6417   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6418                             DL, OpsHi, MMO);
6419
6420   AddToWorklist(Lo.getNode());
6421   AddToWorklist(Hi.getNode());
6422
6423   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6424 }
6425
6426 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6427
6428   if (Level >= AfterLegalizeTypes)
6429     return SDValue();
6430
6431   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6432   SDValue Mask = MST->getMask();
6433   SDValue Data  = MST->getValue();
6434   EVT VT = Data.getValueType();
6435   SDLoc DL(N);
6436
6437   // If the MSTORE data type requires splitting and the mask is provided by a
6438   // SETCC, then split both nodes and its operands before legalization. This
6439   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6440   // and enables future optimizations (e.g. min/max pattern matching on X86).
6441   if (Mask.getOpcode() == ISD::SETCC) {
6442
6443     // Check if any splitting is required.
6444     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6445         TargetLowering::TypeSplitVector)
6446       return SDValue();
6447
6448     SDValue MaskLo, MaskHi, Lo, Hi;
6449     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6450
6451     SDValue Chain = MST->getChain();
6452     SDValue Ptr   = MST->getBasePtr();
6453
6454     EVT MemoryVT = MST->getMemoryVT();
6455     unsigned Alignment = MST->getOriginalAlignment();
6456
6457     // if Alignment is equal to the vector size,
6458     // take the half of it for the second part
6459     unsigned SecondHalfAlignment =
6460       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6461
6462     EVT LoMemVT, HiMemVT;
6463     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6464
6465     SDValue DataLo, DataHi;
6466     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6467
6468     MachineMemOperand *MMO = DAG.getMachineFunction().
6469       getMachineMemOperand(MST->getPointerInfo(),
6470                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6471                            Alignment, MST->getAAInfo(), MST->getRanges());
6472
6473     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6474                             MST->isTruncatingStore(),
6475                             MST->isCompressingStore());
6476
6477     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6478                                      MST->isCompressingStore());
6479
6480     MMO = DAG.getMachineFunction().
6481       getMachineMemOperand(MST->getPointerInfo(),
6482                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6483                            SecondHalfAlignment, MST->getAAInfo(),
6484                            MST->getRanges());
6485
6486     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6487                             MST->isTruncatingStore(),
6488                             MST->isCompressingStore());
6489
6490     AddToWorklist(Lo.getNode());
6491     AddToWorklist(Hi.getNode());
6492
6493     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6494   }
6495   return SDValue();
6496 }
6497
6498 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6499
6500   if (Level >= AfterLegalizeTypes)
6501     return SDValue();
6502
6503   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6504   SDValue Mask = MGT->getMask();
6505   SDLoc DL(N);
6506
6507   // If the MGATHER result requires splitting and the mask is provided by a
6508   // SETCC, then split both nodes and its operands before legalization. This
6509   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6510   // and enables future optimizations (e.g. min/max pattern matching on X86).
6511
6512   if (Mask.getOpcode() != ISD::SETCC)
6513     return SDValue();
6514
6515   EVT VT = N->getValueType(0);
6516
6517   // Check if any splitting is required.
6518   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6519       TargetLowering::TypeSplitVector)
6520     return SDValue();
6521
6522   SDValue MaskLo, MaskHi, Lo, Hi;
6523   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6524
6525   SDValue Src0 = MGT->getValue();
6526   SDValue Src0Lo, Src0Hi;
6527   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6528
6529   EVT LoVT, HiVT;
6530   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6531
6532   SDValue Chain = MGT->getChain();
6533   EVT MemoryVT = MGT->getMemoryVT();
6534   unsigned Alignment = MGT->getOriginalAlignment();
6535
6536   EVT LoMemVT, HiMemVT;
6537   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6538
6539   SDValue BasePtr = MGT->getBasePtr();
6540   SDValue Index = MGT->getIndex();
6541   SDValue IndexLo, IndexHi;
6542   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6543
6544   MachineMemOperand *MMO = DAG.getMachineFunction().
6545     getMachineMemOperand(MGT->getPointerInfo(),
6546                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6547                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6548
6549   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6550   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6551                             MMO);
6552
6553   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6554   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6555                             MMO);
6556
6557   AddToWorklist(Lo.getNode());
6558   AddToWorklist(Hi.getNode());
6559
6560   // Build a factor node to remember that this load is independent of the
6561   // other one.
6562   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6563                       Hi.getValue(1));
6564
6565   // Legalized the chain result - switch anything that used the old chain to
6566   // use the new one.
6567   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6568
6569   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6570
6571   SDValue RetOps[] = { GatherRes, Chain };
6572   return DAG.getMergeValues(RetOps, DL);
6573 }
6574
6575 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6576
6577   if (Level >= AfterLegalizeTypes)
6578     return SDValue();
6579
6580   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6581   SDValue Mask = MLD->getMask();
6582   SDLoc DL(N);
6583
6584   // If the MLOAD result requires splitting and the mask is provided by a
6585   // SETCC, then split both nodes and its operands before legalization. This
6586   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6587   // and enables future optimizations (e.g. min/max pattern matching on X86).
6588
6589   if (Mask.getOpcode() == ISD::SETCC) {
6590     EVT VT = N->getValueType(0);
6591
6592     // Check if any splitting is required.
6593     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6594         TargetLowering::TypeSplitVector)
6595       return SDValue();
6596
6597     SDValue MaskLo, MaskHi, Lo, Hi;
6598     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6599
6600     SDValue Src0 = MLD->getSrc0();
6601     SDValue Src0Lo, Src0Hi;
6602     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6603
6604     EVT LoVT, HiVT;
6605     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6606
6607     SDValue Chain = MLD->getChain();
6608     SDValue Ptr   = MLD->getBasePtr();
6609     EVT MemoryVT = MLD->getMemoryVT();
6610     unsigned Alignment = MLD->getOriginalAlignment();
6611
6612     // if Alignment is equal to the vector size,
6613     // take the half of it for the second part
6614     unsigned SecondHalfAlignment =
6615       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6616          Alignment/2 : Alignment;
6617
6618     EVT LoMemVT, HiMemVT;
6619     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6620
6621     MachineMemOperand *MMO = DAG.getMachineFunction().
6622     getMachineMemOperand(MLD->getPointerInfo(),
6623                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6624                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6625
6626     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6627                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6628
6629     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6630                                      MLD->isExpandingLoad());
6631
6632     MMO = DAG.getMachineFunction().
6633     getMachineMemOperand(MLD->getPointerInfo(),
6634                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6635                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6636
6637     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6638                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6639
6640     AddToWorklist(Lo.getNode());
6641     AddToWorklist(Hi.getNode());
6642
6643     // Build a factor node to remember that this load is independent of the
6644     // other one.
6645     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6646                         Hi.getValue(1));
6647
6648     // Legalized the chain result - switch anything that used the old chain to
6649     // use the new one.
6650     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6651
6652     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6653
6654     SDValue RetOps[] = { LoadRes, Chain };
6655     return DAG.getMergeValues(RetOps, DL);
6656   }
6657   return SDValue();
6658 }
6659
6660 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6661   SDValue N0 = N->getOperand(0);
6662   SDValue N1 = N->getOperand(1);
6663   SDValue N2 = N->getOperand(2);
6664   SDLoc DL(N);
6665
6666   // fold (vselect C, X, X) -> X
6667   if (N1 == N2)
6668     return N1;
6669
6670   // Canonicalize integer abs.
6671   // vselect (setg[te] X,  0),  X, -X ->
6672   // vselect (setgt    X, -1),  X, -X ->
6673   // vselect (setl[te] X,  0), -X,  X ->
6674   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6675   if (N0.getOpcode() == ISD::SETCC) {
6676     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6677     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6678     bool isAbs = false;
6679     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6680
6681     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6682          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6683         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6684       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6685     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6686              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6687       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6688
6689     if (isAbs) {
6690       EVT VT = LHS.getValueType();
6691       SDValue Shift = DAG.getNode(
6692           ISD::SRA, DL, VT, LHS,
6693           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6694       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6695       AddToWorklist(Shift.getNode());
6696       AddToWorklist(Add.getNode());
6697       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6698     }
6699   }
6700
6701   if (SimplifySelectOps(N, N1, N2))
6702     return SDValue(N, 0);  // Don't revisit N.
6703
6704   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6705   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6706     return N1;
6707   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6708   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6709     return N2;
6710
6711   // The ConvertSelectToConcatVector function is assuming both the above
6712   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6713   // and addressed.
6714   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6715       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6716       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6717     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6718       return CV;
6719   }
6720
6721   return SDValue();
6722 }
6723
6724 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6725   SDValue N0 = N->getOperand(0);
6726   SDValue N1 = N->getOperand(1);
6727   SDValue N2 = N->getOperand(2);
6728   SDValue N3 = N->getOperand(3);
6729   SDValue N4 = N->getOperand(4);
6730   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6731
6732   // fold select_cc lhs, rhs, x, x, cc -> x
6733   if (N2 == N3)
6734     return N2;
6735
6736   // Determine if the condition we're dealing with is constant
6737   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6738                                   CC, SDLoc(N), false)) {
6739     AddToWorklist(SCC.getNode());
6740
6741     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6742       if (!SCCC->isNullValue())
6743         return N2;    // cond always true -> true val
6744       else
6745         return N3;    // cond always false -> false val
6746     } else if (SCC->isUndef()) {
6747       // When the condition is UNDEF, just return the first operand. This is
6748       // coherent the DAG creation, no setcc node is created in this case
6749       return N2;
6750     } else if (SCC.getOpcode() == ISD::SETCC) {
6751       // Fold to a simpler select_cc
6752       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6753                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6754                          SCC.getOperand(2));
6755     }
6756   }
6757
6758   // If we can fold this based on the true/false value, do so.
6759   if (SimplifySelectOps(N, N2, N3))
6760     return SDValue(N, 0);  // Don't revisit N.
6761
6762   // fold select_cc into other things, such as min/max/abs
6763   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6764 }
6765
6766 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6767   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6768                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6769                        SDLoc(N));
6770 }
6771
6772 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6773   SDValue LHS = N->getOperand(0);
6774   SDValue RHS = N->getOperand(1);
6775   SDValue Carry = N->getOperand(2);
6776   SDValue Cond = N->getOperand(3);
6777
6778   // If Carry is false, fold to a regular SETCC.
6779   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6780     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6781
6782   return SDValue();
6783 }
6784
6785 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6786 /// a build_vector of constants.
6787 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6788 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6789 /// Vector extends are not folded if operations are legal; this is to
6790 /// avoid introducing illegal build_vector dag nodes.
6791 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6792                                          SelectionDAG &DAG, bool LegalTypes,
6793                                          bool LegalOperations) {
6794   unsigned Opcode = N->getOpcode();
6795   SDValue N0 = N->getOperand(0);
6796   EVT VT = N->getValueType(0);
6797
6798   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6799          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6800          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6801          && "Expected EXTEND dag node in input!");
6802
6803   // fold (sext c1) -> c1
6804   // fold (zext c1) -> c1
6805   // fold (aext c1) -> c1
6806   if (isa<ConstantSDNode>(N0))
6807     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6808
6809   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6810   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6811   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6812   EVT SVT = VT.getScalarType();
6813   if (!(VT.isVector() &&
6814       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6815       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6816     return nullptr;
6817
6818   // We can fold this node into a build_vector.
6819   unsigned VTBits = SVT.getSizeInBits();
6820   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6821   SmallVector<SDValue, 8> Elts;
6822   unsigned NumElts = VT.getVectorNumElements();
6823   SDLoc DL(N);
6824
6825   for (unsigned i=0; i != NumElts; ++i) {
6826     SDValue Op = N0->getOperand(i);
6827     if (Op->isUndef()) {
6828       Elts.push_back(DAG.getUNDEF(SVT));
6829       continue;
6830     }
6831
6832     SDLoc DL(Op);
6833     // Get the constant value and if needed trunc it to the size of the type.
6834     // Nodes like build_vector might have constants wider than the scalar type.
6835     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6836     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6837       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6838     else
6839       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6840   }
6841
6842   return DAG.getBuildVector(VT, DL, Elts).getNode();
6843 }
6844
6845 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6846 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6847 // transformation. Returns true if extension are possible and the above
6848 // mentioned transformation is profitable.
6849 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6850                                     unsigned ExtOpc,
6851                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6852                                     const TargetLowering &TLI) {
6853   bool HasCopyToRegUses = false;
6854   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6855   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6856                             UE = N0.getNode()->use_end();
6857        UI != UE; ++UI) {
6858     SDNode *User = *UI;
6859     if (User == N)
6860       continue;
6861     if (UI.getUse().getResNo() != N0.getResNo())
6862       continue;
6863     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6864     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6865       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6866       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6867         // Sign bits will be lost after a zext.
6868         return false;
6869       bool Add = false;
6870       for (unsigned i = 0; i != 2; ++i) {
6871         SDValue UseOp = User->getOperand(i);
6872         if (UseOp == N0)
6873           continue;
6874         if (!isa<ConstantSDNode>(UseOp))
6875           return false;
6876         Add = true;
6877       }
6878       if (Add)
6879         ExtendNodes.push_back(User);
6880       continue;
6881     }
6882     // If truncates aren't free and there are users we can't
6883     // extend, it isn't worthwhile.
6884     if (!isTruncFree)
6885       return false;
6886     // Remember if this value is live-out.
6887     if (User->getOpcode() == ISD::CopyToReg)
6888       HasCopyToRegUses = true;
6889   }
6890
6891   if (HasCopyToRegUses) {
6892     bool BothLiveOut = false;
6893     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6894          UI != UE; ++UI) {
6895       SDUse &Use = UI.getUse();
6896       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6897         BothLiveOut = true;
6898         break;
6899       }
6900     }
6901     if (BothLiveOut)
6902       // Both unextended and extended values are live out. There had better be
6903       // a good reason for the transformation.
6904       return ExtendNodes.size();
6905   }
6906   return true;
6907 }
6908
6909 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6910                                   SDValue Trunc, SDValue ExtLoad,
6911                                   const SDLoc &DL, ISD::NodeType ExtType) {
6912   // Extend SetCC uses if necessary.
6913   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6914     SDNode *SetCC = SetCCs[i];
6915     SmallVector<SDValue, 4> Ops;
6916
6917     for (unsigned j = 0; j != 2; ++j) {
6918       SDValue SOp = SetCC->getOperand(j);
6919       if (SOp == Trunc)
6920         Ops.push_back(ExtLoad);
6921       else
6922         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6923     }
6924
6925     Ops.push_back(SetCC->getOperand(2));
6926     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6927   }
6928 }
6929
6930 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6931 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6932   SDValue N0 = N->getOperand(0);
6933   EVT DstVT = N->getValueType(0);
6934   EVT SrcVT = N0.getValueType();
6935
6936   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6937           N->getOpcode() == ISD::ZERO_EXTEND) &&
6938          "Unexpected node type (not an extend)!");
6939
6940   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6941   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6942   //   (v8i32 (sext (v8i16 (load x))))
6943   // into:
6944   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6945   //                          (v4i32 (sextload (x + 16)))))
6946   // Where uses of the original load, i.e.:
6947   //   (v8i16 (load x))
6948   // are replaced with:
6949   //   (v8i16 (truncate
6950   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6951   //                            (v4i32 (sextload (x + 16)))))))
6952   //
6953   // This combine is only applicable to illegal, but splittable, vectors.
6954   // All legal types, and illegal non-vector types, are handled elsewhere.
6955   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6956   //
6957   if (N0->getOpcode() != ISD::LOAD)
6958     return SDValue();
6959
6960   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6961
6962   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6963       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6964       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6965     return SDValue();
6966
6967   SmallVector<SDNode *, 4> SetCCs;
6968   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6969     return SDValue();
6970
6971   ISD::LoadExtType ExtType =
6972       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6973
6974   // Try to split the vector types to get down to legal types.
6975   EVT SplitSrcVT = SrcVT;
6976   EVT SplitDstVT = DstVT;
6977   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6978          SplitSrcVT.getVectorNumElements() > 1) {
6979     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6980     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6981   }
6982
6983   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6984     return SDValue();
6985
6986   SDLoc DL(N);
6987   const unsigned NumSplits =
6988       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6989   const unsigned Stride = SplitSrcVT.getStoreSize();
6990   SmallVector<SDValue, 4> Loads;
6991   SmallVector<SDValue, 4> Chains;
6992
6993   SDValue BasePtr = LN0->getBasePtr();
6994   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6995     const unsigned Offset = Idx * Stride;
6996     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6997
6998     SDValue SplitLoad = DAG.getExtLoad(
6999         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7000         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7001         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7002
7003     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7004                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7005
7006     Loads.push_back(SplitLoad.getValue(0));
7007     Chains.push_back(SplitLoad.getValue(1));
7008   }
7009
7010   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7011   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7012
7013   // Simplify TF.
7014   AddToWorklist(NewChain.getNode());
7015
7016   CombineTo(N, NewValue);
7017
7018   // Replace uses of the original load (before extension)
7019   // with a truncate of the concatenated sextloaded vectors.
7020   SDValue Trunc =
7021       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7022   CombineTo(N0.getNode(), Trunc, NewChain);
7023   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7024                   (ISD::NodeType)N->getOpcode());
7025   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7026 }
7027
7028 /// If we're narrowing or widening the result of a vector select and the final
7029 /// size is the same size as a setcc (compare) feeding the select, then try to
7030 /// apply the cast operation to the select's operands because matching vector
7031 /// sizes for a select condition and other operands should be more efficient.
7032 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7033   unsigned CastOpcode = Cast->getOpcode();
7034   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7035           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7036           CastOpcode == ISD::FP_ROUND) &&
7037          "Unexpected opcode for vector select narrowing/widening");
7038
7039   // We only do this transform before legal ops because the pattern may be
7040   // obfuscated by target-specific operations after legalization. Do not create
7041   // an illegal select op, however, because that may be difficult to lower.
7042   EVT VT = Cast->getValueType(0);
7043   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7044     return SDValue();
7045
7046   SDValue VSel = Cast->getOperand(0);
7047   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7048       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7049     return SDValue();
7050
7051   // Does the setcc have the same vector size as the casted select?
7052   SDValue SetCC = VSel.getOperand(0);
7053   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7054   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7055     return SDValue();
7056
7057   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7058   SDValue A = VSel.getOperand(1);
7059   SDValue B = VSel.getOperand(2);
7060   SDValue CastA, CastB;
7061   SDLoc DL(Cast);
7062   if (CastOpcode == ISD::FP_ROUND) {
7063     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7064     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7065     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7066   } else {
7067     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7068     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7069   }
7070   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7071 }
7072
7073 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7074   SDValue N0 = N->getOperand(0);
7075   EVT VT = N->getValueType(0);
7076   SDLoc DL(N);
7077
7078   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7079                                               LegalOperations))
7080     return SDValue(Res, 0);
7081
7082   // fold (sext (sext x)) -> (sext x)
7083   // fold (sext (aext x)) -> (sext x)
7084   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7085     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7086
7087   if (N0.getOpcode() == ISD::TRUNCATE) {
7088     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7089     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7090     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7091       SDNode *oye = N0.getOperand(0).getNode();
7092       if (NarrowLoad.getNode() != N0.getNode()) {
7093         CombineTo(N0.getNode(), NarrowLoad);
7094         // CombineTo deleted the truncate, if needed, but not what's under it.
7095         AddToWorklist(oye);
7096       }
7097       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7098     }
7099
7100     // See if the value being truncated is already sign extended.  If so, just
7101     // eliminate the trunc/sext pair.
7102     SDValue Op = N0.getOperand(0);
7103     unsigned OpBits   = Op.getScalarValueSizeInBits();
7104     unsigned MidBits  = N0.getScalarValueSizeInBits();
7105     unsigned DestBits = VT.getScalarSizeInBits();
7106     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7107
7108     if (OpBits == DestBits) {
7109       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7110       // bits, it is already ready.
7111       if (NumSignBits > DestBits-MidBits)
7112         return Op;
7113     } else if (OpBits < DestBits) {
7114       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7115       // bits, just sext from i32.
7116       if (NumSignBits > OpBits-MidBits)
7117         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7118     } else {
7119       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7120       // bits, just truncate to i32.
7121       if (NumSignBits > OpBits-MidBits)
7122         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7123     }
7124
7125     // fold (sext (truncate x)) -> (sextinreg x).
7126     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7127                                                  N0.getValueType())) {
7128       if (OpBits < DestBits)
7129         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7130       else if (OpBits > DestBits)
7131         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7132       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7133                          DAG.getValueType(N0.getValueType()));
7134     }
7135   }
7136
7137   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7138   // Only generate vector extloads when 1) they're legal, and 2) they are
7139   // deemed desirable by the target.
7140   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7141       ((!LegalOperations && !VT.isVector() &&
7142         !cast<LoadSDNode>(N0)->isVolatile()) ||
7143        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7144     bool DoXform = true;
7145     SmallVector<SDNode*, 4> SetCCs;
7146     if (!N0.hasOneUse())
7147       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7148     if (VT.isVector())
7149       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7150     if (DoXform) {
7151       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7152       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7153                                        LN0->getBasePtr(), N0.getValueType(),
7154                                        LN0->getMemOperand());
7155       CombineTo(N, ExtLoad);
7156       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7157                                   N0.getValueType(), ExtLoad);
7158       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7159       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7160       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7161     }
7162   }
7163
7164   // fold (sext (load x)) to multiple smaller sextloads.
7165   // Only on illegal but splittable vectors.
7166   if (SDValue ExtLoad = CombineExtLoad(N))
7167     return ExtLoad;
7168
7169   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7170   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7171   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7172       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7173     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7174     EVT MemVT = LN0->getMemoryVT();
7175     if ((!LegalOperations && !LN0->isVolatile()) ||
7176         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7177       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7178                                        LN0->getBasePtr(), MemVT,
7179                                        LN0->getMemOperand());
7180       CombineTo(N, ExtLoad);
7181       CombineTo(N0.getNode(),
7182                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7183                             N0.getValueType(), ExtLoad),
7184                 ExtLoad.getValue(1));
7185       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7186     }
7187   }
7188
7189   // fold (sext (and/or/xor (load x), cst)) ->
7190   //      (and/or/xor (sextload x), (sext cst))
7191   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7192        N0.getOpcode() == ISD::XOR) &&
7193       isa<LoadSDNode>(N0.getOperand(0)) &&
7194       N0.getOperand(1).getOpcode() == ISD::Constant &&
7195       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7196       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7197     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7198     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7199       bool DoXform = true;
7200       SmallVector<SDNode*, 4> SetCCs;
7201       if (!N0.hasOneUse())
7202         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7203                                           SetCCs, TLI);
7204       if (DoXform) {
7205         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7206                                          LN0->getChain(), LN0->getBasePtr(),
7207                                          LN0->getMemoryVT(),
7208                                          LN0->getMemOperand());
7209         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7210         Mask = Mask.sext(VT.getSizeInBits());
7211         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7212                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7213         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7214                                     SDLoc(N0.getOperand(0)),
7215                                     N0.getOperand(0).getValueType(), ExtLoad);
7216         CombineTo(N, And);
7217         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7218         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7219         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7220       }
7221     }
7222   }
7223
7224   if (N0.getOpcode() == ISD::SETCC) {
7225     SDValue N00 = N0.getOperand(0);
7226     SDValue N01 = N0.getOperand(1);
7227     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7228     EVT N00VT = N0.getOperand(0).getValueType();
7229
7230     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7231     // Only do this before legalize for now.
7232     if (VT.isVector() && !LegalOperations &&
7233         TLI.getBooleanContents(N00VT) ==
7234             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7235       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7236       // of the same size as the compared operands. Only optimize sext(setcc())
7237       // if this is the case.
7238       EVT SVT = getSetCCResultType(N00VT);
7239
7240       // We know that the # elements of the results is the same as the
7241       // # elements of the compare (and the # elements of the compare result
7242       // for that matter).  Check to see that they are the same size.  If so,
7243       // we know that the element size of the sext'd result matches the
7244       // element size of the compare operands.
7245       if (VT.getSizeInBits() == SVT.getSizeInBits())
7246         return DAG.getSetCC(DL, VT, N00, N01, CC);
7247
7248       // If the desired elements are smaller or larger than the source
7249       // elements, we can use a matching integer vector type and then
7250       // truncate/sign extend.
7251       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7252       if (SVT == MatchingVecType) {
7253         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7254         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7255       }
7256     }
7257
7258     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7259     // Here, T can be 1 or -1, depending on the type of the setcc and
7260     // getBooleanContents().
7261     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7262
7263     // To determine the "true" side of the select, we need to know the high bit
7264     // of the value returned by the setcc if it evaluates to true.
7265     // If the type of the setcc is i1, then the true case of the select is just
7266     // sext(i1 1), that is, -1.
7267     // If the type of the setcc is larger (say, i8) then the value of the high
7268     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7269     // of the appropriate width.
7270     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7271                                            : TLI.getConstTrueVal(DAG, VT, DL);
7272     SDValue Zero = DAG.getConstant(0, DL, VT);
7273     if (SDValue SCC =
7274             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7275       return SCC;
7276
7277     if (!VT.isVector()) {
7278       EVT SetCCVT = getSetCCResultType(N00VT);
7279       // Don't do this transform for i1 because there's a select transform
7280       // that would reverse it.
7281       // TODO: We should not do this transform at all without a target hook
7282       // because a sext is likely cheaper than a select?
7283       if (SetCCVT.getScalarSizeInBits() != 1 &&
7284           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7285         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7286         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7287       }
7288     }
7289   }
7290
7291   // fold (sext x) -> (zext x) if the sign bit is known zero.
7292   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7293       DAG.SignBitIsZero(N0))
7294     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7295
7296   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7297     return NewVSel;
7298
7299   return SDValue();
7300 }
7301
7302 // isTruncateOf - If N is a truncate of some other value, return true, record
7303 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7304 // This function computes KnownBits to avoid a duplicated call to
7305 // computeKnownBits in the caller.
7306 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7307                          KnownBits &Known) {
7308   if (N->getOpcode() == ISD::TRUNCATE) {
7309     Op = N->getOperand(0);
7310     DAG.computeKnownBits(Op, Known);
7311     return true;
7312   }
7313
7314   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7315       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7316     return false;
7317
7318   SDValue Op0 = N->getOperand(0);
7319   SDValue Op1 = N->getOperand(1);
7320   assert(Op0.getValueType() == Op1.getValueType());
7321
7322   if (isNullConstant(Op0))
7323     Op = Op1;
7324   else if (isNullConstant(Op1))
7325     Op = Op0;
7326   else
7327     return false;
7328
7329   DAG.computeKnownBits(Op, Known);
7330
7331   if (!(Known.Zero | 1).isAllOnesValue())
7332     return false;
7333
7334   return true;
7335 }
7336
7337 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7338   SDValue N0 = N->getOperand(0);
7339   EVT VT = N->getValueType(0);
7340
7341   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7342                                               LegalOperations))
7343     return SDValue(Res, 0);
7344
7345   // fold (zext (zext x)) -> (zext x)
7346   // fold (zext (aext x)) -> (zext x)
7347   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7348     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7349                        N0.getOperand(0));
7350
7351   // fold (zext (truncate x)) -> (zext x) or
7352   //      (zext (truncate x)) -> (truncate x)
7353   // This is valid when the truncated bits of x are already zero.
7354   // FIXME: We should extend this to work for vectors too.
7355   SDValue Op;
7356   KnownBits Known;
7357   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7358     APInt TruncatedBits =
7359       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7360       APInt(Op.getValueSizeInBits(), 0) :
7361       APInt::getBitsSet(Op.getValueSizeInBits(),
7362                         N0.getValueSizeInBits(),
7363                         std::min(Op.getValueSizeInBits(),
7364                                  VT.getSizeInBits()));
7365     if (TruncatedBits.isSubsetOf(Known.Zero)) {
7366       if (VT.bitsGT(Op.getValueType()))
7367         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
7368       if (VT.bitsLT(Op.getValueType()))
7369         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7370
7371       return Op;
7372     }
7373   }
7374
7375   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7376   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7377   if (N0.getOpcode() == ISD::TRUNCATE) {
7378     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7379       SDNode *oye = N0.getOperand(0).getNode();
7380       if (NarrowLoad.getNode() != N0.getNode()) {
7381         CombineTo(N0.getNode(), NarrowLoad);
7382         // CombineTo deleted the truncate, if needed, but not what's under it.
7383         AddToWorklist(oye);
7384       }
7385       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7386     }
7387   }
7388
7389   // fold (zext (truncate x)) -> (and x, mask)
7390   if (N0.getOpcode() == ISD::TRUNCATE) {
7391     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7392     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7393     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7394       SDNode *oye = N0.getOperand(0).getNode();
7395       if (NarrowLoad.getNode() != N0.getNode()) {
7396         CombineTo(N0.getNode(), NarrowLoad);
7397         // CombineTo deleted the truncate, if needed, but not what's under it.
7398         AddToWorklist(oye);
7399       }
7400       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7401     }
7402
7403     EVT SrcVT = N0.getOperand(0).getValueType();
7404     EVT MinVT = N0.getValueType();
7405
7406     // Try to mask before the extension to avoid having to generate a larger mask,
7407     // possibly over several sub-vectors.
7408     if (SrcVT.bitsLT(VT)) {
7409       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7410                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7411         SDValue Op = N0.getOperand(0);
7412         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7413         AddToWorklist(Op.getNode());
7414         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7415       }
7416     }
7417
7418     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7419       SDValue Op = N0.getOperand(0);
7420       if (SrcVT.bitsLT(VT)) {
7421         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
7422         AddToWorklist(Op.getNode());
7423       } else if (SrcVT.bitsGT(VT)) {
7424         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7425         AddToWorklist(Op.getNode());
7426       }
7427       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7428     }
7429   }
7430
7431   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7432   // if either of the casts is not free.
7433   if (N0.getOpcode() == ISD::AND &&
7434       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7435       N0.getOperand(1).getOpcode() == ISD::Constant &&
7436       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7437                            N0.getValueType()) ||
7438        !TLI.isZExtFree(N0.getValueType(), VT))) {
7439     SDValue X = N0.getOperand(0).getOperand(0);
7440     if (X.getValueType().bitsLT(VT)) {
7441       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
7442     } else if (X.getValueType().bitsGT(VT)) {
7443       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7444     }
7445     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7446     Mask = Mask.zext(VT.getSizeInBits());
7447     SDLoc DL(N);
7448     return DAG.getNode(ISD::AND, DL, VT,
7449                        X, DAG.getConstant(Mask, DL, VT));
7450   }
7451
7452   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7453   // Only generate vector extloads when 1) they're legal, and 2) they are
7454   // deemed desirable by the target.
7455   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7456       ((!LegalOperations && !VT.isVector() &&
7457         !cast<LoadSDNode>(N0)->isVolatile()) ||
7458        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7459     bool DoXform = true;
7460     SmallVector<SDNode*, 4> SetCCs;
7461     if (!N0.hasOneUse())
7462       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7463     if (VT.isVector())
7464       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7465     if (DoXform) {
7466       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7467       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7468                                        LN0->getChain(),
7469                                        LN0->getBasePtr(), N0.getValueType(),
7470                                        LN0->getMemOperand());
7471
7472       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7473                                   N0.getValueType(), ExtLoad);
7474       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7475
7476       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7477                       ISD::ZERO_EXTEND);
7478       CombineTo(N, ExtLoad);
7479       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7480     }
7481   }
7482
7483   // fold (zext (load x)) to multiple smaller zextloads.
7484   // Only on illegal but splittable vectors.
7485   if (SDValue ExtLoad = CombineExtLoad(N))
7486     return ExtLoad;
7487
7488   // fold (zext (and/or/xor (load x), cst)) ->
7489   //      (and/or/xor (zextload x), (zext cst))
7490   // Unless (and (load x) cst) will match as a zextload already and has
7491   // additional users.
7492   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7493        N0.getOpcode() == ISD::XOR) &&
7494       isa<LoadSDNode>(N0.getOperand(0)) &&
7495       N0.getOperand(1).getOpcode() == ISD::Constant &&
7496       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7497       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7498     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7499     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7500       bool DoXform = true;
7501       SmallVector<SDNode*, 4> SetCCs;
7502       if (!N0.hasOneUse()) {
7503         if (N0.getOpcode() == ISD::AND) {
7504           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7505           auto NarrowLoad = false;
7506           EVT LoadResultTy = AndC->getValueType(0);
7507           EVT ExtVT, LoadedVT;
7508           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7509                                NarrowLoad))
7510             DoXform = false;
7511         }
7512         if (DoXform)
7513           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7514                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7515       }
7516       if (DoXform) {
7517         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7518                                          LN0->getChain(), LN0->getBasePtr(),
7519                                          LN0->getMemoryVT(),
7520                                          LN0->getMemOperand());
7521         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7522         Mask = Mask.zext(VT.getSizeInBits());
7523         SDLoc DL(N);
7524         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7525                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7526         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7527                                     SDLoc(N0.getOperand(0)),
7528                                     N0.getOperand(0).getValueType(), ExtLoad);
7529         CombineTo(N, And);
7530         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7531         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7532                         ISD::ZERO_EXTEND);
7533         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7534       }
7535     }
7536   }
7537
7538   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7539   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7540   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7541       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7542     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7543     EVT MemVT = LN0->getMemoryVT();
7544     if ((!LegalOperations && !LN0->isVolatile()) ||
7545         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7546       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7547                                        LN0->getChain(),
7548                                        LN0->getBasePtr(), MemVT,
7549                                        LN0->getMemOperand());
7550       CombineTo(N, ExtLoad);
7551       CombineTo(N0.getNode(),
7552                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7553                             ExtLoad),
7554                 ExtLoad.getValue(1));
7555       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7556     }
7557   }
7558
7559   if (N0.getOpcode() == ISD::SETCC) {
7560     // Only do this before legalize for now.
7561     if (!LegalOperations && VT.isVector() &&
7562         N0.getValueType().getVectorElementType() == MVT::i1) {
7563       EVT N00VT = N0.getOperand(0).getValueType();
7564       if (getSetCCResultType(N00VT) == N0.getValueType())
7565         return SDValue();
7566
7567       // We know that the # elements of the results is the same as the #
7568       // elements of the compare (and the # elements of the compare result for
7569       // that matter). Check to see that they are the same size. If so, we know
7570       // that the element size of the sext'd result matches the element size of
7571       // the compare operands.
7572       SDLoc DL(N);
7573       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7574       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7575         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7576         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7577                                      N0.getOperand(1), N0.getOperand(2));
7578         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7579       }
7580
7581       // If the desired elements are smaller or larger than the source
7582       // elements we can use a matching integer vector type and then
7583       // truncate/sign extend.
7584       EVT MatchingElementType = EVT::getIntegerVT(
7585           *DAG.getContext(), N00VT.getScalarSizeInBits());
7586       EVT MatchingVectorType = EVT::getVectorVT(
7587           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7588       SDValue VsetCC =
7589           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7590                       N0.getOperand(1), N0.getOperand(2));
7591       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7592                          VecOnes);
7593     }
7594
7595     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7596     SDLoc DL(N);
7597     if (SDValue SCC = SimplifySelectCC(
7598             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7599             DAG.getConstant(0, DL, VT),
7600             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7601       return SCC;
7602   }
7603
7604   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7605   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7606       isa<ConstantSDNode>(N0.getOperand(1)) &&
7607       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7608       N0.hasOneUse()) {
7609     SDValue ShAmt = N0.getOperand(1);
7610     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7611     if (N0.getOpcode() == ISD::SHL) {
7612       SDValue InnerZExt = N0.getOperand(0);
7613       // If the original shl may be shifting out bits, do not perform this
7614       // transformation.
7615       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7616         InnerZExt.getOperand(0).getValueSizeInBits();
7617       if (ShAmtVal > KnownZeroBits)
7618         return SDValue();
7619     }
7620
7621     SDLoc DL(N);
7622
7623     // Ensure that the shift amount is wide enough for the shifted value.
7624     if (VT.getSizeInBits() >= 256)
7625       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7626
7627     return DAG.getNode(N0.getOpcode(), DL, VT,
7628                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7629                        ShAmt);
7630   }
7631
7632   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7633     return NewVSel;
7634
7635   return SDValue();
7636 }
7637
7638 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7639   SDValue N0 = N->getOperand(0);
7640   EVT VT = N->getValueType(0);
7641
7642   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7643                                               LegalOperations))
7644     return SDValue(Res, 0);
7645
7646   // fold (aext (aext x)) -> (aext x)
7647   // fold (aext (zext x)) -> (zext x)
7648   // fold (aext (sext x)) -> (sext x)
7649   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7650       N0.getOpcode() == ISD::ZERO_EXTEND ||
7651       N0.getOpcode() == ISD::SIGN_EXTEND)
7652     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7653
7654   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7655   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7656   if (N0.getOpcode() == ISD::TRUNCATE) {
7657     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7658       SDNode *oye = N0.getOperand(0).getNode();
7659       if (NarrowLoad.getNode() != N0.getNode()) {
7660         CombineTo(N0.getNode(), NarrowLoad);
7661         // CombineTo deleted the truncate, if needed, but not what's under it.
7662         AddToWorklist(oye);
7663       }
7664       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7665     }
7666   }
7667
7668   // fold (aext (truncate x))
7669   if (N0.getOpcode() == ISD::TRUNCATE) {
7670     SDValue TruncOp = N0.getOperand(0);
7671     if (TruncOp.getValueType() == VT)
7672       return TruncOp; // x iff x size == zext size.
7673     if (TruncOp.getValueType().bitsGT(VT))
7674       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
7675     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
7676   }
7677
7678   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7679   // if the trunc is not free.
7680   if (N0.getOpcode() == ISD::AND &&
7681       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7682       N0.getOperand(1).getOpcode() == ISD::Constant &&
7683       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7684                           N0.getValueType())) {
7685     SDLoc DL(N);
7686     SDValue X = N0.getOperand(0).getOperand(0);
7687     if (X.getValueType().bitsLT(VT)) {
7688       X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
7689     } else if (X.getValueType().bitsGT(VT)) {
7690       X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
7691     }
7692     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7693     Mask = Mask.zext(VT.getSizeInBits());
7694     return DAG.getNode(ISD::AND, DL, VT,
7695                        X, DAG.getConstant(Mask, DL, VT));
7696   }
7697
7698   // fold (aext (load x)) -> (aext (truncate (extload x)))
7699   // None of the supported targets knows how to perform load and any_ext
7700   // on vectors in one instruction.  We only perform this transformation on
7701   // scalars.
7702   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7703       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7704       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7705     bool DoXform = true;
7706     SmallVector<SDNode*, 4> SetCCs;
7707     if (!N0.hasOneUse())
7708       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7709     if (DoXform) {
7710       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7711       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7712                                        LN0->getChain(),
7713                                        LN0->getBasePtr(), N0.getValueType(),
7714                                        LN0->getMemOperand());
7715       CombineTo(N, ExtLoad);
7716       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7717                                   N0.getValueType(), ExtLoad);
7718       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7719       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7720                       ISD::ANY_EXTEND);
7721       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7722     }
7723   }
7724
7725   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7726   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7727   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7728   if (N0.getOpcode() == ISD::LOAD &&
7729       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7730       N0.hasOneUse()) {
7731     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7732     ISD::LoadExtType ExtType = LN0->getExtensionType();
7733     EVT MemVT = LN0->getMemoryVT();
7734     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7735       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7736                                        VT, LN0->getChain(), LN0->getBasePtr(),
7737                                        MemVT, LN0->getMemOperand());
7738       CombineTo(N, ExtLoad);
7739       CombineTo(N0.getNode(),
7740                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7741                             N0.getValueType(), ExtLoad),
7742                 ExtLoad.getValue(1));
7743       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7744     }
7745   }
7746
7747   if (N0.getOpcode() == ISD::SETCC) {
7748     // For vectors:
7749     // aext(setcc) -> vsetcc
7750     // aext(setcc) -> truncate(vsetcc)
7751     // aext(setcc) -> aext(vsetcc)
7752     // Only do this before legalize for now.
7753     if (VT.isVector() && !LegalOperations) {
7754       EVT N0VT = N0.getOperand(0).getValueType();
7755         // We know that the # elements of the results is the same as the
7756         // # elements of the compare (and the # elements of the compare result
7757         // for that matter).  Check to see that they are the same size.  If so,
7758         // we know that the element size of the sext'd result matches the
7759         // element size of the compare operands.
7760       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7761         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7762                              N0.getOperand(1),
7763                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7764       // If the desired elements are smaller or larger than the source
7765       // elements we can use a matching integer vector type and then
7766       // truncate/any extend
7767       else {
7768         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7769         SDValue VsetCC =
7770           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7771                         N0.getOperand(1),
7772                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7773         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7774       }
7775     }
7776
7777     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7778     SDLoc DL(N);
7779     if (SDValue SCC = SimplifySelectCC(
7780             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7781             DAG.getConstant(0, DL, VT),
7782             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7783       return SCC;
7784   }
7785
7786   return SDValue();
7787 }
7788
7789 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7790   SDValue N0 = N->getOperand(0);
7791   SDValue N1 = N->getOperand(1);
7792   EVT EVT = cast<VTSDNode>(N1)->getVT();
7793
7794   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7795   if (N0.getOpcode() == ISD::AssertZext &&
7796       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7797     return N0;
7798
7799   return SDValue();
7800 }
7801
7802 /// See if the specified operand can be simplified with the knowledge that only
7803 /// the bits specified by Mask are used.  If so, return the simpler operand,
7804 /// otherwise return a null SDValue.
7805 ///
7806 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7807 /// simplify nodes with multiple uses more aggressively.)
7808 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7809   switch (V.getOpcode()) {
7810   default: break;
7811   case ISD::Constant: {
7812     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7813     assert(CV && "Const value should be ConstSDNode.");
7814     const APInt &CVal = CV->getAPIntValue();
7815     APInt NewVal = CVal & Mask;
7816     if (NewVal != CVal)
7817       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7818     break;
7819   }
7820   case ISD::OR:
7821   case ISD::XOR:
7822     // If the LHS or RHS don't contribute bits to the or, drop them.
7823     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7824       return V.getOperand(1);
7825     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7826       return V.getOperand(0);
7827     break;
7828   case ISD::SRL:
7829     // Only look at single-use SRLs.
7830     if (!V.getNode()->hasOneUse())
7831       break;
7832     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7833       // See if we can recursively simplify the LHS.
7834       unsigned Amt = RHSC->getZExtValue();
7835
7836       // Watch out for shift count overflow though.
7837       if (Amt >= Mask.getBitWidth()) break;
7838       APInt NewMask = Mask << Amt;
7839       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7840         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7841                            SimplifyLHS, V.getOperand(1));
7842     }
7843     break;
7844   case ISD::AND: {
7845     // X & -1 -> X (ignoring bits which aren't demanded).
7846     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7847     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7848       return V.getOperand(0);
7849     break;
7850   }
7851   }
7852   return SDValue();
7853 }
7854
7855 /// If the result of a wider load is shifted to right of N  bits and then
7856 /// truncated to a narrower type and where N is a multiple of number of bits of
7857 /// the narrower type, transform it to a narrower load from address + N / num of
7858 /// bits of new type. If the result is to be extended, also fold the extension
7859 /// to form a extending load.
7860 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7861   unsigned Opc = N->getOpcode();
7862
7863   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7864   SDValue N0 = N->getOperand(0);
7865   EVT VT = N->getValueType(0);
7866   EVT ExtVT = VT;
7867
7868   // This transformation isn't valid for vector loads.
7869   if (VT.isVector())
7870     return SDValue();
7871
7872   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7873   // extended to VT.
7874   if (Opc == ISD::SIGN_EXTEND_INREG) {
7875     ExtType = ISD::SEXTLOAD;
7876     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7877   } else if (Opc == ISD::SRL) {
7878     // Another special-case: SRL is basically zero-extending a narrower value.
7879     ExtType = ISD::ZEXTLOAD;
7880     N0 = SDValue(N, 0);
7881     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7882     if (!N01) return SDValue();
7883     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7884                               VT.getSizeInBits() - N01->getZExtValue());
7885   }
7886   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7887     return SDValue();
7888
7889   unsigned EVTBits = ExtVT.getSizeInBits();
7890
7891   // Do not generate loads of non-round integer types since these can
7892   // be expensive (and would be wrong if the type is not byte sized).
7893   if (!ExtVT.isRound())
7894     return SDValue();
7895
7896   unsigned ShAmt = 0;
7897   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7898     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7899       ShAmt = N01->getZExtValue();
7900       // Is the shift amount a multiple of size of VT?
7901       if ((ShAmt & (EVTBits-1)) == 0) {
7902         N0 = N0.getOperand(0);
7903         // Is the load width a multiple of size of VT?
7904         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7905           return SDValue();
7906       }
7907
7908       // At this point, we must have a load or else we can't do the transform.
7909       if (!isa<LoadSDNode>(N0)) return SDValue();
7910
7911       // Because a SRL must be assumed to *need* to zero-extend the high bits
7912       // (as opposed to anyext the high bits), we can't combine the zextload
7913       // lowering of SRL and an sextload.
7914       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7915         return SDValue();
7916
7917       // If the shift amount is larger than the input type then we're not
7918       // accessing any of the loaded bytes.  If the load was a zextload/extload
7919       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7920       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7921         return SDValue();
7922     }
7923   }
7924
7925   // If the load is shifted left (and the result isn't shifted back right),
7926   // we can fold the truncate through the shift.
7927   unsigned ShLeftAmt = 0;
7928   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7929       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7930     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7931       ShLeftAmt = N01->getZExtValue();
7932       N0 = N0.getOperand(0);
7933     }
7934   }
7935
7936   // If we haven't found a load, we can't narrow it.  Don't transform one with
7937   // multiple uses, this would require adding a new load.
7938   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7939     return SDValue();
7940
7941   // Don't change the width of a volatile load.
7942   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7943   if (LN0->isVolatile())
7944     return SDValue();
7945
7946   // Verify that we are actually reducing a load width here.
7947   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7948     return SDValue();
7949
7950   // For the transform to be legal, the load must produce only two values
7951   // (the value loaded and the chain).  Don't transform a pre-increment
7952   // load, for example, which produces an extra value.  Otherwise the
7953   // transformation is not equivalent, and the downstream logic to replace
7954   // uses gets things wrong.
7955   if (LN0->getNumValues() > 2)
7956     return SDValue();
7957
7958   // If the load that we're shrinking is an extload and we're not just
7959   // discarding the extension we can't simply shrink the load. Bail.
7960   // TODO: It would be possible to merge the extensions in some cases.
7961   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7962       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7963     return SDValue();
7964
7965   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7966     return SDValue();
7967
7968   EVT PtrType = N0.getOperand(1).getValueType();
7969
7970   if (PtrType == MVT::Untyped || PtrType.isExtended())
7971     // It's not possible to generate a constant of extended or untyped type.
7972     return SDValue();
7973
7974   // For big endian targets, we need to adjust the offset to the pointer to
7975   // load the correct bytes.
7976   if (DAG.getDataLayout().isBigEndian()) {
7977     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7978     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7979     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7980   }
7981
7982   uint64_t PtrOff = ShAmt / 8;
7983   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7984   SDLoc DL(LN0);
7985   // The original load itself didn't wrap, so an offset within it doesn't.
7986   SDNodeFlags Flags;
7987   Flags.setNoUnsignedWrap(true);
7988   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7989                                PtrType, LN0->getBasePtr(),
7990                                DAG.getConstant(PtrOff, DL, PtrType),
7991                                Flags);
7992   AddToWorklist(NewPtr.getNode());
7993
7994   SDValue Load;
7995   if (ExtType == ISD::NON_EXTLOAD)
7996     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7997                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7998                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7999   else
8000     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8001                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8002                           NewAlign, LN0->getMemOperand()->getFlags(),
8003                           LN0->getAAInfo());
8004
8005   // Replace the old load's chain with the new load's chain.
8006   WorklistRemover DeadNodes(*this);
8007   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8008
8009   // Shift the result left, if we've swallowed a left shift.
8010   SDValue Result = Load;
8011   if (ShLeftAmt != 0) {
8012     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8013     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8014       ShImmTy = VT;
8015     // If the shift amount is as large as the result size (but, presumably,
8016     // no larger than the source) then the useful bits of the result are
8017     // zero; we can't simply return the shortened shift, because the result
8018     // of that operation is undefined.
8019     SDLoc DL(N0);
8020     if (ShLeftAmt >= VT.getSizeInBits())
8021       Result = DAG.getConstant(0, DL, VT);
8022     else
8023       Result = DAG.getNode(ISD::SHL, DL, VT,
8024                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8025   }
8026
8027   // Return the new loaded value.
8028   return Result;
8029 }
8030
8031 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8032   SDValue N0 = N->getOperand(0);
8033   SDValue N1 = N->getOperand(1);
8034   EVT VT = N->getValueType(0);
8035   EVT EVT = cast<VTSDNode>(N1)->getVT();
8036   unsigned VTBits = VT.getScalarSizeInBits();
8037   unsigned EVTBits = EVT.getScalarSizeInBits();
8038
8039   if (N0.isUndef())
8040     return DAG.getUNDEF(VT);
8041
8042   // fold (sext_in_reg c1) -> c1
8043   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8044     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8045
8046   // If the input is already sign extended, just drop the extension.
8047   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8048     return N0;
8049
8050   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8051   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8052       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8053     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8054                        N0.getOperand(0), N1);
8055
8056   // fold (sext_in_reg (sext x)) -> (sext x)
8057   // fold (sext_in_reg (aext x)) -> (sext x)
8058   // if x is small enough.
8059   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8060     SDValue N00 = N0.getOperand(0);
8061     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8062         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8063       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8064   }
8065
8066   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8067   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8068        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8069        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8070       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8071     if (!LegalOperations ||
8072         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8073       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8074   }
8075
8076   // fold (sext_in_reg (zext x)) -> (sext x)
8077   // iff we are extending the source sign bit.
8078   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8079     SDValue N00 = N0.getOperand(0);
8080     if (N00.getScalarValueSizeInBits() == EVTBits &&
8081         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8082       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8083   }
8084
8085   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8086   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8087     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8088
8089   // fold operands of sext_in_reg based on knowledge that the top bits are not
8090   // demanded.
8091   if (SimplifyDemandedBits(SDValue(N, 0)))
8092     return SDValue(N, 0);
8093
8094   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8095   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8096   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8097     return NarrowLoad;
8098
8099   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8100   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8101   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8102   if (N0.getOpcode() == ISD::SRL) {
8103     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8104       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8105         // We can turn this into an SRA iff the input to the SRL is already sign
8106         // extended enough.
8107         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8108         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8109           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8110                              N0.getOperand(0), N0.getOperand(1));
8111       }
8112   }
8113
8114   // fold (sext_inreg (extload x)) -> (sextload x)
8115   if (ISD::isEXTLoad(N0.getNode()) &&
8116       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8117       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8118       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8119        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8120     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8121     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8122                                      LN0->getChain(),
8123                                      LN0->getBasePtr(), EVT,
8124                                      LN0->getMemOperand());
8125     CombineTo(N, ExtLoad);
8126     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8127     AddToWorklist(ExtLoad.getNode());
8128     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8129   }
8130   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8131   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8132       N0.hasOneUse() &&
8133       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8134       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8135        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8136     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8137     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8138                                      LN0->getChain(),
8139                                      LN0->getBasePtr(), EVT,
8140                                      LN0->getMemOperand());
8141     CombineTo(N, ExtLoad);
8142     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8143     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8144   }
8145
8146   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8147   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8148     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8149                                            N0.getOperand(1), false))
8150       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8151                          BSwap, N1);
8152   }
8153
8154   return SDValue();
8155 }
8156
8157 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8158   SDValue N0 = N->getOperand(0);
8159   EVT VT = N->getValueType(0);
8160
8161   if (N0.isUndef())
8162     return DAG.getUNDEF(VT);
8163
8164   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8165                                               LegalOperations))
8166     return SDValue(Res, 0);
8167
8168   return SDValue();
8169 }
8170
8171 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8172   SDValue N0 = N->getOperand(0);
8173   EVT VT = N->getValueType(0);
8174
8175   if (N0.isUndef())
8176     return DAG.getUNDEF(VT);
8177
8178   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8179                                               LegalOperations))
8180     return SDValue(Res, 0);
8181
8182   return SDValue();
8183 }
8184
8185 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8186   SDValue N0 = N->getOperand(0);
8187   EVT VT = N->getValueType(0);
8188   bool isLE = DAG.getDataLayout().isLittleEndian();
8189
8190   // noop truncate
8191   if (N0.getValueType() == N->getValueType(0))
8192     return N0;
8193   // fold (truncate c1) -> c1
8194   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8195     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8196   // fold (truncate (truncate x)) -> (truncate x)
8197   if (N0.getOpcode() == ISD::TRUNCATE)
8198     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8199   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8200   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8201       N0.getOpcode() == ISD::SIGN_EXTEND ||
8202       N0.getOpcode() == ISD::ANY_EXTEND) {
8203     // if the source is smaller than the dest, we still need an extend.
8204     if (N0.getOperand(0).getValueType().bitsLT(VT))
8205       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8206     // if the source is larger than the dest, than we just need the truncate.
8207     if (N0.getOperand(0).getValueType().bitsGT(VT))
8208       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8209     // if the source and dest are the same type, we can drop both the extend
8210     // and the truncate.
8211     return N0.getOperand(0);
8212   }
8213
8214   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8215   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8216     return SDValue();
8217
8218   // Fold extract-and-trunc into a narrow extract. For example:
8219   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8220   //   i32 y = TRUNCATE(i64 x)
8221   //        -- becomes --
8222   //   v16i8 b = BITCAST (v2i64 val)
8223   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8224   //
8225   // Note: We only run this optimization after type legalization (which often
8226   // creates this pattern) and before operation legalization after which
8227   // we need to be more careful about the vector instructions that we generate.
8228   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8229       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8230
8231     EVT VecTy = N0.getOperand(0).getValueType();
8232     EVT ExTy = N0.getValueType();
8233     EVT TrTy = N->getValueType(0);
8234
8235     unsigned NumElem = VecTy.getVectorNumElements();
8236     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8237
8238     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8239     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8240
8241     SDValue EltNo = N0->getOperand(1);
8242     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8243       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8244       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8245       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8246
8247       SDLoc DL(N);
8248       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8249                          DAG.getBitcast(NVT, N0.getOperand(0)),
8250                          DAG.getConstant(Index, DL, IndexTy));
8251     }
8252   }
8253
8254   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8255   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8256     EVT SrcVT = N0.getValueType();
8257     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8258         TLI.isTruncateFree(SrcVT, VT)) {
8259       SDLoc SL(N0);
8260       SDValue Cond = N0.getOperand(0);
8261       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8262       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8263       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8264     }
8265   }
8266
8267   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8268   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8269       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8270       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8271     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8272       uint64_t Amt = CAmt->getZExtValue();
8273       unsigned Size = VT.getScalarSizeInBits();
8274
8275       if (Amt < Size) {
8276         SDLoc SL(N);
8277         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8278
8279         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8280         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8281                            DAG.getConstant(Amt, SL, AmtVT));
8282       }
8283     }
8284   }
8285
8286   // Fold a series of buildvector, bitcast, and truncate if possible.
8287   // For example fold
8288   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8289   //   (2xi32 (buildvector x, y)).
8290   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8291       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8292       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8293       N0.getOperand(0).hasOneUse()) {
8294
8295     SDValue BuildVect = N0.getOperand(0);
8296     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8297     EVT TruncVecEltTy = VT.getVectorElementType();
8298
8299     // Check that the element types match.
8300     if (BuildVectEltTy == TruncVecEltTy) {
8301       // Now we only need to compute the offset of the truncated elements.
8302       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8303       unsigned TruncVecNumElts = VT.getVectorNumElements();
8304       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8305
8306       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8307              "Invalid number of elements");
8308
8309       SmallVector<SDValue, 8> Opnds;
8310       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8311         Opnds.push_back(BuildVect.getOperand(i));
8312
8313       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8314     }
8315   }
8316
8317   // See if we can simplify the input to this truncate through knowledge that
8318   // only the low bits are being used.
8319   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8320   // Currently we only perform this optimization on scalars because vectors
8321   // may have different active low bits.
8322   if (!VT.isVector()) {
8323     if (SDValue Shorter =
8324             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8325                                                      VT.getSizeInBits())))
8326       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8327   }
8328
8329   // fold (truncate (load x)) -> (smaller load x)
8330   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8331   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8332     if (SDValue Reduced = ReduceLoadWidth(N))
8333       return Reduced;
8334
8335     // Handle the case where the load remains an extending load even
8336     // after truncation.
8337     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8338       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8339       if (!LN0->isVolatile() &&
8340           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8341         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8342                                          VT, LN0->getChain(), LN0->getBasePtr(),
8343                                          LN0->getMemoryVT(),
8344                                          LN0->getMemOperand());
8345         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8346         return NewLoad;
8347       }
8348     }
8349   }
8350
8351   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8352   // where ... are all 'undef'.
8353   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8354     SmallVector<EVT, 8> VTs;
8355     SDValue V;
8356     unsigned Idx = 0;
8357     unsigned NumDefs = 0;
8358
8359     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8360       SDValue X = N0.getOperand(i);
8361       if (!X.isUndef()) {
8362         V = X;
8363         Idx = i;
8364         NumDefs++;
8365       }
8366       // Stop if more than one members are non-undef.
8367       if (NumDefs > 1)
8368         break;
8369       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8370                                      VT.getVectorElementType(),
8371                                      X.getValueType().getVectorNumElements()));
8372     }
8373
8374     if (NumDefs == 0)
8375       return DAG.getUNDEF(VT);
8376
8377     if (NumDefs == 1) {
8378       assert(V.getNode() && "The single defined operand is empty!");
8379       SmallVector<SDValue, 8> Opnds;
8380       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8381         if (i != Idx) {
8382           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8383           continue;
8384         }
8385         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8386         AddToWorklist(NV.getNode());
8387         Opnds.push_back(NV);
8388       }
8389       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8390     }
8391   }
8392
8393   // Fold truncate of a bitcast of a vector to an extract of the low vector
8394   // element.
8395   //
8396   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8397   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8398     SDValue VecSrc = N0.getOperand(0);
8399     EVT SrcVT = VecSrc.getValueType();
8400     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8401         (!LegalOperations ||
8402          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8403       SDLoc SL(N);
8404
8405       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8406       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8407                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8408     }
8409   }
8410
8411   // Simplify the operands using demanded-bits information.
8412   if (!VT.isVector() &&
8413       SimplifyDemandedBits(SDValue(N, 0)))
8414     return SDValue(N, 0);
8415
8416   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8417   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8418   // When the adde's carry is not used.
8419   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8420       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8421       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8422     SDLoc SL(N);
8423     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8424     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8425     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8426     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8427   }
8428
8429   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8430     return NewVSel;
8431
8432   return SDValue();
8433 }
8434
8435 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8436   SDValue Elt = N->getOperand(i);
8437   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8438     return Elt.getNode();
8439   return Elt.getOperand(Elt.getResNo()).getNode();
8440 }
8441
8442 /// build_pair (load, load) -> load
8443 /// if load locations are consecutive.
8444 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8445   assert(N->getOpcode() == ISD::BUILD_PAIR);
8446
8447   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8448   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8449   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8450       LD1->getAddressSpace() != LD2->getAddressSpace())
8451     return SDValue();
8452   EVT LD1VT = LD1->getValueType(0);
8453   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8454   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8455       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8456     unsigned Align = LD1->getAlignment();
8457     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8458         VT.getTypeForEVT(*DAG.getContext()));
8459
8460     if (NewAlign <= Align &&
8461         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8462       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8463                          LD1->getPointerInfo(), Align);
8464   }
8465
8466   return SDValue();
8467 }
8468
8469 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8470   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8471   // and Lo parts; on big-endian machines it doesn't.
8472   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8473 }
8474
8475 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8476                                     const TargetLowering &TLI) {
8477   // If this is not a bitcast to an FP type or if the target doesn't have
8478   // IEEE754-compliant FP logic, we're done.
8479   EVT VT = N->getValueType(0);
8480   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8481     return SDValue();
8482
8483   // TODO: Use splat values for the constant-checking below and remove this
8484   // restriction.
8485   SDValue N0 = N->getOperand(0);
8486   EVT SourceVT = N0.getValueType();
8487   if (SourceVT.isVector())
8488     return SDValue();
8489
8490   unsigned FPOpcode;
8491   APInt SignMask;
8492   switch (N0.getOpcode()) {
8493   case ISD::AND:
8494     FPOpcode = ISD::FABS;
8495     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8496     break;
8497   case ISD::XOR:
8498     FPOpcode = ISD::FNEG;
8499     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8500     break;
8501   // TODO: ISD::OR --> ISD::FNABS?
8502   default:
8503     return SDValue();
8504   }
8505
8506   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8507   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8508   SDValue LogicOp0 = N0.getOperand(0);
8509   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8510   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8511       LogicOp0.getOpcode() == ISD::BITCAST &&
8512       LogicOp0->getOperand(0).getValueType() == VT)
8513     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8514
8515   return SDValue();
8516 }
8517
8518 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8519   SDValue N0 = N->getOperand(0);
8520   EVT VT = N->getValueType(0);
8521
8522   if (N0.isUndef())
8523     return DAG.getUNDEF(VT);
8524
8525   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8526   // Only do this before legalize, since afterward the target may be depending
8527   // on the bitconvert.
8528   // First check to see if this is all constant.
8529   if (!LegalTypes &&
8530       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8531       VT.isVector()) {
8532     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8533
8534     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8535     assert(!DestEltVT.isVector() &&
8536            "Element type of vector ValueType must not be vector!");
8537     if (isSimple)
8538       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8539   }
8540
8541   // If the input is a constant, let getNode fold it.
8542   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8543     // If we can't allow illegal operations, we need to check that this is just
8544     // a fp -> int or int -> conversion and that the resulting operation will
8545     // be legal.
8546     if (!LegalOperations ||
8547         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8548          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8549         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8550          TLI.isOperationLegal(ISD::Constant, VT)))
8551       return DAG.getBitcast(VT, N0);
8552   }
8553
8554   // (conv (conv x, t1), t2) -> (conv x, t2)
8555   if (N0.getOpcode() == ISD::BITCAST)
8556     return DAG.getBitcast(VT, N0.getOperand(0));
8557
8558   // fold (conv (load x)) -> (load (conv*)x)
8559   // If the resultant load doesn't need a higher alignment than the original!
8560   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8561       // Do not change the width of a volatile load.
8562       !cast<LoadSDNode>(N0)->isVolatile() &&
8563       // Do not remove the cast if the types differ in endian layout.
8564       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8565           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8566       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8567       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8568     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8569     unsigned OrigAlign = LN0->getAlignment();
8570
8571     bool Fast = false;
8572     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8573                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8574         Fast) {
8575       SDValue Load =
8576           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8577                       LN0->getPointerInfo(), OrigAlign,
8578                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8579       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8580       return Load;
8581     }
8582   }
8583
8584   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8585     return V;
8586
8587   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8588   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8589   //
8590   // For ppc_fp128:
8591   // fold (bitcast (fneg x)) ->
8592   //     flipbit = signbit
8593   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8594   //
8595   // fold (bitcast (fabs x)) ->
8596   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8597   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8598   // This often reduces constant pool loads.
8599   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8600        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8601       N0.getNode()->hasOneUse() && VT.isInteger() &&
8602       !VT.isVector() && !N0.getValueType().isVector()) {
8603     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8604     AddToWorklist(NewConv.getNode());
8605
8606     SDLoc DL(N);
8607     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8608       assert(VT.getSizeInBits() == 128);
8609       SDValue SignBit = DAG.getConstant(
8610           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8611       SDValue FlipBit;
8612       if (N0.getOpcode() == ISD::FNEG) {
8613         FlipBit = SignBit;
8614         AddToWorklist(FlipBit.getNode());
8615       } else {
8616         assert(N0.getOpcode() == ISD::FABS);
8617         SDValue Hi =
8618             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8619                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8620                                               SDLoc(NewConv)));
8621         AddToWorklist(Hi.getNode());
8622         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8623         AddToWorklist(FlipBit.getNode());
8624       }
8625       SDValue FlipBits =
8626           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8627       AddToWorklist(FlipBits.getNode());
8628       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8629     }
8630     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8631     if (N0.getOpcode() == ISD::FNEG)
8632       return DAG.getNode(ISD::XOR, DL, VT,
8633                          NewConv, DAG.getConstant(SignBit, DL, VT));
8634     assert(N0.getOpcode() == ISD::FABS);
8635     return DAG.getNode(ISD::AND, DL, VT,
8636                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8637   }
8638
8639   // fold (bitconvert (fcopysign cst, x)) ->
8640   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8641   // Note that we don't handle (copysign x, cst) because this can always be
8642   // folded to an fneg or fabs.
8643   //
8644   // For ppc_fp128:
8645   // fold (bitcast (fcopysign cst, x)) ->
8646   //     flipbit = (and (extract_element
8647   //                     (xor (bitcast cst), (bitcast x)), 0),
8648   //                    signbit)
8649   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8650   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8651       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8652       VT.isInteger() && !VT.isVector()) {
8653     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8654     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8655     if (isTypeLegal(IntXVT)) {
8656       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8657       AddToWorklist(X.getNode());
8658
8659       // If X has a different width than the result/lhs, sext it or truncate it.
8660       unsigned VTWidth = VT.getSizeInBits();
8661       if (OrigXWidth < VTWidth) {
8662         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8663         AddToWorklist(X.getNode());
8664       } else if (OrigXWidth > VTWidth) {
8665         // To get the sign bit in the right place, we have to shift it right
8666         // before truncating.
8667         SDLoc DL(X);
8668         X = DAG.getNode(ISD::SRL, DL,
8669                         X.getValueType(), X,
8670                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8671                                         X.getValueType()));
8672         AddToWorklist(X.getNode());
8673         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8674         AddToWorklist(X.getNode());
8675       }
8676
8677       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8678         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8679         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8680         AddToWorklist(Cst.getNode());
8681         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8682         AddToWorklist(X.getNode());
8683         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8684         AddToWorklist(XorResult.getNode());
8685         SDValue XorResult64 = DAG.getNode(
8686             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8687             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8688                                   SDLoc(XorResult)));
8689         AddToWorklist(XorResult64.getNode());
8690         SDValue FlipBit =
8691             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8692                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8693         AddToWorklist(FlipBit.getNode());
8694         SDValue FlipBits =
8695             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8696         AddToWorklist(FlipBits.getNode());
8697         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8698       }
8699       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8700       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8701                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8702       AddToWorklist(X.getNode());
8703
8704       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8705       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8706                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8707       AddToWorklist(Cst.getNode());
8708
8709       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8710     }
8711   }
8712
8713   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8714   if (N0.getOpcode() == ISD::BUILD_PAIR)
8715     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8716       return CombineLD;
8717
8718   // Remove double bitcasts from shuffles - this is often a legacy of
8719   // XformToShuffleWithZero being used to combine bitmaskings (of
8720   // float vectors bitcast to integer vectors) into shuffles.
8721   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8722   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8723       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8724       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8725       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8726     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8727
8728     // If operands are a bitcast, peek through if it casts the original VT.
8729     // If operands are a constant, just bitcast back to original VT.
8730     auto PeekThroughBitcast = [&](SDValue Op) {
8731       if (Op.getOpcode() == ISD::BITCAST &&
8732           Op.getOperand(0).getValueType() == VT)
8733         return SDValue(Op.getOperand(0));
8734       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8735           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8736         return DAG.getBitcast(VT, Op);
8737       return SDValue();
8738     };
8739
8740     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8741     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8742     if (!(SV0 && SV1))
8743       return SDValue();
8744
8745     int MaskScale =
8746         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8747     SmallVector<int, 8> NewMask;
8748     for (int M : SVN->getMask())
8749       for (int i = 0; i != MaskScale; ++i)
8750         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8751
8752     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8753     if (!LegalMask) {
8754       std::swap(SV0, SV1);
8755       ShuffleVectorSDNode::commuteMask(NewMask);
8756       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8757     }
8758
8759     if (LegalMask)
8760       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8761   }
8762
8763   return SDValue();
8764 }
8765
8766 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8767   EVT VT = N->getValueType(0);
8768   return CombineConsecutiveLoads(N, VT);
8769 }
8770
8771 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8772 /// operands. DstEltVT indicates the destination element value type.
8773 SDValue DAGCombiner::
8774 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8775   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8776
8777   // If this is already the right type, we're done.
8778   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8779
8780   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8781   unsigned DstBitSize = DstEltVT.getSizeInBits();
8782
8783   // If this is a conversion of N elements of one type to N elements of another
8784   // type, convert each element.  This handles FP<->INT cases.
8785   if (SrcBitSize == DstBitSize) {
8786     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8787                               BV->getValueType(0).getVectorNumElements());
8788
8789     // Due to the FP element handling below calling this routine recursively,
8790     // we can end up with a scalar-to-vector node here.
8791     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8792       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8793                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8794
8795     SmallVector<SDValue, 8> Ops;
8796     for (SDValue Op : BV->op_values()) {
8797       // If the vector element type is not legal, the BUILD_VECTOR operands
8798       // are promoted and implicitly truncated.  Make that explicit here.
8799       if (Op.getValueType() != SrcEltVT)
8800         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8801       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8802       AddToWorklist(Ops.back().getNode());
8803     }
8804     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8805   }
8806
8807   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8808   // handle annoying details of growing/shrinking FP values, we convert them to
8809   // int first.
8810   if (SrcEltVT.isFloatingPoint()) {
8811     // Convert the input float vector to a int vector where the elements are the
8812     // same sizes.
8813     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8814     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8815     SrcEltVT = IntVT;
8816   }
8817
8818   // Now we know the input is an integer vector.  If the output is a FP type,
8819   // convert to integer first, then to FP of the right size.
8820   if (DstEltVT.isFloatingPoint()) {
8821     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8822     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8823
8824     // Next, convert to FP elements of the same size.
8825     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8826   }
8827
8828   SDLoc DL(BV);
8829
8830   // Okay, we know the src/dst types are both integers of differing types.
8831   // Handling growing first.
8832   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8833   if (SrcBitSize < DstBitSize) {
8834     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8835
8836     SmallVector<SDValue, 8> Ops;
8837     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8838          i += NumInputsPerOutput) {
8839       bool isLE = DAG.getDataLayout().isLittleEndian();
8840       APInt NewBits = APInt(DstBitSize, 0);
8841       bool EltIsUndef = true;
8842       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8843         // Shift the previously computed bits over.
8844         NewBits <<= SrcBitSize;
8845         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8846         if (Op.isUndef()) continue;
8847         EltIsUndef = false;
8848
8849         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8850                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8851       }
8852
8853       if (EltIsUndef)
8854         Ops.push_back(DAG.getUNDEF(DstEltVT));
8855       else
8856         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8857     }
8858
8859     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8860     return DAG.getBuildVector(VT, DL, Ops);
8861   }
8862
8863   // Finally, this must be the case where we are shrinking elements: each input
8864   // turns into multiple outputs.
8865   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8866   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8867                             NumOutputsPerInput*BV->getNumOperands());
8868   SmallVector<SDValue, 8> Ops;
8869
8870   for (const SDValue &Op : BV->op_values()) {
8871     if (Op.isUndef()) {
8872       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8873       continue;
8874     }
8875
8876     APInt OpVal = cast<ConstantSDNode>(Op)->
8877                   getAPIntValue().zextOrTrunc(SrcBitSize);
8878
8879     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8880       APInt ThisVal = OpVal.trunc(DstBitSize);
8881       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8882       OpVal.lshrInPlace(DstBitSize);
8883     }
8884
8885     // For big endian targets, swap the order of the pieces of each element.
8886     if (DAG.getDataLayout().isBigEndian())
8887       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8888   }
8889
8890   return DAG.getBuildVector(VT, DL, Ops);
8891 }
8892
8893 static bool isContractable(SDNode *N) {
8894   SDNodeFlags F = N->getFlags();
8895   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8896 }
8897
8898 /// Try to perform FMA combining on a given FADD node.
8899 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8900   SDValue N0 = N->getOperand(0);
8901   SDValue N1 = N->getOperand(1);
8902   EVT VT = N->getValueType(0);
8903   SDLoc SL(N);
8904
8905   const TargetOptions &Options = DAG.getTarget().Options;
8906
8907   // Floating-point multiply-add with intermediate rounding.
8908   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8909
8910   // Floating-point multiply-add without intermediate rounding.
8911   bool HasFMA =
8912       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8913       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8914
8915   // No valid opcode, do not combine.
8916   if (!HasFMAD && !HasFMA)
8917     return SDValue();
8918
8919   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8920                               Options.UnsafeFPMath || HasFMAD);
8921   // If the addition is not contractable, do not combine.
8922   if (!AllowFusionGlobally && !isContractable(N))
8923     return SDValue();
8924
8925   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8926   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8927     return SDValue();
8928
8929   // Always prefer FMAD to FMA for precision.
8930   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8931   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8932   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8933
8934   // Is the node an FMUL and contractable either due to global flags or
8935   // SDNodeFlags.
8936   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8937     if (N.getOpcode() != ISD::FMUL)
8938       return false;
8939     return AllowFusionGlobally || isContractable(N.getNode());
8940   };
8941   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8942   // prefer to fold the multiply with fewer uses.
8943   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8944     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8945       std::swap(N0, N1);
8946   }
8947
8948   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8949   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8950     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8951                        N0.getOperand(0), N0.getOperand(1), N1);
8952   }
8953
8954   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8955   // Note: Commutes FADD operands.
8956   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8957     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8958                        N1.getOperand(0), N1.getOperand(1), N0);
8959   }
8960
8961   // Look through FP_EXTEND nodes to do more combining.
8962   if (LookThroughFPExt) {
8963     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8964     if (N0.getOpcode() == ISD::FP_EXTEND) {
8965       SDValue N00 = N0.getOperand(0);
8966       if (isContractableFMUL(N00))
8967         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8968                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8969                                        N00.getOperand(0)),
8970                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8971                                        N00.getOperand(1)), N1);
8972     }
8973
8974     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8975     // Note: Commutes FADD operands.
8976     if (N1.getOpcode() == ISD::FP_EXTEND) {
8977       SDValue N10 = N1.getOperand(0);
8978       if (isContractableFMUL(N10))
8979         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8980                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8981                                        N10.getOperand(0)),
8982                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8983                                        N10.getOperand(1)), N0);
8984     }
8985   }
8986
8987   // More folding opportunities when target permits.
8988   if (Aggressive) {
8989     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8990     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8991     // are currently only supported on binary nodes.
8992     if (Options.UnsafeFPMath &&
8993         N0.getOpcode() == PreferredFusedOpcode &&
8994         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8995         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8996       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8997                          N0.getOperand(0), N0.getOperand(1),
8998                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8999                                      N0.getOperand(2).getOperand(0),
9000                                      N0.getOperand(2).getOperand(1),
9001                                      N1));
9002     }
9003
9004     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9005     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9006     // are currently only supported on binary nodes.
9007     if (Options.UnsafeFPMath &&
9008         N1->getOpcode() == PreferredFusedOpcode &&
9009         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9010         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9011       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9012                          N1.getOperand(0), N1.getOperand(1),
9013                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9014                                      N1.getOperand(2).getOperand(0),
9015                                      N1.getOperand(2).getOperand(1),
9016                                      N0));
9017     }
9018
9019     if (LookThroughFPExt) {
9020       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9021       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9022       auto FoldFAddFMAFPExtFMul = [&] (
9023           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9024         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9025                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9026                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9027                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9028                                        Z));
9029       };
9030       if (N0.getOpcode() == PreferredFusedOpcode) {
9031         SDValue N02 = N0.getOperand(2);
9032         if (N02.getOpcode() == ISD::FP_EXTEND) {
9033           SDValue N020 = N02.getOperand(0);
9034           if (isContractableFMUL(N020))
9035             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9036                                         N020.getOperand(0), N020.getOperand(1),
9037                                         N1);
9038         }
9039       }
9040
9041       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9042       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9043       // FIXME: This turns two single-precision and one double-precision
9044       // operation into two double-precision operations, which might not be
9045       // interesting for all targets, especially GPUs.
9046       auto FoldFAddFPExtFMAFMul = [&] (
9047           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9048         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9049                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9050                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9051                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9052                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9053                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9054                                        Z));
9055       };
9056       if (N0.getOpcode() == ISD::FP_EXTEND) {
9057         SDValue N00 = N0.getOperand(0);
9058         if (N00.getOpcode() == PreferredFusedOpcode) {
9059           SDValue N002 = N00.getOperand(2);
9060           if (isContractableFMUL(N002))
9061             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9062                                         N002.getOperand(0), N002.getOperand(1),
9063                                         N1);
9064         }
9065       }
9066
9067       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9068       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9069       if (N1.getOpcode() == PreferredFusedOpcode) {
9070         SDValue N12 = N1.getOperand(2);
9071         if (N12.getOpcode() == ISD::FP_EXTEND) {
9072           SDValue N120 = N12.getOperand(0);
9073           if (isContractableFMUL(N120))
9074             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9075                                         N120.getOperand(0), N120.getOperand(1),
9076                                         N0);
9077         }
9078       }
9079
9080       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9081       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9082       // FIXME: This turns two single-precision and one double-precision
9083       // operation into two double-precision operations, which might not be
9084       // interesting for all targets, especially GPUs.
9085       if (N1.getOpcode() == ISD::FP_EXTEND) {
9086         SDValue N10 = N1.getOperand(0);
9087         if (N10.getOpcode() == PreferredFusedOpcode) {
9088           SDValue N102 = N10.getOperand(2);
9089           if (isContractableFMUL(N102))
9090             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9091                                         N102.getOperand(0), N102.getOperand(1),
9092                                         N0);
9093         }
9094       }
9095     }
9096   }
9097
9098   return SDValue();
9099 }
9100
9101 /// Try to perform FMA combining on a given FSUB node.
9102 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9103   SDValue N0 = N->getOperand(0);
9104   SDValue N1 = N->getOperand(1);
9105   EVT VT = N->getValueType(0);
9106   SDLoc SL(N);
9107
9108   const TargetOptions &Options = DAG.getTarget().Options;
9109   // Floating-point multiply-add with intermediate rounding.
9110   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9111
9112   // Floating-point multiply-add without intermediate rounding.
9113   bool HasFMA =
9114       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9115       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9116
9117   // No valid opcode, do not combine.
9118   if (!HasFMAD && !HasFMA)
9119     return SDValue();
9120
9121   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9122                               Options.UnsafeFPMath || HasFMAD);
9123   // If the subtraction is not contractable, do not combine.
9124   if (!AllowFusionGlobally && !isContractable(N))
9125     return SDValue();
9126
9127   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9128   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9129     return SDValue();
9130
9131   // Always prefer FMAD to FMA for precision.
9132   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9133   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9134   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9135
9136   // Is the node an FMUL and contractable either due to global flags or
9137   // SDNodeFlags.
9138   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9139     if (N.getOpcode() != ISD::FMUL)
9140       return false;
9141     return AllowFusionGlobally || isContractable(N.getNode());
9142   };
9143
9144   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9145   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9146     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9147                        N0.getOperand(0), N0.getOperand(1),
9148                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9149   }
9150
9151   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9152   // Note: Commutes FSUB operands.
9153   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9154     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9155                        DAG.getNode(ISD::FNEG, SL, VT,
9156                                    N1.getOperand(0)),
9157                        N1.getOperand(1), N0);
9158
9159   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9160   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9161       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9162     SDValue N00 = N0.getOperand(0).getOperand(0);
9163     SDValue N01 = N0.getOperand(0).getOperand(1);
9164     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9165                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9166                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9167   }
9168
9169   // Look through FP_EXTEND nodes to do more combining.
9170   if (LookThroughFPExt) {
9171     // fold (fsub (fpext (fmul x, y)), z)
9172     //   -> (fma (fpext x), (fpext y), (fneg z))
9173     if (N0.getOpcode() == ISD::FP_EXTEND) {
9174       SDValue N00 = N0.getOperand(0);
9175       if (isContractableFMUL(N00))
9176         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9177                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9178                                        N00.getOperand(0)),
9179                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9180                                        N00.getOperand(1)),
9181                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9182     }
9183
9184     // fold (fsub x, (fpext (fmul y, z)))
9185     //   -> (fma (fneg (fpext y)), (fpext z), x)
9186     // Note: Commutes FSUB operands.
9187     if (N1.getOpcode() == ISD::FP_EXTEND) {
9188       SDValue N10 = N1.getOperand(0);
9189       if (isContractableFMUL(N10))
9190         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9191                            DAG.getNode(ISD::FNEG, SL, VT,
9192                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9193                                                    N10.getOperand(0))),
9194                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9195                                        N10.getOperand(1)),
9196                            N0);
9197     }
9198
9199     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9200     //   -> (fneg (fma (fpext x), (fpext y), z))
9201     // Note: This could be removed with appropriate canonicalization of the
9202     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9203     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9204     // from implementing the canonicalization in visitFSUB.
9205     if (N0.getOpcode() == ISD::FP_EXTEND) {
9206       SDValue N00 = N0.getOperand(0);
9207       if (N00.getOpcode() == ISD::FNEG) {
9208         SDValue N000 = N00.getOperand(0);
9209         if (isContractableFMUL(N000)) {
9210           return DAG.getNode(ISD::FNEG, SL, VT,
9211                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9212                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9213                                                      N000.getOperand(0)),
9214                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9215                                                      N000.getOperand(1)),
9216                                          N1));
9217         }
9218       }
9219     }
9220
9221     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9222     //   -> (fneg (fma (fpext x)), (fpext y), z)
9223     // Note: This could be removed with appropriate canonicalization of the
9224     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9225     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9226     // from implementing the canonicalization in visitFSUB.
9227     if (N0.getOpcode() == ISD::FNEG) {
9228       SDValue N00 = N0.getOperand(0);
9229       if (N00.getOpcode() == ISD::FP_EXTEND) {
9230         SDValue N000 = N00.getOperand(0);
9231         if (isContractableFMUL(N000)) {
9232           return DAG.getNode(ISD::FNEG, SL, VT,
9233                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9234                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9235                                                      N000.getOperand(0)),
9236                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9237                                                      N000.getOperand(1)),
9238                                          N1));
9239         }
9240       }
9241     }
9242
9243   }
9244
9245   // More folding opportunities when target permits.
9246   if (Aggressive) {
9247     // fold (fsub (fma x, y, (fmul u, v)), z)
9248     //   -> (fma x, y (fma u, v, (fneg z)))
9249     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9250     // are currently only supported on binary nodes.
9251     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9252         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9253         N0.getOperand(2)->hasOneUse()) {
9254       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9255                          N0.getOperand(0), N0.getOperand(1),
9256                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9257                                      N0.getOperand(2).getOperand(0),
9258                                      N0.getOperand(2).getOperand(1),
9259                                      DAG.getNode(ISD::FNEG, SL, VT,
9260                                                  N1)));
9261     }
9262
9263     // fold (fsub x, (fma y, z, (fmul u, v)))
9264     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9265     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9266     // are currently only supported on binary nodes.
9267     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9268         isContractableFMUL(N1.getOperand(2))) {
9269       SDValue N20 = N1.getOperand(2).getOperand(0);
9270       SDValue N21 = N1.getOperand(2).getOperand(1);
9271       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9272                          DAG.getNode(ISD::FNEG, SL, VT,
9273                                      N1.getOperand(0)),
9274                          N1.getOperand(1),
9275                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9276                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9277
9278                                      N21, N0));
9279     }
9280
9281     if (LookThroughFPExt) {
9282       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9283       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9284       if (N0.getOpcode() == PreferredFusedOpcode) {
9285         SDValue N02 = N0.getOperand(2);
9286         if (N02.getOpcode() == ISD::FP_EXTEND) {
9287           SDValue N020 = N02.getOperand(0);
9288           if (isContractableFMUL(N020))
9289             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9290                                N0.getOperand(0), N0.getOperand(1),
9291                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9292                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9293                                                        N020.getOperand(0)),
9294                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9295                                                        N020.getOperand(1)),
9296                                            DAG.getNode(ISD::FNEG, SL, VT,
9297                                                        N1)));
9298         }
9299       }
9300
9301       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9302       //   -> (fma (fpext x), (fpext y),
9303       //           (fma (fpext u), (fpext v), (fneg z)))
9304       // FIXME: This turns two single-precision and one double-precision
9305       // operation into two double-precision operations, which might not be
9306       // interesting for all targets, especially GPUs.
9307       if (N0.getOpcode() == ISD::FP_EXTEND) {
9308         SDValue N00 = N0.getOperand(0);
9309         if (N00.getOpcode() == PreferredFusedOpcode) {
9310           SDValue N002 = N00.getOperand(2);
9311           if (isContractableFMUL(N002))
9312             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9313                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9314                                            N00.getOperand(0)),
9315                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9316                                            N00.getOperand(1)),
9317                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9318                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9319                                                        N002.getOperand(0)),
9320                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9321                                                        N002.getOperand(1)),
9322                                            DAG.getNode(ISD::FNEG, SL, VT,
9323                                                        N1)));
9324         }
9325       }
9326
9327       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9328       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9329       if (N1.getOpcode() == PreferredFusedOpcode &&
9330         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9331         SDValue N120 = N1.getOperand(2).getOperand(0);
9332         if (isContractableFMUL(N120)) {
9333           SDValue N1200 = N120.getOperand(0);
9334           SDValue N1201 = N120.getOperand(1);
9335           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9336                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9337                              N1.getOperand(1),
9338                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9339                                          DAG.getNode(ISD::FNEG, SL, VT,
9340                                              DAG.getNode(ISD::FP_EXTEND, SL,
9341                                                          VT, N1200)),
9342                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9343                                                      N1201),
9344                                          N0));
9345         }
9346       }
9347
9348       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9349       //   -> (fma (fneg (fpext y)), (fpext z),
9350       //           (fma (fneg (fpext u)), (fpext v), x))
9351       // FIXME: This turns two single-precision and one double-precision
9352       // operation into two double-precision operations, which might not be
9353       // interesting for all targets, especially GPUs.
9354       if (N1.getOpcode() == ISD::FP_EXTEND &&
9355         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9356         SDValue N100 = N1.getOperand(0).getOperand(0);
9357         SDValue N101 = N1.getOperand(0).getOperand(1);
9358         SDValue N102 = N1.getOperand(0).getOperand(2);
9359         if (isContractableFMUL(N102)) {
9360           SDValue N1020 = N102.getOperand(0);
9361           SDValue N1021 = N102.getOperand(1);
9362           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9363                              DAG.getNode(ISD::FNEG, SL, VT,
9364                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9365                                                      N100)),
9366                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9367                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9368                                          DAG.getNode(ISD::FNEG, SL, VT,
9369                                              DAG.getNode(ISD::FP_EXTEND, SL,
9370                                                          VT, N1020)),
9371                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9372                                                      N1021),
9373                                          N0));
9374         }
9375       }
9376     }
9377   }
9378
9379   return SDValue();
9380 }
9381
9382 /// Try to perform FMA combining on a given FMUL node based on the distributive
9383 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9384 /// subtraction instead of addition).
9385 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9386   SDValue N0 = N->getOperand(0);
9387   SDValue N1 = N->getOperand(1);
9388   EVT VT = N->getValueType(0);
9389   SDLoc SL(N);
9390
9391   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9392
9393   const TargetOptions &Options = DAG.getTarget().Options;
9394
9395   // The transforms below are incorrect when x == 0 and y == inf, because the
9396   // intermediate multiplication produces a nan.
9397   if (!Options.NoInfsFPMath)
9398     return SDValue();
9399
9400   // Floating-point multiply-add without intermediate rounding.
9401   bool HasFMA =
9402       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9403       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9404       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9405
9406   // Floating-point multiply-add with intermediate rounding. This can result
9407   // in a less precise result due to the changed rounding order.
9408   bool HasFMAD = Options.UnsafeFPMath &&
9409                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9410
9411   // No valid opcode, do not combine.
9412   if (!HasFMAD && !HasFMA)
9413     return SDValue();
9414
9415   // Always prefer FMAD to FMA for precision.
9416   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9417   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9418
9419   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9420   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9421   auto FuseFADD = [&](SDValue X, SDValue Y) {
9422     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9423       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9424       if (XC1 && XC1->isExactlyValue(+1.0))
9425         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9426       if (XC1 && XC1->isExactlyValue(-1.0))
9427         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9428                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9429     }
9430     return SDValue();
9431   };
9432
9433   if (SDValue FMA = FuseFADD(N0, N1))
9434     return FMA;
9435   if (SDValue FMA = FuseFADD(N1, N0))
9436     return FMA;
9437
9438   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9439   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9440   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9441   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9442   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9443     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9444       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9445       if (XC0 && XC0->isExactlyValue(+1.0))
9446         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9447                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9448                            Y);
9449       if (XC0 && XC0->isExactlyValue(-1.0))
9450         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9451                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9452                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9453
9454       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9455       if (XC1 && XC1->isExactlyValue(+1.0))
9456         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9457                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9458       if (XC1 && XC1->isExactlyValue(-1.0))
9459         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9460     }
9461     return SDValue();
9462   };
9463
9464   if (SDValue FMA = FuseFSUB(N0, N1))
9465     return FMA;
9466   if (SDValue FMA = FuseFSUB(N1, N0))
9467     return FMA;
9468
9469   return SDValue();
9470 }
9471
9472 SDValue DAGCombiner::visitFADD(SDNode *N) {
9473   SDValue N0 = N->getOperand(0);
9474   SDValue N1 = N->getOperand(1);
9475   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9476   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9477   EVT VT = N->getValueType(0);
9478   SDLoc DL(N);
9479   const TargetOptions &Options = DAG.getTarget().Options;
9480   const SDNodeFlags Flags = N->getFlags();
9481
9482   // fold vector ops
9483   if (VT.isVector())
9484     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9485       return FoldedVOp;
9486
9487   // fold (fadd c1, c2) -> c1 + c2
9488   if (N0CFP && N1CFP)
9489     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9490
9491   // canonicalize constant to RHS
9492   if (N0CFP && !N1CFP)
9493     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9494
9495   if (SDValue NewSel = foldBinOpIntoSelect(N))
9496     return NewSel;
9497
9498   // fold (fadd A, (fneg B)) -> (fsub A, B)
9499   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9500       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9501     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9502                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9503
9504   // fold (fadd (fneg A), B) -> (fsub B, A)
9505   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9506       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9507     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9508                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9509
9510   // FIXME: Auto-upgrade the target/function-level option.
9511   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9512     // fold (fadd A, 0) -> A
9513     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9514       if (N1C->isZero())
9515         return N0;
9516   }
9517
9518   // If 'unsafe math' is enabled, fold lots of things.
9519   if (Options.UnsafeFPMath) {
9520     // No FP constant should be created after legalization as Instruction
9521     // Selection pass has a hard time dealing with FP constants.
9522     bool AllowNewConst = (Level < AfterLegalizeDAG);
9523
9524     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9525     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9526         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9527       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9528                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9529                                      Flags),
9530                          Flags);
9531
9532     // If allowed, fold (fadd (fneg x), x) -> 0.0
9533     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9534       return DAG.getConstantFP(0.0, DL, VT);
9535
9536     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9537     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9538       return DAG.getConstantFP(0.0, DL, VT);
9539
9540     // We can fold chains of FADD's of the same value into multiplications.
9541     // This transform is not safe in general because we are reducing the number
9542     // of rounding steps.
9543     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9544       if (N0.getOpcode() == ISD::FMUL) {
9545         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9546         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9547
9548         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9549         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9550           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9551                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9552           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9553         }
9554
9555         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9556         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9557             N1.getOperand(0) == N1.getOperand(1) &&
9558             N0.getOperand(0) == N1.getOperand(0)) {
9559           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9560                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9561           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9562         }
9563       }
9564
9565       if (N1.getOpcode() == ISD::FMUL) {
9566         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9567         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9568
9569         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9570         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9571           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9572                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9573           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9574         }
9575
9576         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9577         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9578             N0.getOperand(0) == N0.getOperand(1) &&
9579             N1.getOperand(0) == N0.getOperand(0)) {
9580           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9581                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9582           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9583         }
9584       }
9585
9586       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9587         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9588         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9589         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9590             (N0.getOperand(0) == N1)) {
9591           return DAG.getNode(ISD::FMUL, DL, VT,
9592                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9593         }
9594       }
9595
9596       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9597         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9598         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9599         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9600             N1.getOperand(0) == N0) {
9601           return DAG.getNode(ISD::FMUL, DL, VT,
9602                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9603         }
9604       }
9605
9606       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9607       if (AllowNewConst &&
9608           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9609           N0.getOperand(0) == N0.getOperand(1) &&
9610           N1.getOperand(0) == N1.getOperand(1) &&
9611           N0.getOperand(0) == N1.getOperand(0)) {
9612         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9613                            DAG.getConstantFP(4.0, DL, VT), Flags);
9614       }
9615     }
9616   } // enable-unsafe-fp-math
9617
9618   // FADD -> FMA combines:
9619   if (SDValue Fused = visitFADDForFMACombine(N)) {
9620     AddToWorklist(Fused.getNode());
9621     return Fused;
9622   }
9623   return SDValue();
9624 }
9625
9626 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9627   SDValue N0 = N->getOperand(0);
9628   SDValue N1 = N->getOperand(1);
9629   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9630   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9631   EVT VT = N->getValueType(0);
9632   SDLoc DL(N);
9633   const TargetOptions &Options = DAG.getTarget().Options;
9634   const SDNodeFlags Flags = N->getFlags();
9635
9636   // fold vector ops
9637   if (VT.isVector())
9638     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9639       return FoldedVOp;
9640
9641   // fold (fsub c1, c2) -> c1-c2
9642   if (N0CFP && N1CFP)
9643     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9644
9645   if (SDValue NewSel = foldBinOpIntoSelect(N))
9646     return NewSel;
9647
9648   // fold (fsub A, (fneg B)) -> (fadd A, B)
9649   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9650     return DAG.getNode(ISD::FADD, DL, VT, N0,
9651                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9652
9653   // FIXME: Auto-upgrade the target/function-level option.
9654   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9655     // (fsub 0, B) -> -B
9656     if (N0CFP && N0CFP->isZero()) {
9657       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9658         return GetNegatedExpression(N1, DAG, LegalOperations);
9659       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9660         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9661     }
9662   }
9663
9664   // If 'unsafe math' is enabled, fold lots of things.
9665   if (Options.UnsafeFPMath) {
9666     // (fsub A, 0) -> A
9667     if (N1CFP && N1CFP->isZero())
9668       return N0;
9669
9670     // (fsub x, x) -> 0.0
9671     if (N0 == N1)
9672       return DAG.getConstantFP(0.0f, DL, VT);
9673
9674     // (fsub x, (fadd x, y)) -> (fneg y)
9675     // (fsub x, (fadd y, x)) -> (fneg y)
9676     if (N1.getOpcode() == ISD::FADD) {
9677       SDValue N10 = N1->getOperand(0);
9678       SDValue N11 = N1->getOperand(1);
9679
9680       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9681         return GetNegatedExpression(N11, DAG, LegalOperations);
9682
9683       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9684         return GetNegatedExpression(N10, DAG, LegalOperations);
9685     }
9686   }
9687
9688   // FSUB -> FMA combines:
9689   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9690     AddToWorklist(Fused.getNode());
9691     return Fused;
9692   }
9693
9694   return SDValue();
9695 }
9696
9697 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9698   SDValue N0 = N->getOperand(0);
9699   SDValue N1 = N->getOperand(1);
9700   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9701   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9702   EVT VT = N->getValueType(0);
9703   SDLoc DL(N);
9704   const TargetOptions &Options = DAG.getTarget().Options;
9705   const SDNodeFlags Flags = N->getFlags();
9706
9707   // fold vector ops
9708   if (VT.isVector()) {
9709     // This just handles C1 * C2 for vectors. Other vector folds are below.
9710     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9711       return FoldedVOp;
9712   }
9713
9714   // fold (fmul c1, c2) -> c1*c2
9715   if (N0CFP && N1CFP)
9716     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9717
9718   // canonicalize constant to RHS
9719   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9720      !isConstantFPBuildVectorOrConstantFP(N1))
9721     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9722
9723   // fold (fmul A, 1.0) -> A
9724   if (N1CFP && N1CFP->isExactlyValue(1.0))
9725     return N0;
9726
9727   if (SDValue NewSel = foldBinOpIntoSelect(N))
9728     return NewSel;
9729
9730   if (Options.UnsafeFPMath) {
9731     // fold (fmul A, 0) -> 0
9732     if (N1CFP && N1CFP->isZero())
9733       return N1;
9734
9735     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9736     if (N0.getOpcode() == ISD::FMUL) {
9737       // Fold scalars or any vector constants (not just splats).
9738       // This fold is done in general by InstCombine, but extra fmul insts
9739       // may have been generated during lowering.
9740       SDValue N00 = N0.getOperand(0);
9741       SDValue N01 = N0.getOperand(1);
9742       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9743       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9744       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9745
9746       // Check 1: Make sure that the first operand of the inner multiply is NOT
9747       // a constant. Otherwise, we may induce infinite looping.
9748       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9749         // Check 2: Make sure that the second operand of the inner multiply and
9750         // the second operand of the outer multiply are constants.
9751         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9752             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9753           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9754           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9755         }
9756       }
9757     }
9758
9759     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9760     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9761     // during an early run of DAGCombiner can prevent folding with fmuls
9762     // inserted during lowering.
9763     if (N0.getOpcode() == ISD::FADD &&
9764         (N0.getOperand(0) == N0.getOperand(1)) &&
9765         N0.hasOneUse()) {
9766       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9767       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9768       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9769     }
9770   }
9771
9772   // fold (fmul X, 2.0) -> (fadd X, X)
9773   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9774     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9775
9776   // fold (fmul X, -1.0) -> (fneg X)
9777   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9778     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9779       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9780
9781   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9782   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9783     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9784       // Both can be negated for free, check to see if at least one is cheaper
9785       // negated.
9786       if (LHSNeg == 2 || RHSNeg == 2)
9787         return DAG.getNode(ISD::FMUL, DL, VT,
9788                            GetNegatedExpression(N0, DAG, LegalOperations),
9789                            GetNegatedExpression(N1, DAG, LegalOperations),
9790                            Flags);
9791     }
9792   }
9793
9794   // FMUL -> FMA combines:
9795   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9796     AddToWorklist(Fused.getNode());
9797     return Fused;
9798   }
9799
9800   return SDValue();
9801 }
9802
9803 SDValue DAGCombiner::visitFMA(SDNode *N) {
9804   SDValue N0 = N->getOperand(0);
9805   SDValue N1 = N->getOperand(1);
9806   SDValue N2 = N->getOperand(2);
9807   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9808   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9809   EVT VT = N->getValueType(0);
9810   SDLoc DL(N);
9811   const TargetOptions &Options = DAG.getTarget().Options;
9812
9813   // Constant fold FMA.
9814   if (isa<ConstantFPSDNode>(N0) &&
9815       isa<ConstantFPSDNode>(N1) &&
9816       isa<ConstantFPSDNode>(N2)) {
9817     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9818   }
9819
9820   if (Options.UnsafeFPMath) {
9821     if (N0CFP && N0CFP->isZero())
9822       return N2;
9823     if (N1CFP && N1CFP->isZero())
9824       return N2;
9825   }
9826   // TODO: The FMA node should have flags that propagate to these nodes.
9827   if (N0CFP && N0CFP->isExactlyValue(1.0))
9828     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9829   if (N1CFP && N1CFP->isExactlyValue(1.0))
9830     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9831
9832   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9833   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9834      !isConstantFPBuildVectorOrConstantFP(N1))
9835     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9836
9837   // TODO: FMA nodes should have flags that propagate to the created nodes.
9838   // For now, create a Flags object for use with all unsafe math transforms.
9839   SDNodeFlags Flags;
9840   Flags.setUnsafeAlgebra(true);
9841
9842   if (Options.UnsafeFPMath) {
9843     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9844     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9845         isConstantFPBuildVectorOrConstantFP(N1) &&
9846         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9847       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9848                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9849                                      Flags), Flags);
9850     }
9851
9852     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9853     if (N0.getOpcode() == ISD::FMUL &&
9854         isConstantFPBuildVectorOrConstantFP(N1) &&
9855         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9856       return DAG.getNode(ISD::FMA, DL, VT,
9857                          N0.getOperand(0),
9858                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9859                                      Flags),
9860                          N2);
9861     }
9862   }
9863
9864   // (fma x, 1, y) -> (fadd x, y)
9865   // (fma x, -1, y) -> (fadd (fneg x), y)
9866   if (N1CFP) {
9867     if (N1CFP->isExactlyValue(1.0))
9868       // TODO: The FMA node should have flags that propagate to this node.
9869       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9870
9871     if (N1CFP->isExactlyValue(-1.0) &&
9872         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9873       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9874       AddToWorklist(RHSNeg.getNode());
9875       // TODO: The FMA node should have flags that propagate to this node.
9876       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9877     }
9878   }
9879
9880   if (Options.UnsafeFPMath) {
9881     // (fma x, c, x) -> (fmul x, (c+1))
9882     if (N1CFP && N0 == N2) {
9883       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9884                          DAG.getNode(ISD::FADD, DL, VT, N1,
9885                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9886                          Flags);
9887     }
9888
9889     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9890     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9891       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9892                          DAG.getNode(ISD::FADD, DL, VT, N1,
9893                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
9894                          Flags);
9895     }
9896   }
9897
9898   return SDValue();
9899 }
9900
9901 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9902 // reciprocal.
9903 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9904 // Notice that this is not always beneficial. One reason is different targets
9905 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9906 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9907 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9908 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9909   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9910   const SDNodeFlags Flags = N->getFlags();
9911   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9912     return SDValue();
9913
9914   // Skip if current node is a reciprocal.
9915   SDValue N0 = N->getOperand(0);
9916   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9917   if (N0CFP && N0CFP->isExactlyValue(1.0))
9918     return SDValue();
9919
9920   // Exit early if the target does not want this transform or if there can't
9921   // possibly be enough uses of the divisor to make the transform worthwhile.
9922   SDValue N1 = N->getOperand(1);
9923   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9924   if (!MinUses || N1->use_size() < MinUses)
9925     return SDValue();
9926
9927   // Find all FDIV users of the same divisor.
9928   // Use a set because duplicates may be present in the user list.
9929   SetVector<SDNode *> Users;
9930   for (auto *U : N1->uses()) {
9931     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9932       // This division is eligible for optimization only if global unsafe math
9933       // is enabled or if this division allows reciprocal formation.
9934       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
9935         Users.insert(U);
9936     }
9937   }
9938
9939   // Now that we have the actual number of divisor uses, make sure it meets
9940   // the minimum threshold specified by the target.
9941   if (Users.size() < MinUses)
9942     return SDValue();
9943
9944   EVT VT = N->getValueType(0);
9945   SDLoc DL(N);
9946   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9947   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9948
9949   // Dividend / Divisor -> Dividend * Reciprocal
9950   for (auto *U : Users) {
9951     SDValue Dividend = U->getOperand(0);
9952     if (Dividend != FPOne) {
9953       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9954                                     Reciprocal, Flags);
9955       CombineTo(U, NewNode);
9956     } else if (U != Reciprocal.getNode()) {
9957       // In the absence of fast-math-flags, this user node is always the
9958       // same node as Reciprocal, but with FMF they may be different nodes.
9959       CombineTo(U, Reciprocal);
9960     }
9961   }
9962   return SDValue(N, 0);  // N was replaced.
9963 }
9964
9965 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9966   SDValue N0 = N->getOperand(0);
9967   SDValue N1 = N->getOperand(1);
9968   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9969   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9970   EVT VT = N->getValueType(0);
9971   SDLoc DL(N);
9972   const TargetOptions &Options = DAG.getTarget().Options;
9973   SDNodeFlags Flags = N->getFlags();
9974
9975   // fold vector ops
9976   if (VT.isVector())
9977     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9978       return FoldedVOp;
9979
9980   // fold (fdiv c1, c2) -> c1/c2
9981   if (N0CFP && N1CFP)
9982     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9983
9984   if (SDValue NewSel = foldBinOpIntoSelect(N))
9985     return NewSel;
9986
9987   if (Options.UnsafeFPMath) {
9988     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9989     if (N1CFP) {
9990       // Compute the reciprocal 1.0 / c2.
9991       const APFloat &N1APF = N1CFP->getValueAPF();
9992       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9993       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9994       // Only do the transform if the reciprocal is a legal fp immediate that
9995       // isn't too nasty (eg NaN, denormal, ...).
9996       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9997           (!LegalOperations ||
9998            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9999            // backend)... we should handle this gracefully after Legalize.
10000            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10001            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10002            TLI.isFPImmLegal(Recip, VT)))
10003         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10004                            DAG.getConstantFP(Recip, DL, VT), Flags);
10005     }
10006
10007     // If this FDIV is part of a reciprocal square root, it may be folded
10008     // into a target-specific square root estimate instruction.
10009     if (N1.getOpcode() == ISD::FSQRT) {
10010       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10011         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10012       }
10013     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10014                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10015       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10016                                           Flags)) {
10017         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10018         AddToWorklist(RV.getNode());
10019         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10020       }
10021     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10022                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10023       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10024                                           Flags)) {
10025         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10026         AddToWorklist(RV.getNode());
10027         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10028       }
10029     } else if (N1.getOpcode() == ISD::FMUL) {
10030       // Look through an FMUL. Even though this won't remove the FDIV directly,
10031       // it's still worthwhile to get rid of the FSQRT if possible.
10032       SDValue SqrtOp;
10033       SDValue OtherOp;
10034       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10035         SqrtOp = N1.getOperand(0);
10036         OtherOp = N1.getOperand(1);
10037       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10038         SqrtOp = N1.getOperand(1);
10039         OtherOp = N1.getOperand(0);
10040       }
10041       if (SqrtOp.getNode()) {
10042         // We found a FSQRT, so try to make this fold:
10043         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10044         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10045           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10046           AddToWorklist(RV.getNode());
10047           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10048         }
10049       }
10050     }
10051
10052     // Fold into a reciprocal estimate and multiply instead of a real divide.
10053     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10054       AddToWorklist(RV.getNode());
10055       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10056     }
10057   }
10058
10059   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10060   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10061     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10062       // Both can be negated for free, check to see if at least one is cheaper
10063       // negated.
10064       if (LHSNeg == 2 || RHSNeg == 2)
10065         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10066                            GetNegatedExpression(N0, DAG, LegalOperations),
10067                            GetNegatedExpression(N1, DAG, LegalOperations),
10068                            Flags);
10069     }
10070   }
10071
10072   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10073     return CombineRepeatedDivisors;
10074
10075   return SDValue();
10076 }
10077
10078 SDValue DAGCombiner::visitFREM(SDNode *N) {
10079   SDValue N0 = N->getOperand(0);
10080   SDValue N1 = N->getOperand(1);
10081   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10082   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10083   EVT VT = N->getValueType(0);
10084
10085   // fold (frem c1, c2) -> fmod(c1,c2)
10086   if (N0CFP && N1CFP)
10087     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10088
10089   if (SDValue NewSel = foldBinOpIntoSelect(N))
10090     return NewSel;
10091
10092   return SDValue();
10093 }
10094
10095 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10096   if (!DAG.getTarget().Options.UnsafeFPMath)
10097     return SDValue();
10098
10099   SDValue N0 = N->getOperand(0);
10100   if (TLI.isFsqrtCheap(N0, DAG))
10101     return SDValue();
10102
10103   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10104   // For now, create a Flags object for use with all unsafe math transforms.
10105   SDNodeFlags Flags;
10106   Flags.setUnsafeAlgebra(true);
10107   return buildSqrtEstimate(N0, Flags);
10108 }
10109
10110 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10111 /// copysign(x, fp_round(y)) -> copysign(x, y)
10112 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10113   SDValue N1 = N->getOperand(1);
10114   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10115        N1.getOpcode() == ISD::FP_ROUND)) {
10116     // Do not optimize out type conversion of f128 type yet.
10117     // For some targets like x86_64, configuration is changed to keep one f128
10118     // value in one SSE register, but instruction selection cannot handle
10119     // FCOPYSIGN on SSE registers yet.
10120     EVT N1VT = N1->getValueType(0);
10121     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10122     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10123   }
10124   return false;
10125 }
10126
10127 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10128   SDValue N0 = N->getOperand(0);
10129   SDValue N1 = N->getOperand(1);
10130   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10131   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10132   EVT VT = N->getValueType(0);
10133
10134   if (N0CFP && N1CFP) // Constant fold
10135     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10136
10137   if (N1CFP) {
10138     const APFloat &V = N1CFP->getValueAPF();
10139     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10140     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10141     if (!V.isNegative()) {
10142       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10143         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10144     } else {
10145       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10146         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10147                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10148     }
10149   }
10150
10151   // copysign(fabs(x), y) -> copysign(x, y)
10152   // copysign(fneg(x), y) -> copysign(x, y)
10153   // copysign(copysign(x,z), y) -> copysign(x, y)
10154   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10155       N0.getOpcode() == ISD::FCOPYSIGN)
10156     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10157
10158   // copysign(x, abs(y)) -> abs(x)
10159   if (N1.getOpcode() == ISD::FABS)
10160     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10161
10162   // copysign(x, copysign(y,z)) -> copysign(x, z)
10163   if (N1.getOpcode() == ISD::FCOPYSIGN)
10164     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10165
10166   // copysign(x, fp_extend(y)) -> copysign(x, y)
10167   // copysign(x, fp_round(y)) -> copysign(x, y)
10168   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10169     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10170
10171   return SDValue();
10172 }
10173
10174 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10175   SDValue N0 = N->getOperand(0);
10176   EVT VT = N->getValueType(0);
10177   EVT OpVT = N0.getValueType();
10178
10179   // fold (sint_to_fp c1) -> c1fp
10180   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10181       // ...but only if the target supports immediate floating-point values
10182       (!LegalOperations ||
10183        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10184     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10185
10186   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10187   // but UINT_TO_FP is legal on this target, try to convert.
10188   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10189       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10190     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10191     if (DAG.SignBitIsZero(N0))
10192       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10193   }
10194
10195   // The next optimizations are desirable only if SELECT_CC can be lowered.
10196   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10197     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10198     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10199         !VT.isVector() &&
10200         (!LegalOperations ||
10201          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10202       SDLoc DL(N);
10203       SDValue Ops[] =
10204         { N0.getOperand(0), N0.getOperand(1),
10205           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10206           N0.getOperand(2) };
10207       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10208     }
10209
10210     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10211     //      (select_cc x, y, 1.0, 0.0,, cc)
10212     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10213         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10214         (!LegalOperations ||
10215          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10216       SDLoc DL(N);
10217       SDValue Ops[] =
10218         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10219           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10220           N0.getOperand(0).getOperand(2) };
10221       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10222     }
10223   }
10224
10225   return SDValue();
10226 }
10227
10228 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10229   SDValue N0 = N->getOperand(0);
10230   EVT VT = N->getValueType(0);
10231   EVT OpVT = N0.getValueType();
10232
10233   // fold (uint_to_fp c1) -> c1fp
10234   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10235       // ...but only if the target supports immediate floating-point values
10236       (!LegalOperations ||
10237        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10238     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10239
10240   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10241   // but SINT_TO_FP is legal on this target, try to convert.
10242   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10243       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10244     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10245     if (DAG.SignBitIsZero(N0))
10246       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10247   }
10248
10249   // The next optimizations are desirable only if SELECT_CC can be lowered.
10250   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10251     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10252
10253     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10254         (!LegalOperations ||
10255          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10256       SDLoc DL(N);
10257       SDValue Ops[] =
10258         { N0.getOperand(0), N0.getOperand(1),
10259           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10260           N0.getOperand(2) };
10261       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10262     }
10263   }
10264
10265   return SDValue();
10266 }
10267
10268 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10269 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10270   SDValue N0 = N->getOperand(0);
10271   EVT VT = N->getValueType(0);
10272
10273   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10274     return SDValue();
10275
10276   SDValue Src = N0.getOperand(0);
10277   EVT SrcVT = Src.getValueType();
10278   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10279   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10280
10281   // We can safely assume the conversion won't overflow the output range,
10282   // because (for example) (uint8_t)18293.f is undefined behavior.
10283
10284   // Since we can assume the conversion won't overflow, our decision as to
10285   // whether the input will fit in the float should depend on the minimum
10286   // of the input range and output range.
10287
10288   // This means this is also safe for a signed input and unsigned output, since
10289   // a negative input would lead to undefined behavior.
10290   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10291   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10292   unsigned ActualSize = std::min(InputSize, OutputSize);
10293   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10294
10295   // We can only fold away the float conversion if the input range can be
10296   // represented exactly in the float range.
10297   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10298     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10299       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10300                                                        : ISD::ZERO_EXTEND;
10301       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10302     }
10303     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10304       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10305     return DAG.getBitcast(VT, Src);
10306   }
10307   return SDValue();
10308 }
10309
10310 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10311   SDValue N0 = N->getOperand(0);
10312   EVT VT = N->getValueType(0);
10313
10314   // fold (fp_to_sint c1fp) -> c1
10315   if (isConstantFPBuildVectorOrConstantFP(N0))
10316     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10317
10318   return FoldIntToFPToInt(N, DAG);
10319 }
10320
10321 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10322   SDValue N0 = N->getOperand(0);
10323   EVT VT = N->getValueType(0);
10324
10325   // fold (fp_to_uint c1fp) -> c1
10326   if (isConstantFPBuildVectorOrConstantFP(N0))
10327     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10328
10329   return FoldIntToFPToInt(N, DAG);
10330 }
10331
10332 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10333   SDValue N0 = N->getOperand(0);
10334   SDValue N1 = N->getOperand(1);
10335   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10336   EVT VT = N->getValueType(0);
10337
10338   // fold (fp_round c1fp) -> c1fp
10339   if (N0CFP)
10340     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10341
10342   // fold (fp_round (fp_extend x)) -> x
10343   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10344     return N0.getOperand(0);
10345
10346   // fold (fp_round (fp_round x)) -> (fp_round x)
10347   if (N0.getOpcode() == ISD::FP_ROUND) {
10348     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10349     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10350
10351     // Skip this folding if it results in an fp_round from f80 to f16.
10352     //
10353     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10354     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10355     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10356     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10357     // x86.
10358     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10359       return SDValue();
10360
10361     // If the first fp_round isn't a value preserving truncation, it might
10362     // introduce a tie in the second fp_round, that wouldn't occur in the
10363     // single-step fp_round we want to fold to.
10364     // In other words, double rounding isn't the same as rounding.
10365     // Also, this is a value preserving truncation iff both fp_round's are.
10366     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10367       SDLoc DL(N);
10368       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10369                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10370     }
10371   }
10372
10373   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10374   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10375     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10376                               N0.getOperand(0), N1);
10377     AddToWorklist(Tmp.getNode());
10378     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10379                        Tmp, N0.getOperand(1));
10380   }
10381
10382   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10383     return NewVSel;
10384
10385   return SDValue();
10386 }
10387
10388 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10389   SDValue N0 = N->getOperand(0);
10390   EVT VT = N->getValueType(0);
10391   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10392   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10393
10394   // fold (fp_round_inreg c1fp) -> c1fp
10395   if (N0CFP && isTypeLegal(EVT)) {
10396     SDLoc DL(N);
10397     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10398     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10399   }
10400
10401   return SDValue();
10402 }
10403
10404 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10405   SDValue N0 = N->getOperand(0);
10406   EVT VT = N->getValueType(0);
10407
10408   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10409   if (N->hasOneUse() &&
10410       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10411     return SDValue();
10412
10413   // fold (fp_extend c1fp) -> c1fp
10414   if (isConstantFPBuildVectorOrConstantFP(N0))
10415     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10416
10417   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10418   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10419       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10420     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10421
10422   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10423   // value of X.
10424   if (N0.getOpcode() == ISD::FP_ROUND
10425       && N0.getConstantOperandVal(1) == 1) {
10426     SDValue In = N0.getOperand(0);
10427     if (In.getValueType() == VT) return In;
10428     if (VT.bitsLT(In.getValueType()))
10429       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10430                          In, N0.getOperand(1));
10431     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10432   }
10433
10434   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10435   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10436        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10437     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10438     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10439                                      LN0->getChain(),
10440                                      LN0->getBasePtr(), N0.getValueType(),
10441                                      LN0->getMemOperand());
10442     CombineTo(N, ExtLoad);
10443     CombineTo(N0.getNode(),
10444               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10445                           N0.getValueType(), ExtLoad,
10446                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10447               ExtLoad.getValue(1));
10448     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10449   }
10450
10451   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10452     return NewVSel;
10453
10454   return SDValue();
10455 }
10456
10457 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10458   SDValue N0 = N->getOperand(0);
10459   EVT VT = N->getValueType(0);
10460
10461   // fold (fceil c1) -> fceil(c1)
10462   if (isConstantFPBuildVectorOrConstantFP(N0))
10463     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10464
10465   return SDValue();
10466 }
10467
10468 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10469   SDValue N0 = N->getOperand(0);
10470   EVT VT = N->getValueType(0);
10471
10472   // fold (ftrunc c1) -> ftrunc(c1)
10473   if (isConstantFPBuildVectorOrConstantFP(N0))
10474     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10475
10476   return SDValue();
10477 }
10478
10479 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10480   SDValue N0 = N->getOperand(0);
10481   EVT VT = N->getValueType(0);
10482
10483   // fold (ffloor c1) -> ffloor(c1)
10484   if (isConstantFPBuildVectorOrConstantFP(N0))
10485     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10486
10487   return SDValue();
10488 }
10489
10490 // FIXME: FNEG and FABS have a lot in common; refactor.
10491 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10492   SDValue N0 = N->getOperand(0);
10493   EVT VT = N->getValueType(0);
10494
10495   // Constant fold FNEG.
10496   if (isConstantFPBuildVectorOrConstantFP(N0))
10497     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10498
10499   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10500                          &DAG.getTarget().Options))
10501     return GetNegatedExpression(N0, DAG, LegalOperations);
10502
10503   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10504   // constant pool values.
10505   if (!TLI.isFNegFree(VT) &&
10506       N0.getOpcode() == ISD::BITCAST &&
10507       N0.getNode()->hasOneUse()) {
10508     SDValue Int = N0.getOperand(0);
10509     EVT IntVT = Int.getValueType();
10510     if (IntVT.isInteger() && !IntVT.isVector()) {
10511       APInt SignMask;
10512       if (N0.getValueType().isVector()) {
10513         // For a vector, get a mask such as 0x80... per scalar element
10514         // and splat it.
10515         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10516         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10517       } else {
10518         // For a scalar, just generate 0x80...
10519         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10520       }
10521       SDLoc DL0(N0);
10522       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10523                         DAG.getConstant(SignMask, DL0, IntVT));
10524       AddToWorklist(Int.getNode());
10525       return DAG.getBitcast(VT, Int);
10526     }
10527   }
10528
10529   // (fneg (fmul c, x)) -> (fmul -c, x)
10530   if (N0.getOpcode() == ISD::FMUL &&
10531       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10532     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10533     if (CFP1) {
10534       APFloat CVal = CFP1->getValueAPF();
10535       CVal.changeSign();
10536       if (Level >= AfterLegalizeDAG &&
10537           (TLI.isFPImmLegal(CVal, VT) ||
10538            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10539         return DAG.getNode(
10540             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10541             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10542             N0->getFlags());
10543     }
10544   }
10545
10546   return SDValue();
10547 }
10548
10549 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10550   SDValue N0 = N->getOperand(0);
10551   SDValue N1 = N->getOperand(1);
10552   EVT VT = N->getValueType(0);
10553   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10554   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10555
10556   if (N0CFP && N1CFP) {
10557     const APFloat &C0 = N0CFP->getValueAPF();
10558     const APFloat &C1 = N1CFP->getValueAPF();
10559     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10560   }
10561
10562   // Canonicalize to constant on RHS.
10563   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10564      !isConstantFPBuildVectorOrConstantFP(N1))
10565     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10566
10567   return SDValue();
10568 }
10569
10570 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10571   SDValue N0 = N->getOperand(0);
10572   SDValue N1 = N->getOperand(1);
10573   EVT VT = N->getValueType(0);
10574   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10575   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10576
10577   if (N0CFP && N1CFP) {
10578     const APFloat &C0 = N0CFP->getValueAPF();
10579     const APFloat &C1 = N1CFP->getValueAPF();
10580     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10581   }
10582
10583   // Canonicalize to constant on RHS.
10584   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10585      !isConstantFPBuildVectorOrConstantFP(N1))
10586     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10587
10588   return SDValue();
10589 }
10590
10591 SDValue DAGCombiner::visitFABS(SDNode *N) {
10592   SDValue N0 = N->getOperand(0);
10593   EVT VT = N->getValueType(0);
10594
10595   // fold (fabs c1) -> fabs(c1)
10596   if (isConstantFPBuildVectorOrConstantFP(N0))
10597     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10598
10599   // fold (fabs (fabs x)) -> (fabs x)
10600   if (N0.getOpcode() == ISD::FABS)
10601     return N->getOperand(0);
10602
10603   // fold (fabs (fneg x)) -> (fabs x)
10604   // fold (fabs (fcopysign x, y)) -> (fabs x)
10605   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10606     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10607
10608   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10609   // constant pool values.
10610   if (!TLI.isFAbsFree(VT) &&
10611       N0.getOpcode() == ISD::BITCAST &&
10612       N0.getNode()->hasOneUse()) {
10613     SDValue Int = N0.getOperand(0);
10614     EVT IntVT = Int.getValueType();
10615     if (IntVT.isInteger() && !IntVT.isVector()) {
10616       APInt SignMask;
10617       if (N0.getValueType().isVector()) {
10618         // For a vector, get a mask such as 0x7f... per scalar element
10619         // and splat it.
10620         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10621         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10622       } else {
10623         // For a scalar, just generate 0x7f...
10624         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10625       }
10626       SDLoc DL(N0);
10627       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10628                         DAG.getConstant(SignMask, DL, IntVT));
10629       AddToWorklist(Int.getNode());
10630       return DAG.getBitcast(N->getValueType(0), Int);
10631     }
10632   }
10633
10634   return SDValue();
10635 }
10636
10637 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10638   SDValue Chain = N->getOperand(0);
10639   SDValue N1 = N->getOperand(1);
10640   SDValue N2 = N->getOperand(2);
10641
10642   // If N is a constant we could fold this into a fallthrough or unconditional
10643   // branch. However that doesn't happen very often in normal code, because
10644   // Instcombine/SimplifyCFG should have handled the available opportunities.
10645   // If we did this folding here, it would be necessary to update the
10646   // MachineBasicBlock CFG, which is awkward.
10647
10648   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10649   // on the target.
10650   if (N1.getOpcode() == ISD::SETCC &&
10651       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10652                                    N1.getOperand(0).getValueType())) {
10653     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10654                        Chain, N1.getOperand(2),
10655                        N1.getOperand(0), N1.getOperand(1), N2);
10656   }
10657
10658   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10659       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10660        (N1.getOperand(0).hasOneUse() &&
10661         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10662     SDNode *Trunc = nullptr;
10663     if (N1.getOpcode() == ISD::TRUNCATE) {
10664       // Look pass the truncate.
10665       Trunc = N1.getNode();
10666       N1 = N1.getOperand(0);
10667     }
10668
10669     // Match this pattern so that we can generate simpler code:
10670     //
10671     //   %a = ...
10672     //   %b = and i32 %a, 2
10673     //   %c = srl i32 %b, 1
10674     //   brcond i32 %c ...
10675     //
10676     // into
10677     //
10678     //   %a = ...
10679     //   %b = and i32 %a, 2
10680     //   %c = setcc eq %b, 0
10681     //   brcond %c ...
10682     //
10683     // This applies only when the AND constant value has one bit set and the
10684     // SRL constant is equal to the log2 of the AND constant. The back-end is
10685     // smart enough to convert the result into a TEST/JMP sequence.
10686     SDValue Op0 = N1.getOperand(0);
10687     SDValue Op1 = N1.getOperand(1);
10688
10689     if (Op0.getOpcode() == ISD::AND &&
10690         Op1.getOpcode() == ISD::Constant) {
10691       SDValue AndOp1 = Op0.getOperand(1);
10692
10693       if (AndOp1.getOpcode() == ISD::Constant) {
10694         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10695
10696         if (AndConst.isPowerOf2() &&
10697             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10698           SDLoc DL(N);
10699           SDValue SetCC =
10700             DAG.getSetCC(DL,
10701                          getSetCCResultType(Op0.getValueType()),
10702                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10703                          ISD::SETNE);
10704
10705           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10706                                           MVT::Other, Chain, SetCC, N2);
10707           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10708           // will convert it back to (X & C1) >> C2.
10709           CombineTo(N, NewBRCond, false);
10710           // Truncate is dead.
10711           if (Trunc)
10712             deleteAndRecombine(Trunc);
10713           // Replace the uses of SRL with SETCC
10714           WorklistRemover DeadNodes(*this);
10715           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10716           deleteAndRecombine(N1.getNode());
10717           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10718         }
10719       }
10720     }
10721
10722     if (Trunc)
10723       // Restore N1 if the above transformation doesn't match.
10724       N1 = N->getOperand(1);
10725   }
10726
10727   // Transform br(xor(x, y)) -> br(x != y)
10728   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10729   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10730     SDNode *TheXor = N1.getNode();
10731     SDValue Op0 = TheXor->getOperand(0);
10732     SDValue Op1 = TheXor->getOperand(1);
10733     if (Op0.getOpcode() == Op1.getOpcode()) {
10734       // Avoid missing important xor optimizations.
10735       if (SDValue Tmp = visitXOR(TheXor)) {
10736         if (Tmp.getNode() != TheXor) {
10737           DEBUG(dbgs() << "\nReplacing.8 ";
10738                 TheXor->dump(&DAG);
10739                 dbgs() << "\nWith: ";
10740                 Tmp.getNode()->dump(&DAG);
10741                 dbgs() << '\n');
10742           WorklistRemover DeadNodes(*this);
10743           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10744           deleteAndRecombine(TheXor);
10745           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10746                              MVT::Other, Chain, Tmp, N2);
10747         }
10748
10749         // visitXOR has changed XOR's operands or replaced the XOR completely,
10750         // bail out.
10751         return SDValue(N, 0);
10752       }
10753     }
10754
10755     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10756       bool Equal = false;
10757       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10758           Op0.getOpcode() == ISD::XOR) {
10759         TheXor = Op0.getNode();
10760         Equal = true;
10761       }
10762
10763       EVT SetCCVT = N1.getValueType();
10764       if (LegalTypes)
10765         SetCCVT = getSetCCResultType(SetCCVT);
10766       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10767                                    SetCCVT,
10768                                    Op0, Op1,
10769                                    Equal ? ISD::SETEQ : ISD::SETNE);
10770       // Replace the uses of XOR with SETCC
10771       WorklistRemover DeadNodes(*this);
10772       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10773       deleteAndRecombine(N1.getNode());
10774       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10775                          MVT::Other, Chain, SetCC, N2);
10776     }
10777   }
10778
10779   return SDValue();
10780 }
10781
10782 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10783 //
10784 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10785   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10786   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10787
10788   // If N is a constant we could fold this into a fallthrough or unconditional
10789   // branch. However that doesn't happen very often in normal code, because
10790   // Instcombine/SimplifyCFG should have handled the available opportunities.
10791   // If we did this folding here, it would be necessary to update the
10792   // MachineBasicBlock CFG, which is awkward.
10793
10794   // Use SimplifySetCC to simplify SETCC's.
10795   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10796                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10797                                false);
10798   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10799
10800   // fold to a simpler setcc
10801   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10802     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10803                        N->getOperand(0), Simp.getOperand(2),
10804                        Simp.getOperand(0), Simp.getOperand(1),
10805                        N->getOperand(4));
10806
10807   return SDValue();
10808 }
10809
10810 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10811 /// and that N may be folded in the load / store addressing mode.
10812 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10813                                     SelectionDAG &DAG,
10814                                     const TargetLowering &TLI) {
10815   EVT VT;
10816   unsigned AS;
10817
10818   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10819     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10820       return false;
10821     VT = LD->getMemoryVT();
10822     AS = LD->getAddressSpace();
10823   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10824     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10825       return false;
10826     VT = ST->getMemoryVT();
10827     AS = ST->getAddressSpace();
10828   } else
10829     return false;
10830
10831   TargetLowering::AddrMode AM;
10832   if (N->getOpcode() == ISD::ADD) {
10833     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10834     if (Offset)
10835       // [reg +/- imm]
10836       AM.BaseOffs = Offset->getSExtValue();
10837     else
10838       // [reg +/- reg]
10839       AM.Scale = 1;
10840   } else if (N->getOpcode() == ISD::SUB) {
10841     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10842     if (Offset)
10843       // [reg +/- imm]
10844       AM.BaseOffs = -Offset->getSExtValue();
10845     else
10846       // [reg +/- reg]
10847       AM.Scale = 1;
10848   } else
10849     return false;
10850
10851   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10852                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10853 }
10854
10855 /// Try turning a load/store into a pre-indexed load/store when the base
10856 /// pointer is an add or subtract and it has other uses besides the load/store.
10857 /// After the transformation, the new indexed load/store has effectively folded
10858 /// the add/subtract in and all of its other uses are redirected to the
10859 /// new load/store.
10860 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10861   if (Level < AfterLegalizeDAG)
10862     return false;
10863
10864   bool isLoad = true;
10865   SDValue Ptr;
10866   EVT VT;
10867   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10868     if (LD->isIndexed())
10869       return false;
10870     VT = LD->getMemoryVT();
10871     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10872         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10873       return false;
10874     Ptr = LD->getBasePtr();
10875   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10876     if (ST->isIndexed())
10877       return false;
10878     VT = ST->getMemoryVT();
10879     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10880         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10881       return false;
10882     Ptr = ST->getBasePtr();
10883     isLoad = false;
10884   } else {
10885     return false;
10886   }
10887
10888   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10889   // out.  There is no reason to make this a preinc/predec.
10890   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10891       Ptr.getNode()->hasOneUse())
10892     return false;
10893
10894   // Ask the target to do addressing mode selection.
10895   SDValue BasePtr;
10896   SDValue Offset;
10897   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10898   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10899     return false;
10900
10901   // Backends without true r+i pre-indexed forms may need to pass a
10902   // constant base with a variable offset so that constant coercion
10903   // will work with the patterns in canonical form.
10904   bool Swapped = false;
10905   if (isa<ConstantSDNode>(BasePtr)) {
10906     std::swap(BasePtr, Offset);
10907     Swapped = true;
10908   }
10909
10910   // Don't create a indexed load / store with zero offset.
10911   if (isNullConstant(Offset))
10912     return false;
10913
10914   // Try turning it into a pre-indexed load / store except when:
10915   // 1) The new base ptr is a frame index.
10916   // 2) If N is a store and the new base ptr is either the same as or is a
10917   //    predecessor of the value being stored.
10918   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10919   //    that would create a cycle.
10920   // 4) All uses are load / store ops that use it as old base ptr.
10921
10922   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10923   // (plus the implicit offset) to a register to preinc anyway.
10924   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10925     return false;
10926
10927   // Check #2.
10928   if (!isLoad) {
10929     SDValue Val = cast<StoreSDNode>(N)->getValue();
10930     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10931       return false;
10932   }
10933
10934   // Caches for hasPredecessorHelper.
10935   SmallPtrSet<const SDNode *, 32> Visited;
10936   SmallVector<const SDNode *, 16> Worklist;
10937   Worklist.push_back(N);
10938
10939   // If the offset is a constant, there may be other adds of constants that
10940   // can be folded with this one. We should do this to avoid having to keep
10941   // a copy of the original base pointer.
10942   SmallVector<SDNode *, 16> OtherUses;
10943   if (isa<ConstantSDNode>(Offset))
10944     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10945                               UE = BasePtr.getNode()->use_end();
10946          UI != UE; ++UI) {
10947       SDUse &Use = UI.getUse();
10948       // Skip the use that is Ptr and uses of other results from BasePtr's
10949       // node (important for nodes that return multiple results).
10950       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10951         continue;
10952
10953       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10954         continue;
10955
10956       if (Use.getUser()->getOpcode() != ISD::ADD &&
10957           Use.getUser()->getOpcode() != ISD::SUB) {
10958         OtherUses.clear();
10959         break;
10960       }
10961
10962       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10963       if (!isa<ConstantSDNode>(Op1)) {
10964         OtherUses.clear();
10965         break;
10966       }
10967
10968       // FIXME: In some cases, we can be smarter about this.
10969       if (Op1.getValueType() != Offset.getValueType()) {
10970         OtherUses.clear();
10971         break;
10972       }
10973
10974       OtherUses.push_back(Use.getUser());
10975     }
10976
10977   if (Swapped)
10978     std::swap(BasePtr, Offset);
10979
10980   // Now check for #3 and #4.
10981   bool RealUse = false;
10982
10983   for (SDNode *Use : Ptr.getNode()->uses()) {
10984     if (Use == N)
10985       continue;
10986     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10987       return false;
10988
10989     // If Ptr may be folded in addressing mode of other use, then it's
10990     // not profitable to do this transformation.
10991     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10992       RealUse = true;
10993   }
10994
10995   if (!RealUse)
10996     return false;
10997
10998   SDValue Result;
10999   if (isLoad)
11000     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11001                                 BasePtr, Offset, AM);
11002   else
11003     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11004                                  BasePtr, Offset, AM);
11005   ++PreIndexedNodes;
11006   ++NodesCombined;
11007   DEBUG(dbgs() << "\nReplacing.4 ";
11008         N->dump(&DAG);
11009         dbgs() << "\nWith: ";
11010         Result.getNode()->dump(&DAG);
11011         dbgs() << '\n');
11012   WorklistRemover DeadNodes(*this);
11013   if (isLoad) {
11014     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11015     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11016   } else {
11017     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11018   }
11019
11020   // Finally, since the node is now dead, remove it from the graph.
11021   deleteAndRecombine(N);
11022
11023   if (Swapped)
11024     std::swap(BasePtr, Offset);
11025
11026   // Replace other uses of BasePtr that can be updated to use Ptr
11027   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11028     unsigned OffsetIdx = 1;
11029     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11030       OffsetIdx = 0;
11031     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11032            BasePtr.getNode() && "Expected BasePtr operand");
11033
11034     // We need to replace ptr0 in the following expression:
11035     //   x0 * offset0 + y0 * ptr0 = t0
11036     // knowing that
11037     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11038     //
11039     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11040     // indexed load/store and the expresion that needs to be re-written.
11041     //
11042     // Therefore, we have:
11043     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11044
11045     ConstantSDNode *CN =
11046       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11047     int X0, X1, Y0, Y1;
11048     const APInt &Offset0 = CN->getAPIntValue();
11049     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11050
11051     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11052     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11053     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11054     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11055
11056     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11057
11058     APInt CNV = Offset0;
11059     if (X0 < 0) CNV = -CNV;
11060     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11061     else CNV = CNV - Offset1;
11062
11063     SDLoc DL(OtherUses[i]);
11064
11065     // We can now generate the new expression.
11066     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11067     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11068
11069     SDValue NewUse = DAG.getNode(Opcode,
11070                                  DL,
11071                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11072     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11073     deleteAndRecombine(OtherUses[i]);
11074   }
11075
11076   // Replace the uses of Ptr with uses of the updated base value.
11077   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11078   deleteAndRecombine(Ptr.getNode());
11079
11080   return true;
11081 }
11082
11083 /// Try to combine a load/store with a add/sub of the base pointer node into a
11084 /// post-indexed load/store. The transformation folded the add/subtract into the
11085 /// new indexed load/store effectively and all of its uses are redirected to the
11086 /// new load/store.
11087 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11088   if (Level < AfterLegalizeDAG)
11089     return false;
11090
11091   bool isLoad = true;
11092   SDValue Ptr;
11093   EVT VT;
11094   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11095     if (LD->isIndexed())
11096       return false;
11097     VT = LD->getMemoryVT();
11098     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11099         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11100       return false;
11101     Ptr = LD->getBasePtr();
11102   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11103     if (ST->isIndexed())
11104       return false;
11105     VT = ST->getMemoryVT();
11106     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11107         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11108       return false;
11109     Ptr = ST->getBasePtr();
11110     isLoad = false;
11111   } else {
11112     return false;
11113   }
11114
11115   if (Ptr.getNode()->hasOneUse())
11116     return false;
11117
11118   for (SDNode *Op : Ptr.getNode()->uses()) {
11119     if (Op == N ||
11120         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11121       continue;
11122
11123     SDValue BasePtr;
11124     SDValue Offset;
11125     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11126     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11127       // Don't create a indexed load / store with zero offset.
11128       if (isNullConstant(Offset))
11129         continue;
11130
11131       // Try turning it into a post-indexed load / store except when
11132       // 1) All uses are load / store ops that use it as base ptr (and
11133       //    it may be folded as addressing mmode).
11134       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11135       //    nor a successor of N. Otherwise, if Op is folded that would
11136       //    create a cycle.
11137
11138       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11139         continue;
11140
11141       // Check for #1.
11142       bool TryNext = false;
11143       for (SDNode *Use : BasePtr.getNode()->uses()) {
11144         if (Use == Ptr.getNode())
11145           continue;
11146
11147         // If all the uses are load / store addresses, then don't do the
11148         // transformation.
11149         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11150           bool RealUse = false;
11151           for (SDNode *UseUse : Use->uses()) {
11152             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11153               RealUse = true;
11154           }
11155
11156           if (!RealUse) {
11157             TryNext = true;
11158             break;
11159           }
11160         }
11161       }
11162
11163       if (TryNext)
11164         continue;
11165
11166       // Check for #2
11167       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11168         SDValue Result = isLoad
11169           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11170                                BasePtr, Offset, AM)
11171           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11172                                 BasePtr, Offset, AM);
11173         ++PostIndexedNodes;
11174         ++NodesCombined;
11175         DEBUG(dbgs() << "\nReplacing.5 ";
11176               N->dump(&DAG);
11177               dbgs() << "\nWith: ";
11178               Result.getNode()->dump(&DAG);
11179               dbgs() << '\n');
11180         WorklistRemover DeadNodes(*this);
11181         if (isLoad) {
11182           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11183           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11184         } else {
11185           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11186         }
11187
11188         // Finally, since the node is now dead, remove it from the graph.
11189         deleteAndRecombine(N);
11190
11191         // Replace the uses of Use with uses of the updated base value.
11192         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11193                                       Result.getValue(isLoad ? 1 : 0));
11194         deleteAndRecombine(Op);
11195         return true;
11196       }
11197     }
11198   }
11199
11200   return false;
11201 }
11202
11203 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11204 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11205   ISD::MemIndexedMode AM = LD->getAddressingMode();
11206   assert(AM != ISD::UNINDEXED);
11207   SDValue BP = LD->getOperand(1);
11208   SDValue Inc = LD->getOperand(2);
11209
11210   // Some backends use TargetConstants for load offsets, but don't expect
11211   // TargetConstants in general ADD nodes. We can convert these constants into
11212   // regular Constants (if the constant is not opaque).
11213   assert((Inc.getOpcode() != ISD::TargetConstant ||
11214           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11215          "Cannot split out indexing using opaque target constants");
11216   if (Inc.getOpcode() == ISD::TargetConstant) {
11217     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11218     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11219                           ConstInc->getValueType(0));
11220   }
11221
11222   unsigned Opc =
11223       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11224   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11225 }
11226
11227 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11228   LoadSDNode *LD  = cast<LoadSDNode>(N);
11229   SDValue Chain = LD->getChain();
11230   SDValue Ptr   = LD->getBasePtr();
11231
11232   // If load is not volatile and there are no uses of the loaded value (and
11233   // the updated indexed value in case of indexed loads), change uses of the
11234   // chain value into uses of the chain input (i.e. delete the dead load).
11235   if (!LD->isVolatile()) {
11236     if (N->getValueType(1) == MVT::Other) {
11237       // Unindexed loads.
11238       if (!N->hasAnyUseOfValue(0)) {
11239         // It's not safe to use the two value CombineTo variant here. e.g.
11240         // v1, chain2 = load chain1, loc
11241         // v2, chain3 = load chain2, loc
11242         // v3         = add v2, c
11243         // Now we replace use of chain2 with chain1.  This makes the second load
11244         // isomorphic to the one we are deleting, and thus makes this load live.
11245         DEBUG(dbgs() << "\nReplacing.6 ";
11246               N->dump(&DAG);
11247               dbgs() << "\nWith chain: ";
11248               Chain.getNode()->dump(&DAG);
11249               dbgs() << "\n");
11250         WorklistRemover DeadNodes(*this);
11251         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11252         AddUsersToWorklist(Chain.getNode());
11253         if (N->use_empty())
11254           deleteAndRecombine(N);
11255
11256         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11257       }
11258     } else {
11259       // Indexed loads.
11260       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11261
11262       // If this load has an opaque TargetConstant offset, then we cannot split
11263       // the indexing into an add/sub directly (that TargetConstant may not be
11264       // valid for a different type of node, and we cannot convert an opaque
11265       // target constant into a regular constant).
11266       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11267                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11268
11269       if (!N->hasAnyUseOfValue(0) &&
11270           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11271         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11272         SDValue Index;
11273         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11274           Index = SplitIndexingFromLoad(LD);
11275           // Try to fold the base pointer arithmetic into subsequent loads and
11276           // stores.
11277           AddUsersToWorklist(N);
11278         } else
11279           Index = DAG.getUNDEF(N->getValueType(1));
11280         DEBUG(dbgs() << "\nReplacing.7 ";
11281               N->dump(&DAG);
11282               dbgs() << "\nWith: ";
11283               Undef.getNode()->dump(&DAG);
11284               dbgs() << " and 2 other values\n");
11285         WorklistRemover DeadNodes(*this);
11286         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11287         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11288         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11289         deleteAndRecombine(N);
11290         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11291       }
11292     }
11293   }
11294
11295   // If this load is directly stored, replace the load value with the stored
11296   // value.
11297   // TODO: Handle store large -> read small portion.
11298   // TODO: Handle TRUNCSTORE/LOADEXT
11299   if (OptLevel != CodeGenOpt::None &&
11300       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11301     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11302       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11303       if (PrevST->getBasePtr() == Ptr &&
11304           PrevST->getValue().getValueType() == N->getValueType(0))
11305         return CombineTo(N, PrevST->getOperand(1), Chain);
11306     }
11307   }
11308
11309   // Try to infer better alignment information than the load already has.
11310   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11311     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11312       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11313         SDValue NewLoad = DAG.getExtLoad(
11314             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11315             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11316             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11317         if (NewLoad.getNode() != N)
11318           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11319       }
11320     }
11321   }
11322
11323   if (LD->isUnindexed()) {
11324     // Walk up chain skipping non-aliasing memory nodes.
11325     SDValue BetterChain = FindBetterChain(N, Chain);
11326
11327     // If there is a better chain.
11328     if (Chain != BetterChain) {
11329       SDValue ReplLoad;
11330
11331       // Replace the chain to void dependency.
11332       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11333         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11334                                BetterChain, Ptr, LD->getMemOperand());
11335       } else {
11336         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11337                                   LD->getValueType(0),
11338                                   BetterChain, Ptr, LD->getMemoryVT(),
11339                                   LD->getMemOperand());
11340       }
11341
11342       // Create token factor to keep old chain connected.
11343       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11344                                   MVT::Other, Chain, ReplLoad.getValue(1));
11345
11346       // Make sure the new and old chains are cleaned up.
11347       AddToWorklist(Token.getNode());
11348
11349       // Replace uses with load result and token factor. Don't add users
11350       // to work list.
11351       return CombineTo(N, ReplLoad.getValue(0), Token, false);
11352     }
11353   }
11354
11355   // Try transforming N to an indexed load.
11356   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11357     return SDValue(N, 0);
11358
11359   // Try to slice up N to more direct loads if the slices are mapped to
11360   // different register banks or pairing can take place.
11361   if (SliceUpLoad(N))
11362     return SDValue(N, 0);
11363
11364   return SDValue();
11365 }
11366
11367 namespace {
11368 /// \brief Helper structure used to slice a load in smaller loads.
11369 /// Basically a slice is obtained from the following sequence:
11370 /// Origin = load Ty1, Base
11371 /// Shift = srl Ty1 Origin, CstTy Amount
11372 /// Inst = trunc Shift to Ty2
11373 ///
11374 /// Then, it will be rewriten into:
11375 /// Slice = load SliceTy, Base + SliceOffset
11376 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11377 ///
11378 /// SliceTy is deduced from the number of bits that are actually used to
11379 /// build Inst.
11380 struct LoadedSlice {
11381   /// \brief Helper structure used to compute the cost of a slice.
11382   struct Cost {
11383     /// Are we optimizing for code size.
11384     bool ForCodeSize;
11385     /// Various cost.
11386     unsigned Loads;
11387     unsigned Truncates;
11388     unsigned CrossRegisterBanksCopies;
11389     unsigned ZExts;
11390     unsigned Shift;
11391
11392     Cost(bool ForCodeSize = false)
11393         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11394           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11395
11396     /// \brief Get the cost of one isolated slice.
11397     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11398         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11399           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11400       EVT TruncType = LS.Inst->getValueType(0);
11401       EVT LoadedType = LS.getLoadedType();
11402       if (TruncType != LoadedType &&
11403           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11404         ZExts = 1;
11405     }
11406
11407     /// \brief Account for slicing gain in the current cost.
11408     /// Slicing provide a few gains like removing a shift or a
11409     /// truncate. This method allows to grow the cost of the original
11410     /// load with the gain from this slice.
11411     void addSliceGain(const LoadedSlice &LS) {
11412       // Each slice saves a truncate.
11413       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11414       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11415                               LS.Inst->getValueType(0)))
11416         ++Truncates;
11417       // If there is a shift amount, this slice gets rid of it.
11418       if (LS.Shift)
11419         ++Shift;
11420       // If this slice can merge a cross register bank copy, account for it.
11421       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11422         ++CrossRegisterBanksCopies;
11423     }
11424
11425     Cost &operator+=(const Cost &RHS) {
11426       Loads += RHS.Loads;
11427       Truncates += RHS.Truncates;
11428       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11429       ZExts += RHS.ZExts;
11430       Shift += RHS.Shift;
11431       return *this;
11432     }
11433
11434     bool operator==(const Cost &RHS) const {
11435       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11436              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11437              ZExts == RHS.ZExts && Shift == RHS.Shift;
11438     }
11439
11440     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11441
11442     bool operator<(const Cost &RHS) const {
11443       // Assume cross register banks copies are as expensive as loads.
11444       // FIXME: Do we want some more target hooks?
11445       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11446       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11447       // Unless we are optimizing for code size, consider the
11448       // expensive operation first.
11449       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11450         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11451       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11452              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11453     }
11454
11455     bool operator>(const Cost &RHS) const { return RHS < *this; }
11456
11457     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11458
11459     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11460   };
11461   // The last instruction that represent the slice. This should be a
11462   // truncate instruction.
11463   SDNode *Inst;
11464   // The original load instruction.
11465   LoadSDNode *Origin;
11466   // The right shift amount in bits from the original load.
11467   unsigned Shift;
11468   // The DAG from which Origin came from.
11469   // This is used to get some contextual information about legal types, etc.
11470   SelectionDAG *DAG;
11471
11472   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11473               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11474       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11475
11476   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11477   /// \return Result is \p BitWidth and has used bits set to 1 and
11478   ///         not used bits set to 0.
11479   APInt getUsedBits() const {
11480     // Reproduce the trunc(lshr) sequence:
11481     // - Start from the truncated value.
11482     // - Zero extend to the desired bit width.
11483     // - Shift left.
11484     assert(Origin && "No original load to compare against.");
11485     unsigned BitWidth = Origin->getValueSizeInBits(0);
11486     assert(Inst && "This slice is not bound to an instruction");
11487     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11488            "Extracted slice is bigger than the whole type!");
11489     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11490     UsedBits.setAllBits();
11491     UsedBits = UsedBits.zext(BitWidth);
11492     UsedBits <<= Shift;
11493     return UsedBits;
11494   }
11495
11496   /// \brief Get the size of the slice to be loaded in bytes.
11497   unsigned getLoadedSize() const {
11498     unsigned SliceSize = getUsedBits().countPopulation();
11499     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11500     return SliceSize / 8;
11501   }
11502
11503   /// \brief Get the type that will be loaded for this slice.
11504   /// Note: This may not be the final type for the slice.
11505   EVT getLoadedType() const {
11506     assert(DAG && "Missing context");
11507     LLVMContext &Ctxt = *DAG->getContext();
11508     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11509   }
11510
11511   /// \brief Get the alignment of the load used for this slice.
11512   unsigned getAlignment() const {
11513     unsigned Alignment = Origin->getAlignment();
11514     unsigned Offset = getOffsetFromBase();
11515     if (Offset != 0)
11516       Alignment = MinAlign(Alignment, Alignment + Offset);
11517     return Alignment;
11518   }
11519
11520   /// \brief Check if this slice can be rewritten with legal operations.
11521   bool isLegal() const {
11522     // An invalid slice is not legal.
11523     if (!Origin || !Inst || !DAG)
11524       return false;
11525
11526     // Offsets are for indexed load only, we do not handle that.
11527     if (!Origin->getOffset().isUndef())
11528       return false;
11529
11530     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11531
11532     // Check that the type is legal.
11533     EVT SliceType = getLoadedType();
11534     if (!TLI.isTypeLegal(SliceType))
11535       return false;
11536
11537     // Check that the load is legal for this type.
11538     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11539       return false;
11540
11541     // Check that the offset can be computed.
11542     // 1. Check its type.
11543     EVT PtrType = Origin->getBasePtr().getValueType();
11544     if (PtrType == MVT::Untyped || PtrType.isExtended())
11545       return false;
11546
11547     // 2. Check that it fits in the immediate.
11548     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11549       return false;
11550
11551     // 3. Check that the computation is legal.
11552     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11553       return false;
11554
11555     // Check that the zext is legal if it needs one.
11556     EVT TruncateType = Inst->getValueType(0);
11557     if (TruncateType != SliceType &&
11558         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11559       return false;
11560
11561     return true;
11562   }
11563
11564   /// \brief Get the offset in bytes of this slice in the original chunk of
11565   /// bits.
11566   /// \pre DAG != nullptr.
11567   uint64_t getOffsetFromBase() const {
11568     assert(DAG && "Missing context.");
11569     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11570     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11571     uint64_t Offset = Shift / 8;
11572     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11573     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11574            "The size of the original loaded type is not a multiple of a"
11575            " byte.");
11576     // If Offset is bigger than TySizeInBytes, it means we are loading all
11577     // zeros. This should have been optimized before in the process.
11578     assert(TySizeInBytes > Offset &&
11579            "Invalid shift amount for given loaded size");
11580     if (IsBigEndian)
11581       Offset = TySizeInBytes - Offset - getLoadedSize();
11582     return Offset;
11583   }
11584
11585   /// \brief Generate the sequence of instructions to load the slice
11586   /// represented by this object and redirect the uses of this slice to
11587   /// this new sequence of instructions.
11588   /// \pre this->Inst && this->Origin are valid Instructions and this
11589   /// object passed the legal check: LoadedSlice::isLegal returned true.
11590   /// \return The last instruction of the sequence used to load the slice.
11591   SDValue loadSlice() const {
11592     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11593     const SDValue &OldBaseAddr = Origin->getBasePtr();
11594     SDValue BaseAddr = OldBaseAddr;
11595     // Get the offset in that chunk of bytes w.r.t. the endianness.
11596     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11597     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11598     if (Offset) {
11599       // BaseAddr = BaseAddr + Offset.
11600       EVT ArithType = BaseAddr.getValueType();
11601       SDLoc DL(Origin);
11602       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11603                               DAG->getConstant(Offset, DL, ArithType));
11604     }
11605
11606     // Create the type of the loaded slice according to its size.
11607     EVT SliceType = getLoadedType();
11608
11609     // Create the load for the slice.
11610     SDValue LastInst =
11611         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11612                      Origin->getPointerInfo().getWithOffset(Offset),
11613                      getAlignment(), Origin->getMemOperand()->getFlags());
11614     // If the final type is not the same as the loaded type, this means that
11615     // we have to pad with zero. Create a zero extend for that.
11616     EVT FinalType = Inst->getValueType(0);
11617     if (SliceType != FinalType)
11618       LastInst =
11619           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11620     return LastInst;
11621   }
11622
11623   /// \brief Check if this slice can be merged with an expensive cross register
11624   /// bank copy. E.g.,
11625   /// i = load i32
11626   /// f = bitcast i32 i to float
11627   bool canMergeExpensiveCrossRegisterBankCopy() const {
11628     if (!Inst || !Inst->hasOneUse())
11629       return false;
11630     SDNode *Use = *Inst->use_begin();
11631     if (Use->getOpcode() != ISD::BITCAST)
11632       return false;
11633     assert(DAG && "Missing context");
11634     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11635     EVT ResVT = Use->getValueType(0);
11636     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11637     const TargetRegisterClass *ArgRC =
11638         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11639     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11640       return false;
11641
11642     // At this point, we know that we perform a cross-register-bank copy.
11643     // Check if it is expensive.
11644     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11645     // Assume bitcasts are cheap, unless both register classes do not
11646     // explicitly share a common sub class.
11647     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11648       return false;
11649
11650     // Check if it will be merged with the load.
11651     // 1. Check the alignment constraint.
11652     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11653         ResVT.getTypeForEVT(*DAG->getContext()));
11654
11655     if (RequiredAlignment > getAlignment())
11656       return false;
11657
11658     // 2. Check that the load is a legal operation for that type.
11659     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11660       return false;
11661
11662     // 3. Check that we do not have a zext in the way.
11663     if (Inst->getValueType(0) != getLoadedType())
11664       return false;
11665
11666     return true;
11667   }
11668 };
11669 }
11670
11671 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11672 /// \p UsedBits looks like 0..0 1..1 0..0.
11673 static bool areUsedBitsDense(const APInt &UsedBits) {
11674   // If all the bits are one, this is dense!
11675   if (UsedBits.isAllOnesValue())
11676     return true;
11677
11678   // Get rid of the unused bits on the right.
11679   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11680   // Get rid of the unused bits on the left.
11681   if (NarrowedUsedBits.countLeadingZeros())
11682     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11683   // Check that the chunk of bits is completely used.
11684   return NarrowedUsedBits.isAllOnesValue();
11685 }
11686
11687 /// \brief Check whether or not \p First and \p Second are next to each other
11688 /// in memory. This means that there is no hole between the bits loaded
11689 /// by \p First and the bits loaded by \p Second.
11690 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11691                                      const LoadedSlice &Second) {
11692   assert(First.Origin == Second.Origin && First.Origin &&
11693          "Unable to match different memory origins.");
11694   APInt UsedBits = First.getUsedBits();
11695   assert((UsedBits & Second.getUsedBits()) == 0 &&
11696          "Slices are not supposed to overlap.");
11697   UsedBits |= Second.getUsedBits();
11698   return areUsedBitsDense(UsedBits);
11699 }
11700
11701 /// \brief Adjust the \p GlobalLSCost according to the target
11702 /// paring capabilities and the layout of the slices.
11703 /// \pre \p GlobalLSCost should account for at least as many loads as
11704 /// there is in the slices in \p LoadedSlices.
11705 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11706                                  LoadedSlice::Cost &GlobalLSCost) {
11707   unsigned NumberOfSlices = LoadedSlices.size();
11708   // If there is less than 2 elements, no pairing is possible.
11709   if (NumberOfSlices < 2)
11710     return;
11711
11712   // Sort the slices so that elements that are likely to be next to each
11713   // other in memory are next to each other in the list.
11714   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11715             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11716     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11717     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11718   });
11719   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11720   // First (resp. Second) is the first (resp. Second) potentially candidate
11721   // to be placed in a paired load.
11722   const LoadedSlice *First = nullptr;
11723   const LoadedSlice *Second = nullptr;
11724   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11725                 // Set the beginning of the pair.
11726                                                            First = Second) {
11727
11728     Second = &LoadedSlices[CurrSlice];
11729
11730     // If First is NULL, it means we start a new pair.
11731     // Get to the next slice.
11732     if (!First)
11733       continue;
11734
11735     EVT LoadedType = First->getLoadedType();
11736
11737     // If the types of the slices are different, we cannot pair them.
11738     if (LoadedType != Second->getLoadedType())
11739       continue;
11740
11741     // Check if the target supplies paired loads for this type.
11742     unsigned RequiredAlignment = 0;
11743     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11744       // move to the next pair, this type is hopeless.
11745       Second = nullptr;
11746       continue;
11747     }
11748     // Check if we meet the alignment requirement.
11749     if (RequiredAlignment > First->getAlignment())
11750       continue;
11751
11752     // Check that both loads are next to each other in memory.
11753     if (!areSlicesNextToEachOther(*First, *Second))
11754       continue;
11755
11756     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11757     --GlobalLSCost.Loads;
11758     // Move to the next pair.
11759     Second = nullptr;
11760   }
11761 }
11762
11763 /// \brief Check the profitability of all involved LoadedSlice.
11764 /// Currently, it is considered profitable if there is exactly two
11765 /// involved slices (1) which are (2) next to each other in memory, and
11766 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11767 ///
11768 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11769 /// the elements themselves.
11770 ///
11771 /// FIXME: When the cost model will be mature enough, we can relax
11772 /// constraints (1) and (2).
11773 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11774                                 const APInt &UsedBits, bool ForCodeSize) {
11775   unsigned NumberOfSlices = LoadedSlices.size();
11776   if (StressLoadSlicing)
11777     return NumberOfSlices > 1;
11778
11779   // Check (1).
11780   if (NumberOfSlices != 2)
11781     return false;
11782
11783   // Check (2).
11784   if (!areUsedBitsDense(UsedBits))
11785     return false;
11786
11787   // Check (3).
11788   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11789   // The original code has one big load.
11790   OrigCost.Loads = 1;
11791   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11792     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11793     // Accumulate the cost of all the slices.
11794     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11795     GlobalSlicingCost += SliceCost;
11796
11797     // Account as cost in the original configuration the gain obtained
11798     // with the current slices.
11799     OrigCost.addSliceGain(LS);
11800   }
11801
11802   // If the target supports paired load, adjust the cost accordingly.
11803   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11804   return OrigCost > GlobalSlicingCost;
11805 }
11806
11807 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11808 /// operations, split it in the various pieces being extracted.
11809 ///
11810 /// This sort of thing is introduced by SROA.
11811 /// This slicing takes care not to insert overlapping loads.
11812 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11813 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11814   if (Level < AfterLegalizeDAG)
11815     return false;
11816
11817   LoadSDNode *LD = cast<LoadSDNode>(N);
11818   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11819       !LD->getValueType(0).isInteger())
11820     return false;
11821
11822   // Keep track of already used bits to detect overlapping values.
11823   // In that case, we will just abort the transformation.
11824   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11825
11826   SmallVector<LoadedSlice, 4> LoadedSlices;
11827
11828   // Check if this load is used as several smaller chunks of bits.
11829   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11830   // of computation for each trunc.
11831   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11832        UI != UIEnd; ++UI) {
11833     // Skip the uses of the chain.
11834     if (UI.getUse().getResNo() != 0)
11835       continue;
11836
11837     SDNode *User = *UI;
11838     unsigned Shift = 0;
11839
11840     // Check if this is a trunc(lshr).
11841     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11842         isa<ConstantSDNode>(User->getOperand(1))) {
11843       Shift = User->getConstantOperandVal(1);
11844       User = *User->use_begin();
11845     }
11846
11847     // At this point, User is a Truncate, iff we encountered, trunc or
11848     // trunc(lshr).
11849     if (User->getOpcode() != ISD::TRUNCATE)
11850       return false;
11851
11852     // The width of the type must be a power of 2 and greater than 8-bits.
11853     // Otherwise the load cannot be represented in LLVM IR.
11854     // Moreover, if we shifted with a non-8-bits multiple, the slice
11855     // will be across several bytes. We do not support that.
11856     unsigned Width = User->getValueSizeInBits(0);
11857     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11858       return 0;
11859
11860     // Build the slice for this chain of computations.
11861     LoadedSlice LS(User, LD, Shift, &DAG);
11862     APInt CurrentUsedBits = LS.getUsedBits();
11863
11864     // Check if this slice overlaps with another.
11865     if ((CurrentUsedBits & UsedBits) != 0)
11866       return false;
11867     // Update the bits used globally.
11868     UsedBits |= CurrentUsedBits;
11869
11870     // Check if the new slice would be legal.
11871     if (!LS.isLegal())
11872       return false;
11873
11874     // Record the slice.
11875     LoadedSlices.push_back(LS);
11876   }
11877
11878   // Abort slicing if it does not seem to be profitable.
11879   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11880     return false;
11881
11882   ++SlicedLoads;
11883
11884   // Rewrite each chain to use an independent load.
11885   // By construction, each chain can be represented by a unique load.
11886
11887   // Prepare the argument for the new token factor for all the slices.
11888   SmallVector<SDValue, 8> ArgChains;
11889   for (SmallVectorImpl<LoadedSlice>::const_iterator
11890            LSIt = LoadedSlices.begin(),
11891            LSItEnd = LoadedSlices.end();
11892        LSIt != LSItEnd; ++LSIt) {
11893     SDValue SliceInst = LSIt->loadSlice();
11894     CombineTo(LSIt->Inst, SliceInst, true);
11895     if (SliceInst.getOpcode() != ISD::LOAD)
11896       SliceInst = SliceInst.getOperand(0);
11897     assert(SliceInst->getOpcode() == ISD::LOAD &&
11898            "It takes more than a zext to get to the loaded slice!!");
11899     ArgChains.push_back(SliceInst.getValue(1));
11900   }
11901
11902   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11903                               ArgChains);
11904   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11905   AddToWorklist(Chain.getNode());
11906   return true;
11907 }
11908
11909 /// Check to see if V is (and load (ptr), imm), where the load is having
11910 /// specific bytes cleared out.  If so, return the byte size being masked out
11911 /// and the shift amount.
11912 static std::pair<unsigned, unsigned>
11913 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11914   std::pair<unsigned, unsigned> Result(0, 0);
11915
11916   // Check for the structure we're looking for.
11917   if (V->getOpcode() != ISD::AND ||
11918       !isa<ConstantSDNode>(V->getOperand(1)) ||
11919       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11920     return Result;
11921
11922   // Check the chain and pointer.
11923   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11924   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11925
11926   // The store should be chained directly to the load or be an operand of a
11927   // tokenfactor.
11928   if (LD == Chain.getNode())
11929     ; // ok.
11930   else if (Chain->getOpcode() != ISD::TokenFactor)
11931     return Result; // Fail.
11932   else {
11933     bool isOk = false;
11934     for (const SDValue &ChainOp : Chain->op_values())
11935       if (ChainOp.getNode() == LD) {
11936         isOk = true;
11937         break;
11938       }
11939     if (!isOk) return Result;
11940   }
11941
11942   // This only handles simple types.
11943   if (V.getValueType() != MVT::i16 &&
11944       V.getValueType() != MVT::i32 &&
11945       V.getValueType() != MVT::i64)
11946     return Result;
11947
11948   // Check the constant mask.  Invert it so that the bits being masked out are
11949   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
11950   // follow the sign bit for uniformity.
11951   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11952   unsigned NotMaskLZ = countLeadingZeros(NotMask);
11953   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
11954   unsigned NotMaskTZ = countTrailingZeros(NotMask);
11955   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
11956   if (NotMaskLZ == 64) return Result;  // All zero mask.
11957
11958   // See if we have a continuous run of bits.  If so, we have 0*1+0*
11959   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11960     return Result;
11961
11962   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11963   if (V.getValueType() != MVT::i64 && NotMaskLZ)
11964     NotMaskLZ -= 64-V.getValueSizeInBits();
11965
11966   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11967   switch (MaskedBytes) {
11968   case 1:
11969   case 2:
11970   case 4: break;
11971   default: return Result; // All one mask, or 5-byte mask.
11972   }
11973
11974   // Verify that the first bit starts at a multiple of mask so that the access
11975   // is aligned the same as the access width.
11976   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11977
11978   Result.first = MaskedBytes;
11979   Result.second = NotMaskTZ/8;
11980   return Result;
11981 }
11982
11983
11984 /// Check to see if IVal is something that provides a value as specified by
11985 /// MaskInfo. If so, replace the specified store with a narrower store of
11986 /// truncated IVal.
11987 static SDNode *
11988 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11989                                 SDValue IVal, StoreSDNode *St,
11990                                 DAGCombiner *DC) {
11991   unsigned NumBytes = MaskInfo.first;
11992   unsigned ByteShift = MaskInfo.second;
11993   SelectionDAG &DAG = DC->getDAG();
11994
11995   // Check to see if IVal is all zeros in the part being masked in by the 'or'
11996   // that uses this.  If not, this is not a replacement.
11997   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11998                                   ByteShift*8, (ByteShift+NumBytes)*8);
11999   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12000
12001   // Check that it is legal on the target to do this.  It is legal if the new
12002   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12003   // legalization.
12004   MVT VT = MVT::getIntegerVT(NumBytes*8);
12005   if (!DC->isTypeLegal(VT))
12006     return nullptr;
12007
12008   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12009   // shifted by ByteShift and truncated down to NumBytes.
12010   if (ByteShift) {
12011     SDLoc DL(IVal);
12012     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12013                        DAG.getConstant(ByteShift*8, DL,
12014                                     DC->getShiftAmountTy(IVal.getValueType())));
12015   }
12016
12017   // Figure out the offset for the store and the alignment of the access.
12018   unsigned StOffset;
12019   unsigned NewAlign = St->getAlignment();
12020
12021   if (DAG.getDataLayout().isLittleEndian())
12022     StOffset = ByteShift;
12023   else
12024     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12025
12026   SDValue Ptr = St->getBasePtr();
12027   if (StOffset) {
12028     SDLoc DL(IVal);
12029     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12030                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12031     NewAlign = MinAlign(NewAlign, StOffset);
12032   }
12033
12034   // Truncate down to the new size.
12035   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12036
12037   ++OpsNarrowed;
12038   return DAG
12039       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12040                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12041       .getNode();
12042 }
12043
12044
12045 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12046 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12047 /// narrowing the load and store if it would end up being a win for performance
12048 /// or code size.
12049 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12050   StoreSDNode *ST  = cast<StoreSDNode>(N);
12051   if (ST->isVolatile())
12052     return SDValue();
12053
12054   SDValue Chain = ST->getChain();
12055   SDValue Value = ST->getValue();
12056   SDValue Ptr   = ST->getBasePtr();
12057   EVT VT = Value.getValueType();
12058
12059   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12060     return SDValue();
12061
12062   unsigned Opc = Value.getOpcode();
12063
12064   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12065   // is a byte mask indicating a consecutive number of bytes, check to see if
12066   // Y is known to provide just those bytes.  If so, we try to replace the
12067   // load + replace + store sequence with a single (narrower) store, which makes
12068   // the load dead.
12069   if (Opc == ISD::OR) {
12070     std::pair<unsigned, unsigned> MaskedLoad;
12071     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12072     if (MaskedLoad.first)
12073       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12074                                                   Value.getOperand(1), ST,this))
12075         return SDValue(NewST, 0);
12076
12077     // Or is commutative, so try swapping X and Y.
12078     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12079     if (MaskedLoad.first)
12080       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12081                                                   Value.getOperand(0), ST,this))
12082         return SDValue(NewST, 0);
12083   }
12084
12085   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12086       Value.getOperand(1).getOpcode() != ISD::Constant)
12087     return SDValue();
12088
12089   SDValue N0 = Value.getOperand(0);
12090   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12091       Chain == SDValue(N0.getNode(), 1)) {
12092     LoadSDNode *LD = cast<LoadSDNode>(N0);
12093     if (LD->getBasePtr() != Ptr ||
12094         LD->getPointerInfo().getAddrSpace() !=
12095         ST->getPointerInfo().getAddrSpace())
12096       return SDValue();
12097
12098     // Find the type to narrow it the load / op / store to.
12099     SDValue N1 = Value.getOperand(1);
12100     unsigned BitWidth = N1.getValueSizeInBits();
12101     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12102     if (Opc == ISD::AND)
12103       Imm ^= APInt::getAllOnesValue(BitWidth);
12104     if (Imm == 0 || Imm.isAllOnesValue())
12105       return SDValue();
12106     unsigned ShAmt = Imm.countTrailingZeros();
12107     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12108     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12109     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12110     // The narrowing should be profitable, the load/store operation should be
12111     // legal (or custom) and the store size should be equal to the NewVT width.
12112     while (NewBW < BitWidth &&
12113            (NewVT.getStoreSizeInBits() != NewBW ||
12114             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12115             !TLI.isNarrowingProfitable(VT, NewVT))) {
12116       NewBW = NextPowerOf2(NewBW);
12117       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12118     }
12119     if (NewBW >= BitWidth)
12120       return SDValue();
12121
12122     // If the lsb changed does not start at the type bitwidth boundary,
12123     // start at the previous one.
12124     if (ShAmt % NewBW)
12125       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12126     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12127                                    std::min(BitWidth, ShAmt + NewBW));
12128     if ((Imm & Mask) == Imm) {
12129       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12130       if (Opc == ISD::AND)
12131         NewImm ^= APInt::getAllOnesValue(NewBW);
12132       uint64_t PtrOff = ShAmt / 8;
12133       // For big endian targets, we need to adjust the offset to the pointer to
12134       // load the correct bytes.
12135       if (DAG.getDataLayout().isBigEndian())
12136         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12137
12138       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12139       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12140       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12141         return SDValue();
12142
12143       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12144                                    Ptr.getValueType(), Ptr,
12145                                    DAG.getConstant(PtrOff, SDLoc(LD),
12146                                                    Ptr.getValueType()));
12147       SDValue NewLD =
12148           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12149                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12150                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12151       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12152                                    DAG.getConstant(NewImm, SDLoc(Value),
12153                                                    NewVT));
12154       SDValue NewST =
12155           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12156                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12157
12158       AddToWorklist(NewPtr.getNode());
12159       AddToWorklist(NewLD.getNode());
12160       AddToWorklist(NewVal.getNode());
12161       WorklistRemover DeadNodes(*this);
12162       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12163       ++OpsNarrowed;
12164       return NewST;
12165     }
12166   }
12167
12168   return SDValue();
12169 }
12170
12171 /// For a given floating point load / store pair, if the load value isn't used
12172 /// by any other operations, then consider transforming the pair to integer
12173 /// load / store operations if the target deems the transformation profitable.
12174 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12175   StoreSDNode *ST  = cast<StoreSDNode>(N);
12176   SDValue Chain = ST->getChain();
12177   SDValue Value = ST->getValue();
12178   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12179       Value.hasOneUse() &&
12180       Chain == SDValue(Value.getNode(), 1)) {
12181     LoadSDNode *LD = cast<LoadSDNode>(Value);
12182     EVT VT = LD->getMemoryVT();
12183     if (!VT.isFloatingPoint() ||
12184         VT != ST->getMemoryVT() ||
12185         LD->isNonTemporal() ||
12186         ST->isNonTemporal() ||
12187         LD->getPointerInfo().getAddrSpace() != 0 ||
12188         ST->getPointerInfo().getAddrSpace() != 0)
12189       return SDValue();
12190
12191     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12192     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12193         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12194         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12195         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12196       return SDValue();
12197
12198     unsigned LDAlign = LD->getAlignment();
12199     unsigned STAlign = ST->getAlignment();
12200     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12201     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12202     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12203       return SDValue();
12204
12205     SDValue NewLD =
12206         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12207                     LD->getPointerInfo(), LDAlign);
12208
12209     SDValue NewST =
12210         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12211                      ST->getPointerInfo(), STAlign);
12212
12213     AddToWorklist(NewLD.getNode());
12214     AddToWorklist(NewST.getNode());
12215     WorklistRemover DeadNodes(*this);
12216     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12217     ++LdStFP2Int;
12218     return NewST;
12219   }
12220
12221   return SDValue();
12222 }
12223
12224 // This is a helper function for visitMUL to check the profitability
12225 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12226 // MulNode is the original multiply, AddNode is (add x, c1),
12227 // and ConstNode is c2.
12228 //
12229 // If the (add x, c1) has multiple uses, we could increase
12230 // the number of adds if we make this transformation.
12231 // It would only be worth doing this if we can remove a
12232 // multiply in the process. Check for that here.
12233 // To illustrate:
12234 //     (A + c1) * c3
12235 //     (A + c2) * c3
12236 // We're checking for cases where we have common "c3 * A" expressions.
12237 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12238                                               SDValue &AddNode,
12239                                               SDValue &ConstNode) {
12240   APInt Val;
12241
12242   // If the add only has one use, this would be OK to do.
12243   if (AddNode.getNode()->hasOneUse())
12244     return true;
12245
12246   // Walk all the users of the constant with which we're multiplying.
12247   for (SDNode *Use : ConstNode->uses()) {
12248
12249     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12250       continue;
12251
12252     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12253       SDNode *OtherOp;
12254       SDNode *MulVar = AddNode.getOperand(0).getNode();
12255
12256       // OtherOp is what we're multiplying against the constant.
12257       if (Use->getOperand(0) == ConstNode)
12258         OtherOp = Use->getOperand(1).getNode();
12259       else
12260         OtherOp = Use->getOperand(0).getNode();
12261
12262       // Check to see if multiply is with the same operand of our "add".
12263       //
12264       //     ConstNode  = CONST
12265       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12266       //     ...
12267       //     AddNode  = (A + c1)  <-- MulVar is A.
12268       //         = AddNode * ConstNode   <-- current visiting instruction.
12269       //
12270       // If we make this transformation, we will have a common
12271       // multiply (ConstNode * A) that we can save.
12272       if (OtherOp == MulVar)
12273         return true;
12274
12275       // Now check to see if a future expansion will give us a common
12276       // multiply.
12277       //
12278       //     ConstNode  = CONST
12279       //     AddNode    = (A + c1)
12280       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12281       //     ...
12282       //     OtherOp = (A + c2)
12283       //     Use     = OtherOp * ConstNode <-- visiting Use.
12284       //
12285       // If we make this transformation, we will have a common
12286       // multiply (CONST * A) after we also do the same transformation
12287       // to the "t2" instruction.
12288       if (OtherOp->getOpcode() == ISD::ADD &&
12289           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12290           OtherOp->getOperand(0).getNode() == MulVar)
12291         return true;
12292     }
12293   }
12294
12295   // Didn't find a case where this would be profitable.
12296   return false;
12297 }
12298
12299 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12300                                          unsigned NumStores) {
12301   SmallVector<SDValue, 8> Chains;
12302   SmallPtrSet<const SDNode *, 8> Visited;
12303   SDLoc StoreDL(StoreNodes[0].MemNode);
12304
12305   for (unsigned i = 0; i < NumStores; ++i) {
12306     Visited.insert(StoreNodes[i].MemNode);
12307   }
12308
12309   // don't include nodes that are children
12310   for (unsigned i = 0; i < NumStores; ++i) {
12311     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12312       Chains.push_back(StoreNodes[i].MemNode->getChain());
12313   }
12314
12315   assert(Chains.size() > 0 && "Chain should have generated a chain");
12316   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12317 }
12318
12319 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12320                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12321                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12322   // Make sure we have something to merge.
12323   if (NumStores < 2)
12324     return false;
12325
12326   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12327
12328   // The latest Node in the DAG.
12329   SDLoc DL(StoreNodes[0].MemNode);
12330
12331   SDValue StoredVal;
12332   if (UseVector) {
12333     bool IsVec = MemVT.isVector();
12334     unsigned Elts = NumStores;
12335     if (IsVec) {
12336       // When merging vector stores, get the total number of elements.
12337       Elts *= MemVT.getVectorNumElements();
12338     }
12339     // Get the type for the merged vector store.
12340     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12341     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12342
12343     if (IsConstantSrc) {
12344       SmallVector<SDValue, 8> BuildVector;
12345       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12346         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12347         SDValue Val = St->getValue();
12348         if (MemVT.getScalarType().isInteger())
12349           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12350             Val = DAG.getConstant(
12351                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12352                 SDLoc(CFP), MemVT);
12353         BuildVector.push_back(Val);
12354       }
12355       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12356     } else {
12357       SmallVector<SDValue, 8> Ops;
12358       for (unsigned i = 0; i < NumStores; ++i) {
12359         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12360         SDValue Val = St->getValue();
12361         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12362         if (Val.getValueType() != MemVT)
12363           return false;
12364         Ops.push_back(Val);
12365       }
12366
12367       // Build the extracted vector elements back into a vector.
12368       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12369                               DL, Ty, Ops);    }
12370   } else {
12371     // We should always use a vector store when merging extracted vector
12372     // elements, so this path implies a store of constants.
12373     assert(IsConstantSrc && "Merged vector elements should use vector store");
12374
12375     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12376     APInt StoreInt(SizeInBits, 0);
12377
12378     // Construct a single integer constant which is made of the smaller
12379     // constant inputs.
12380     bool IsLE = DAG.getDataLayout().isLittleEndian();
12381     for (unsigned i = 0; i < NumStores; ++i) {
12382       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12383       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12384
12385       SDValue Val = St->getValue();
12386       StoreInt <<= ElementSizeBytes * 8;
12387       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12388         StoreInt |= C->getAPIntValue().zext(SizeInBits);
12389       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12390         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
12391       } else {
12392         llvm_unreachable("Invalid constant element type");
12393       }
12394     }
12395
12396     // Create the new Load and Store operations.
12397     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12398     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12399   }
12400
12401   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12402   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12403   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12404                                   FirstInChain->getBasePtr(),
12405                                   FirstInChain->getPointerInfo(),
12406                                   FirstInChain->getAlignment());
12407
12408   // Replace all merged stores with the new store.
12409   for (unsigned i = 0; i < NumStores; ++i)
12410     CombineTo(StoreNodes[i].MemNode, NewStore);
12411
12412   AddToWorklist(NewChain.getNode());
12413   return true;
12414 }
12415
12416 void DAGCombiner::getStoreMergeCandidates(
12417     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12418   // This holds the base pointer, index, and the offset in bytes from the base
12419   // pointer.
12420   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12421   EVT MemVT = St->getMemoryVT();
12422
12423   // We must have a base and an offset.
12424   if (!BasePtr.Base.getNode())
12425     return;
12426
12427   // Do not handle stores to undef base pointers.
12428   if (BasePtr.Base.isUndef())
12429     return;
12430
12431   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12432   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12433                        isa<ConstantFPSDNode>(St->getValue());
12434   bool IsExtractVecSrc =
12435       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12436        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12437   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12438     if (Other->isVolatile() || Other->isIndexed())
12439       return false;
12440     // We can merge constant floats to equivalent integers
12441     if (Other->getMemoryVT() != MemVT)
12442       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12443             isa<ConstantFPSDNode>(Other->getValue())))
12444         return false;
12445     if (IsLoadSrc)
12446       if (!isa<LoadSDNode>(Other->getValue()))
12447         return false;
12448     if (IsConstantSrc)
12449       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12450             isa<ConstantFPSDNode>(Other->getValue())))
12451         return false;
12452     if (IsExtractVecSrc)
12453       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12454             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12455         return false;
12456     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12457     return (Ptr.equalBaseIndex(BasePtr));
12458   };
12459   // We looking for a root node which is an ancestor to all mergable
12460   // stores. We search up through a load, to our root and then down
12461   // through all children. For instance we will find Store{1,2,3} if
12462   // St is Store1, Store2. or Store3 where the root is not a load
12463   // which always true for nonvolatile ops. TODO: Expand
12464   // the search to find all valid candidates through multiple layers of loads.
12465   //
12466   // Root
12467   // |-------|-------|
12468   // Load    Load    Store3
12469   // |       |
12470   // Store1   Store2
12471   //
12472   // FIXME: We should be able to climb and
12473   // descend TokenFactors to find candidates as well.
12474
12475   SDNode *RootNode = (St->getChain()).getNode();
12476
12477   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12478     RootNode = Ldn->getChain().getNode();
12479     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12480       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12481         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12482           if (I2.getOperandNo() == 0)
12483             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12484               BaseIndexOffset Ptr;
12485               if (CandidateMatch(OtherST, Ptr))
12486                 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12487             }
12488   } else
12489     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12490       if (I.getOperandNo() == 0)
12491         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12492           BaseIndexOffset Ptr;
12493           if (CandidateMatch(OtherST, Ptr))
12494             StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12495         }
12496 }
12497
12498 // We need to check that merging these stores does not cause a loop
12499 // in the DAG. Any store candidate may depend on another candidate
12500 // indirectly through its operand (we already consider dependencies
12501 // through the chain). Check in parallel by searching up from
12502 // non-chain operands of candidates.
12503 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12504     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12505   SmallPtrSet<const SDNode *, 16> Visited;
12506   SmallVector<const SDNode *, 8> Worklist;
12507   // search ops of store candidates
12508   for (unsigned i = 0; i < NumStores; ++i) {
12509     SDNode *n = StoreNodes[i].MemNode;
12510     // Potential loops may happen only through non-chain operands
12511     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12512       Worklist.push_back(n->getOperand(j).getNode());
12513   }
12514   // search through DAG. We can stop early if we find a storenode
12515   for (unsigned i = 0; i < NumStores; ++i) {
12516     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12517       return false;
12518   }
12519   return true;
12520 }
12521
12522 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12523   if (OptLevel == CodeGenOpt::None)
12524     return false;
12525
12526   EVT MemVT = St->getMemoryVT();
12527   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12528
12529   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12530     return false;
12531
12532   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12533       Attribute::NoImplicitFloat);
12534
12535   // This function cannot currently deal with non-byte-sized memory sizes.
12536   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12537     return false;
12538
12539   if (!MemVT.isSimple())
12540     return false;
12541
12542   // Perform an early exit check. Do not bother looking at stored values that
12543   // are not constants, loads, or extracted vector elements.
12544   SDValue StoredVal = St->getValue();
12545   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12546   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12547                        isa<ConstantFPSDNode>(StoredVal);
12548   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12549                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12550
12551   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12552     return false;
12553
12554   // Don't merge vectors into wider vectors if the source data comes from loads.
12555   // TODO: This restriction can be lifted by using logic similar to the
12556   // ExtractVecSrc case.
12557   if (MemVT.isVector() && IsLoadSrc)
12558     return false;
12559
12560   SmallVector<MemOpLink, 8> StoreNodes;
12561   // Find potential store merge candidates by searching through chain sub-DAG
12562   getStoreMergeCandidates(St, StoreNodes);
12563
12564   // Check if there is anything to merge.
12565   if (StoreNodes.size() < 2)
12566     return false;
12567
12568   // Sort the memory operands according to their distance from the
12569   // base pointer.
12570   std::sort(StoreNodes.begin(), StoreNodes.end(),
12571             [](MemOpLink LHS, MemOpLink RHS) {
12572               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12573             });
12574
12575   // Store Merge attempts to merge the lowest stores. This generally
12576   // works out as if successful, as the remaining stores are checked
12577   // after the first collection of stores is merged. However, in the
12578   // case that a non-mergeable store is found first, e.g., {p[-2],
12579   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12580   // mergeable cases. To prevent this, we prune such stores from the
12581   // front of StoreNodes here.
12582
12583   unsigned StartIdx = 0;
12584   while ((StartIdx + 1 < StoreNodes.size()) &&
12585          StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12586              StoreNodes[StartIdx + 1].OffsetFromBase)
12587     ++StartIdx;
12588
12589   // Bail if we don't have enough candidates to merge.
12590   if (StartIdx + 1 >= StoreNodes.size())
12591     return false;
12592
12593   if (StartIdx)
12594     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12595
12596   // Scan the memory operations on the chain and find the first non-consecutive
12597   // store memory address.
12598   unsigned NumConsecutiveStores = 0;
12599   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12600
12601   // Check that the addresses are consecutive starting from the second
12602   // element in the list of stores.
12603   for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12604     int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12605     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12606       break;
12607     NumConsecutiveStores = i + 1;
12608   }
12609
12610   if (NumConsecutiveStores < 2)
12611     return false;
12612
12613   // Check that we can merge these candidates without causing a cycle
12614   if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores))
12615     return false;
12616
12617
12618   // The node with the lowest store address.
12619   LLVMContext &Context = *DAG.getContext();
12620   const DataLayout &DL = DAG.getDataLayout();
12621
12622   // Store the constants into memory as one consecutive store.
12623   if (IsConstantSrc) {
12624     bool RV = false;
12625     while (NumConsecutiveStores > 1) {
12626       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12627       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12628       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12629       unsigned LastLegalType = 0;
12630       unsigned LastLegalVectorType = 0;
12631       bool NonZero = false;
12632       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12633         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12634         SDValue StoredVal = ST->getValue();
12635
12636         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12637           NonZero |= !C->isNullValue();
12638         } else if (ConstantFPSDNode *C =
12639                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12640           NonZero |= !C->getConstantFPValue()->isNullValue();
12641         } else {
12642           // Non-constant.
12643           break;
12644         }
12645
12646         // Find a legal type for the constant store.
12647         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12648         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12649         bool IsFast = false;
12650         if (TLI.isTypeLegal(StoreTy) &&
12651             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12652                                    FirstStoreAlign, &IsFast) &&
12653             IsFast) {
12654           LastLegalType = i + 1;
12655           // Or check whether a truncstore is legal.
12656         } else if (TLI.getTypeAction(Context, StoreTy) ==
12657                    TargetLowering::TypePromoteInteger) {
12658           EVT LegalizedStoredValueTy =
12659               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12660           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12661               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12662                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12663               IsFast) {
12664             LastLegalType = i + 1;
12665           }
12666         }
12667
12668         // We only use vectors if the constant is known to be zero or the target
12669         // allows it and the function is not marked with the noimplicitfloat
12670         // attribute.
12671         if ((!NonZero ||
12672              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12673             !NoVectors) {
12674           // Find a legal type for the vector store.
12675           EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12676           if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
12677               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12678                                      FirstStoreAlign, &IsFast) &&
12679               IsFast)
12680             LastLegalVectorType = i + 1;
12681         }
12682       }
12683
12684       // Check if we found a legal integer type that creates a meaningful merge.
12685       if (LastLegalType < 2 && LastLegalVectorType < 2)
12686         break;
12687
12688       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12689       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12690
12691       bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12692                                                     true, UseVector);
12693       if (!Merged)
12694         break;
12695       // Remove merged stores for next iteration.
12696       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12697       RV = true;
12698       NumConsecutiveStores -= NumElem;
12699     }
12700     return RV;
12701   }
12702
12703   // When extracting multiple vector elements, try to store them
12704   // in one vector store rather than a sequence of scalar stores.
12705   if (IsExtractVecSrc) {
12706     bool RV = false;
12707     while (StoreNodes.size() >= 2) {
12708       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12709       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12710       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12711       unsigned NumStoresToMerge = 0;
12712       bool IsVec = MemVT.isVector();
12713       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12714         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12715         unsigned StoreValOpcode = St->getValue().getOpcode();
12716         // This restriction could be loosened.
12717         // Bail out if any stored values are not elements extracted from a
12718         // vector. It should be possible to handle mixed sources, but load
12719         // sources need more careful handling (see the block of code below that
12720         // handles consecutive loads).
12721         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12722             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12723           return false;
12724
12725         // Find a legal type for the vector store.
12726         unsigned Elts = i + 1;
12727         if (IsVec) {
12728           // When merging vector stores, get the total number of elements.
12729           Elts *= MemVT.getVectorNumElements();
12730         }
12731         EVT Ty =
12732             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12733         bool IsFast;
12734         if (TLI.isTypeLegal(Ty) &&
12735             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12736                                    FirstStoreAlign, &IsFast) &&
12737             IsFast)
12738           NumStoresToMerge = i + 1;
12739       }
12740
12741       bool Merged = MergeStoresOfConstantsOrVecElts(
12742           StoreNodes, MemVT, NumStoresToMerge, false, true);
12743       if (!Merged)
12744         break;
12745       // Remove merged stores for next iteration.
12746       StoreNodes.erase(StoreNodes.begin(),
12747                        StoreNodes.begin() + NumStoresToMerge);
12748       RV = true;
12749       NumConsecutiveStores -= NumStoresToMerge;
12750     }
12751     return RV;
12752   }
12753
12754   // Below we handle the case of multiple consecutive stores that
12755   // come from multiple consecutive loads. We merge them into a single
12756   // wide load and a single wide store.
12757
12758   // Look for load nodes which are used by the stored values.
12759   SmallVector<MemOpLink, 8> LoadNodes;
12760
12761   // Find acceptable loads. Loads need to have the same chain (token factor),
12762   // must not be zext, volatile, indexed, and they must be consecutive.
12763   BaseIndexOffset LdBasePtr;
12764   for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12765     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
12766     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12767     if (!Ld) break;
12768
12769     // Loads must only have one use.
12770     if (!Ld->hasNUsesOfValue(1, 0))
12771       break;
12772
12773     // The memory operands must not be volatile.
12774     if (Ld->isVolatile() || Ld->isIndexed())
12775       break;
12776
12777     // We do not accept ext loads.
12778     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12779       break;
12780
12781     // The stored memory type must be the same.
12782     if (Ld->getMemoryVT() != MemVT)
12783       break;
12784
12785     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12786     // If this is not the first ptr that we check.
12787     if (LdBasePtr.Base.getNode()) {
12788       // The base ptr must be the same.
12789       if (!LdPtr.equalBaseIndex(LdBasePtr))
12790         break;
12791     } else {
12792       // Check that all other base pointers are the same as this one.
12793       LdBasePtr = LdPtr;
12794     }
12795
12796     // We found a potential memory operand to merge.
12797     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12798   }
12799
12800   if (LoadNodes.size() < 2)
12801     return false;
12802
12803   // If we have load/store pair instructions and we only have two values,
12804   // don't bother.
12805   unsigned RequiredAlignment;
12806   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12807       St->getAlignment() >= RequiredAlignment)
12808     return false;
12809   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12810   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12811   unsigned FirstStoreAlign = FirstInChain->getAlignment();
12812   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12813   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12814   unsigned FirstLoadAlign = FirstLoad->getAlignment();
12815
12816   // Scan the memory operations on the chain and find the first non-consecutive
12817   // load memory address. These variables hold the index in the store node
12818   // array.
12819   unsigned LastConsecutiveLoad = 0;
12820   // This variable refers to the size and not index in the array.
12821   unsigned LastLegalVectorType = 0;
12822   unsigned LastLegalIntegerType = 0;
12823   StartAddress = LoadNodes[0].OffsetFromBase;
12824   SDValue FirstChain = FirstLoad->getChain();
12825   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12826     // All loads must share the same chain.
12827     if (LoadNodes[i].MemNode->getChain() != FirstChain)
12828       break;
12829
12830     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12831     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12832       break;
12833     LastConsecutiveLoad = i;
12834     // Find a legal type for the vector store.
12835     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12836     bool IsFastSt, IsFastLd;
12837     if (TLI.isTypeLegal(StoreTy) &&
12838         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12839                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12840         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12841                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
12842       LastLegalVectorType = i + 1;
12843     }
12844
12845     // Find a legal type for the integer store.
12846     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12847     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12848     if (TLI.isTypeLegal(StoreTy) &&
12849         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12850                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
12851         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12852                                FirstLoadAlign, &IsFastLd) && IsFastLd)
12853       LastLegalIntegerType = i + 1;
12854     // Or check whether a truncstore and extload is legal.
12855     else if (TLI.getTypeAction(Context, StoreTy) ==
12856              TargetLowering::TypePromoteInteger) {
12857       EVT LegalizedStoredValueTy =
12858         TLI.getTypeToTransformTo(Context, StoreTy);
12859       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12860           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12861           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12862           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12863           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12864                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12865           IsFastSt &&
12866           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12867                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12868           IsFastLd)
12869         LastLegalIntegerType = i+1;
12870     }
12871   }
12872
12873   // Only use vector types if the vector type is larger than the integer type.
12874   // If they are the same, use integers.
12875   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12876   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12877
12878   // We add +1 here because the LastXXX variables refer to location while
12879   // the NumElem refers to array/index size.
12880   unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12881   NumElem = std::min(LastLegalType, NumElem);
12882
12883   if (NumElem < 2)
12884     return false;
12885
12886   // Find if it is better to use vectors or integers to load and store
12887   // to memory.
12888   EVT JointMemOpVT;
12889   if (UseVectorTy) {
12890     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12891   } else {
12892     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12893     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12894   }
12895
12896   SDLoc LoadDL(LoadNodes[0].MemNode);
12897   SDLoc StoreDL(StoreNodes[0].MemNode);
12898
12899   // The merged loads are required to have the same incoming chain, so
12900   // using the first's chain is acceptable.
12901   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12902                                 FirstLoad->getBasePtr(),
12903                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12904
12905   SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12906
12907   AddToWorklist(NewStoreChain.getNode());
12908
12909   SDValue NewStore =
12910       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12911                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12912
12913   // Transfer chain users from old loads to the new load.
12914   for (unsigned i = 0; i < NumElem; ++i) {
12915     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12916     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12917                                   SDValue(NewLoad.getNode(), 1));
12918   }
12919
12920   // Replace the all stores with the new store.
12921   for (unsigned i = 0; i < NumElem; ++i)
12922     CombineTo(StoreNodes[i].MemNode, NewStore);
12923   return true;
12924 }
12925
12926 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12927   SDLoc SL(ST);
12928   SDValue ReplStore;
12929
12930   // Replace the chain to avoid dependency.
12931   if (ST->isTruncatingStore()) {
12932     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12933                                   ST->getBasePtr(), ST->getMemoryVT(),
12934                                   ST->getMemOperand());
12935   } else {
12936     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12937                              ST->getMemOperand());
12938   }
12939
12940   // Create token to keep both nodes around.
12941   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12942                               MVT::Other, ST->getChain(), ReplStore);
12943
12944   // Make sure the new and old chains are cleaned up.
12945   AddToWorklist(Token.getNode());
12946
12947   // Don't add users to work list.
12948   return CombineTo(ST, Token, false);
12949 }
12950
12951 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12952   SDValue Value = ST->getValue();
12953   if (Value.getOpcode() == ISD::TargetConstantFP)
12954     return SDValue();
12955
12956   SDLoc DL(ST);
12957
12958   SDValue Chain = ST->getChain();
12959   SDValue Ptr = ST->getBasePtr();
12960
12961   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12962
12963   // NOTE: If the original store is volatile, this transform must not increase
12964   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12965   // processor operation but an i64 (which is not legal) requires two.  So the
12966   // transform should not be done in this case.
12967
12968   SDValue Tmp;
12969   switch (CFP->getSimpleValueType(0).SimpleTy) {
12970   default:
12971     llvm_unreachable("Unknown FP type");
12972   case MVT::f16:    // We don't do this for these yet.
12973   case MVT::f80:
12974   case MVT::f128:
12975   case MVT::ppcf128:
12976     return SDValue();
12977   case MVT::f32:
12978     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12979         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12980       ;
12981       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12982                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12983                             MVT::i32);
12984       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12985     }
12986
12987     return SDValue();
12988   case MVT::f64:
12989     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12990          !ST->isVolatile()) ||
12991         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12992       ;
12993       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12994                             getZExtValue(), SDLoc(CFP), MVT::i64);
12995       return DAG.getStore(Chain, DL, Tmp,
12996                           Ptr, ST->getMemOperand());
12997     }
12998
12999     if (!ST->isVolatile() &&
13000         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13001       // Many FP stores are not made apparent until after legalize, e.g. for
13002       // argument passing.  Since this is so common, custom legalize the
13003       // 64-bit integer store into two 32-bit stores.
13004       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13005       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13006       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13007       if (DAG.getDataLayout().isBigEndian())
13008         std::swap(Lo, Hi);
13009
13010       unsigned Alignment = ST->getAlignment();
13011       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13012       AAMDNodes AAInfo = ST->getAAInfo();
13013
13014       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13015                                  ST->getAlignment(), MMOFlags, AAInfo);
13016       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13017                         DAG.getConstant(4, DL, Ptr.getValueType()));
13018       Alignment = MinAlign(Alignment, 4U);
13019       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13020                                  ST->getPointerInfo().getWithOffset(4),
13021                                  Alignment, MMOFlags, AAInfo);
13022       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13023                          St0, St1);
13024     }
13025
13026     return SDValue();
13027   }
13028 }
13029
13030 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13031   StoreSDNode *ST  = cast<StoreSDNode>(N);
13032   SDValue Chain = ST->getChain();
13033   SDValue Value = ST->getValue();
13034   SDValue Ptr   = ST->getBasePtr();
13035
13036   // If this is a store of a bit convert, store the input value if the
13037   // resultant store does not need a higher alignment than the original.
13038   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13039       ST->isUnindexed()) {
13040     EVT SVT = Value.getOperand(0).getValueType();
13041     if (((!LegalOperations && !ST->isVolatile()) ||
13042          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13043         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13044       unsigned OrigAlign = ST->getAlignment();
13045       bool Fast = false;
13046       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13047                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13048           Fast) {
13049         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13050                             ST->getPointerInfo(), OrigAlign,
13051                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13052       }
13053     }
13054   }
13055
13056   // Turn 'store undef, Ptr' -> nothing.
13057   if (Value.isUndef() && ST->isUnindexed())
13058     return Chain;
13059
13060   // Try to infer better alignment information than the store already has.
13061   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13062     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13063       if (Align > ST->getAlignment()) {
13064         SDValue NewStore =
13065             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13066                               ST->getMemoryVT(), Align,
13067                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13068         if (NewStore.getNode() != N)
13069           return CombineTo(ST, NewStore, true);
13070       }
13071     }
13072   }
13073
13074   // Try transforming a pair floating point load / store ops to integer
13075   // load / store ops.
13076   if (SDValue NewST = TransformFPLoadStorePair(N))
13077     return NewST;
13078
13079   if (ST->isUnindexed()) {
13080     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13081     // adjacent stores.
13082     if (findBetterNeighborChains(ST)) {
13083       // replaceStoreChain uses CombineTo, which handled all of the worklist
13084       // manipulation. Return the original node to not do anything else.
13085       return SDValue(ST, 0);
13086     }
13087     Chain = ST->getChain();
13088   }
13089
13090   // Try transforming N to an indexed store.
13091   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13092     return SDValue(N, 0);
13093
13094   // FIXME: is there such a thing as a truncating indexed store?
13095   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13096       Value.getValueType().isInteger()) {
13097     // See if we can simplify the input to this truncstore with knowledge that
13098     // only the low bits are being used.  For example:
13099     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13100     SDValue Shorter = GetDemandedBits(
13101         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13102                                     ST->getMemoryVT().getScalarSizeInBits()));
13103     AddToWorklist(Value.getNode());
13104     if (Shorter.getNode())
13105       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13106                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13107
13108     // Otherwise, see if we can simplify the operation with
13109     // SimplifyDemandedBits, which only works if the value has a single use.
13110     if (SimplifyDemandedBits(
13111             Value,
13112             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13113                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13114       // Re-visit the store if anything changed and the store hasn't been merged
13115       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13116       // node back to the worklist if necessary, but we also need to re-visit
13117       // the Store node itself.
13118       if (N->getOpcode() != ISD::DELETED_NODE)
13119         AddToWorklist(N);
13120       return SDValue(N, 0);
13121     }
13122   }
13123
13124   // If this is a load followed by a store to the same location, then the store
13125   // is dead/noop.
13126   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13127     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13128         ST->isUnindexed() && !ST->isVolatile() &&
13129         // There can't be any side effects between the load and store, such as
13130         // a call or store.
13131         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13132       // The store is dead, remove it.
13133       return Chain;
13134     }
13135   }
13136
13137   // If this is a store followed by a store with the same value to the same
13138   // location, then the store is dead/noop.
13139   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13140     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
13141         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
13142         ST1->isUnindexed() && !ST1->isVolatile()) {
13143       // The store is dead, remove it.
13144       return Chain;
13145     }
13146   }
13147
13148   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13149   // truncating store.  We can do this even if this is already a truncstore.
13150   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13151       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13152       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13153                             ST->getMemoryVT())) {
13154     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13155                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13156   }
13157
13158   // Only perform this optimization before the types are legal, because we
13159   // don't want to perform this optimization on every DAGCombine invocation.
13160   if (!LegalTypes) {
13161     for (;;) {
13162       // There can be multiple store sequences on the same chain.
13163       // Keep trying to merge store sequences until we are unable to do so
13164       // or until we merge the last store on the chain.
13165       bool Changed = MergeConsecutiveStores(ST);
13166       if (!Changed) break;
13167       // Return N as merge only uses CombineTo and no worklist clean
13168       // up is necessary.
13169       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13170         return SDValue(N, 0);
13171     }
13172   }
13173
13174   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13175   //
13176   // Make sure to do this only after attempting to merge stores in order to
13177   //  avoid changing the types of some subset of stores due to visit order,
13178   //  preventing their merging.
13179   if (isa<ConstantFPSDNode>(ST->getValue())) {
13180     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13181       return NewSt;
13182   }
13183
13184   if (SDValue NewSt = splitMergedValStore(ST))
13185     return NewSt;
13186
13187   return ReduceLoadOpStoreWidth(N);
13188 }
13189
13190 /// For the instruction sequence of store below, F and I values
13191 /// are bundled together as an i64 value before being stored into memory.
13192 /// Sometimes it is more efficent to generate separate stores for F and I,
13193 /// which can remove the bitwise instructions or sink them to colder places.
13194 ///
13195 ///   (store (or (zext (bitcast F to i32) to i64),
13196 ///              (shl (zext I to i64), 32)), addr)  -->
13197 ///   (store F, addr) and (store I, addr+4)
13198 ///
13199 /// Similarly, splitting for other merged store can also be beneficial, like:
13200 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13201 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13202 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13203 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13204 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13205 ///
13206 /// We allow each target to determine specifically which kind of splitting is
13207 /// supported.
13208 ///
13209 /// The store patterns are commonly seen from the simple code snippet below
13210 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13211 ///   void goo(const std::pair<int, float> &);
13212 ///   hoo() {
13213 ///     ...
13214 ///     goo(std::make_pair(tmp, ftmp));
13215 ///     ...
13216 ///   }
13217 ///
13218 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13219   if (OptLevel == CodeGenOpt::None)
13220     return SDValue();
13221
13222   SDValue Val = ST->getValue();
13223   SDLoc DL(ST);
13224
13225   // Match OR operand.
13226   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13227     return SDValue();
13228
13229   // Match SHL operand and get Lower and Higher parts of Val.
13230   SDValue Op1 = Val.getOperand(0);
13231   SDValue Op2 = Val.getOperand(1);
13232   SDValue Lo, Hi;
13233   if (Op1.getOpcode() != ISD::SHL) {
13234     std::swap(Op1, Op2);
13235     if (Op1.getOpcode() != ISD::SHL)
13236       return SDValue();
13237   }
13238   Lo = Op2;
13239   Hi = Op1.getOperand(0);
13240   if (!Op1.hasOneUse())
13241     return SDValue();
13242
13243   // Match shift amount to HalfValBitSize.
13244   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13245   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13246   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13247     return SDValue();
13248
13249   // Lo and Hi are zero-extended from int with size less equal than 32
13250   // to i64.
13251   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13252       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13253       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13254       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13255       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13256       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13257     return SDValue();
13258
13259   // Use the EVT of low and high parts before bitcast as the input
13260   // of target query.
13261   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13262                   ? Lo.getOperand(0).getValueType()
13263                   : Lo.getValueType();
13264   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13265                    ? Hi.getOperand(0).getValueType()
13266                    : Hi.getValueType();
13267   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13268     return SDValue();
13269
13270   // Start to split store.
13271   unsigned Alignment = ST->getAlignment();
13272   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13273   AAMDNodes AAInfo = ST->getAAInfo();
13274
13275   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13276   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13277   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13278   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13279
13280   SDValue Chain = ST->getChain();
13281   SDValue Ptr = ST->getBasePtr();
13282   // Lower value store.
13283   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13284                              ST->getAlignment(), MMOFlags, AAInfo);
13285   Ptr =
13286       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13287                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13288   // Higher value store.
13289   SDValue St1 =
13290       DAG.getStore(St0, DL, Hi, Ptr,
13291                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13292                    Alignment / 2, MMOFlags, AAInfo);
13293   return St1;
13294 }
13295
13296 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13297   SDValue InVec = N->getOperand(0);
13298   SDValue InVal = N->getOperand(1);
13299   SDValue EltNo = N->getOperand(2);
13300   SDLoc DL(N);
13301
13302   // If the inserted element is an UNDEF, just use the input vector.
13303   if (InVal.isUndef())
13304     return InVec;
13305
13306   EVT VT = InVec.getValueType();
13307
13308   // Check that we know which element is being inserted
13309   if (!isa<ConstantSDNode>(EltNo))
13310     return SDValue();
13311   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13312
13313   // Canonicalize insert_vector_elt dag nodes.
13314   // Example:
13315   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13316   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13317   //
13318   // Do this only if the child insert_vector node has one use; also
13319   // do this only if indices are both constants and Idx1 < Idx0.
13320   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13321       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13322     unsigned OtherElt = InVec.getConstantOperandVal(2);
13323     if (Elt < OtherElt) {
13324       // Swap nodes.
13325       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13326                                   InVec.getOperand(0), InVal, EltNo);
13327       AddToWorklist(NewOp.getNode());
13328       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13329                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13330     }
13331   }
13332
13333   // If we can't generate a legal BUILD_VECTOR, exit
13334   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13335     return SDValue();
13336
13337   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13338   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13339   // vector elements.
13340   SmallVector<SDValue, 8> Ops;
13341   // Do not combine these two vectors if the output vector will not replace
13342   // the input vector.
13343   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13344     Ops.append(InVec.getNode()->op_begin(),
13345                InVec.getNode()->op_end());
13346   } else if (InVec.isUndef()) {
13347     unsigned NElts = VT.getVectorNumElements();
13348     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13349   } else {
13350     return SDValue();
13351   }
13352
13353   // Insert the element
13354   if (Elt < Ops.size()) {
13355     // All the operands of BUILD_VECTOR must have the same type;
13356     // we enforce that here.
13357     EVT OpVT = Ops[0].getValueType();
13358     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13359   }
13360
13361   // Return the new vector
13362   return DAG.getBuildVector(VT, DL, Ops);
13363 }
13364
13365 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13366     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13367   assert(!OriginalLoad->isVolatile());
13368
13369   EVT ResultVT = EVE->getValueType(0);
13370   EVT VecEltVT = InVecVT.getVectorElementType();
13371   unsigned Align = OriginalLoad->getAlignment();
13372   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13373       VecEltVT.getTypeForEVT(*DAG.getContext()));
13374
13375   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13376     return SDValue();
13377
13378   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13379     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13380   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13381     return SDValue();
13382
13383   Align = NewAlign;
13384
13385   SDValue NewPtr = OriginalLoad->getBasePtr();
13386   SDValue Offset;
13387   EVT PtrType = NewPtr.getValueType();
13388   MachinePointerInfo MPI;
13389   SDLoc DL(EVE);
13390   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13391     int Elt = ConstEltNo->getZExtValue();
13392     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13393     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13394     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13395   } else {
13396     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13397     Offset = DAG.getNode(
13398         ISD::MUL, DL, PtrType, Offset,
13399         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13400     MPI = OriginalLoad->getPointerInfo();
13401   }
13402   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13403
13404   // The replacement we need to do here is a little tricky: we need to
13405   // replace an extractelement of a load with a load.
13406   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13407   // Note that this replacement assumes that the extractvalue is the only
13408   // use of the load; that's okay because we don't want to perform this
13409   // transformation in other cases anyway.
13410   SDValue Load;
13411   SDValue Chain;
13412   if (ResultVT.bitsGT(VecEltVT)) {
13413     // If the result type of vextract is wider than the load, then issue an
13414     // extending load instead.
13415     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13416                                                   VecEltVT)
13417                                    ? ISD::ZEXTLOAD
13418                                    : ISD::EXTLOAD;
13419     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13420                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13421                           Align, OriginalLoad->getMemOperand()->getFlags(),
13422                           OriginalLoad->getAAInfo());
13423     Chain = Load.getValue(1);
13424   } else {
13425     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13426                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13427                        OriginalLoad->getAAInfo());
13428     Chain = Load.getValue(1);
13429     if (ResultVT.bitsLT(VecEltVT))
13430       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13431     else
13432       Load = DAG.getBitcast(ResultVT, Load);
13433   }
13434   WorklistRemover DeadNodes(*this);
13435   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13436   SDValue To[] = { Load, Chain };
13437   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13438   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13439   // worklist explicitly as well.
13440   AddToWorklist(Load.getNode());
13441   AddUsersToWorklist(Load.getNode()); // Add users too
13442   // Make sure to revisit this node to clean it up; it will usually be dead.
13443   AddToWorklist(EVE);
13444   ++OpsNarrowed;
13445   return SDValue(EVE, 0);
13446 }
13447
13448 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13449   // (vextract (scalar_to_vector val, 0) -> val
13450   SDValue InVec = N->getOperand(0);
13451   EVT VT = InVec.getValueType();
13452   EVT NVT = N->getValueType(0);
13453
13454   if (InVec.isUndef())
13455     return DAG.getUNDEF(NVT);
13456
13457   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13458     // Check if the result type doesn't match the inserted element type. A
13459     // SCALAR_TO_VECTOR may truncate the inserted element and the
13460     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13461     SDValue InOp = InVec.getOperand(0);
13462     if (InOp.getValueType() != NVT) {
13463       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13464       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13465     }
13466     return InOp;
13467   }
13468
13469   SDValue EltNo = N->getOperand(1);
13470   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13471
13472   // extract_vector_elt (build_vector x, y), 1 -> y
13473   if (ConstEltNo &&
13474       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13475       TLI.isTypeLegal(VT) &&
13476       (InVec.hasOneUse() ||
13477        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13478     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13479     EVT InEltVT = Elt.getValueType();
13480
13481     // Sometimes build_vector's scalar input types do not match result type.
13482     if (NVT == InEltVT)
13483       return Elt;
13484
13485     // TODO: It may be useful to truncate if free if the build_vector implicitly
13486     // converts.
13487   }
13488
13489   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13490   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13491       ConstEltNo->isNullValue() && VT.isInteger()) {
13492     SDValue BCSrc = InVec.getOperand(0);
13493     if (BCSrc.getValueType().isScalarInteger())
13494       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13495   }
13496
13497   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13498   //
13499   // This only really matters if the index is non-constant since other combines
13500   // on the constant elements already work.
13501   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13502       EltNo == InVec.getOperand(2)) {
13503     SDValue Elt = InVec.getOperand(1);
13504     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13505   }
13506
13507   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13508   // We only perform this optimization before the op legalization phase because
13509   // we may introduce new vector instructions which are not backed by TD
13510   // patterns. For example on AVX, extracting elements from a wide vector
13511   // without using extract_subvector. However, if we can find an underlying
13512   // scalar value, then we can always use that.
13513   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13514     int NumElem = VT.getVectorNumElements();
13515     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13516     // Find the new index to extract from.
13517     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13518
13519     // Extracting an undef index is undef.
13520     if (OrigElt == -1)
13521       return DAG.getUNDEF(NVT);
13522
13523     // Select the right vector half to extract from.
13524     SDValue SVInVec;
13525     if (OrigElt < NumElem) {
13526       SVInVec = InVec->getOperand(0);
13527     } else {
13528       SVInVec = InVec->getOperand(1);
13529       OrigElt -= NumElem;
13530     }
13531
13532     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13533       SDValue InOp = SVInVec.getOperand(OrigElt);
13534       if (InOp.getValueType() != NVT) {
13535         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13536         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13537       }
13538
13539       return InOp;
13540     }
13541
13542     // FIXME: We should handle recursing on other vector shuffles and
13543     // scalar_to_vector here as well.
13544
13545     if (!LegalOperations) {
13546       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13547       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13548                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13549     }
13550   }
13551
13552   bool BCNumEltsChanged = false;
13553   EVT ExtVT = VT.getVectorElementType();
13554   EVT LVT = ExtVT;
13555
13556   // If the result of load has to be truncated, then it's not necessarily
13557   // profitable.
13558   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13559     return SDValue();
13560
13561   if (InVec.getOpcode() == ISD::BITCAST) {
13562     // Don't duplicate a load with other uses.
13563     if (!InVec.hasOneUse())
13564       return SDValue();
13565
13566     EVT BCVT = InVec.getOperand(0).getValueType();
13567     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13568       return SDValue();
13569     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13570       BCNumEltsChanged = true;
13571     InVec = InVec.getOperand(0);
13572     ExtVT = BCVT.getVectorElementType();
13573   }
13574
13575   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13576   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13577       ISD::isNormalLoad(InVec.getNode()) &&
13578       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13579     SDValue Index = N->getOperand(1);
13580     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13581       if (!OrigLoad->isVolatile()) {
13582         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13583                                                              OrigLoad);
13584       }
13585     }
13586   }
13587
13588   // Perform only after legalization to ensure build_vector / vector_shuffle
13589   // optimizations have already been done.
13590   if (!LegalOperations) return SDValue();
13591
13592   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13593   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13594   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13595
13596   if (ConstEltNo) {
13597     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13598
13599     LoadSDNode *LN0 = nullptr;
13600     const ShuffleVectorSDNode *SVN = nullptr;
13601     if (ISD::isNormalLoad(InVec.getNode())) {
13602       LN0 = cast<LoadSDNode>(InVec);
13603     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13604                InVec.getOperand(0).getValueType() == ExtVT &&
13605                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13606       // Don't duplicate a load with other uses.
13607       if (!InVec.hasOneUse())
13608         return SDValue();
13609
13610       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13611     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13612       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13613       // =>
13614       // (load $addr+1*size)
13615
13616       // Don't duplicate a load with other uses.
13617       if (!InVec.hasOneUse())
13618         return SDValue();
13619
13620       // If the bit convert changed the number of elements, it is unsafe
13621       // to examine the mask.
13622       if (BCNumEltsChanged)
13623         return SDValue();
13624
13625       // Select the input vector, guarding against out of range extract vector.
13626       unsigned NumElems = VT.getVectorNumElements();
13627       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13628       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13629
13630       if (InVec.getOpcode() == ISD::BITCAST) {
13631         // Don't duplicate a load with other uses.
13632         if (!InVec.hasOneUse())
13633           return SDValue();
13634
13635         InVec = InVec.getOperand(0);
13636       }
13637       if (ISD::isNormalLoad(InVec.getNode())) {
13638         LN0 = cast<LoadSDNode>(InVec);
13639         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13640         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13641       }
13642     }
13643
13644     // Make sure we found a non-volatile load and the extractelement is
13645     // the only use.
13646     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13647       return SDValue();
13648
13649     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13650     if (Elt == -1)
13651       return DAG.getUNDEF(LVT);
13652
13653     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13654   }
13655
13656   return SDValue();
13657 }
13658
13659 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13660 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13661   // We perform this optimization post type-legalization because
13662   // the type-legalizer often scalarizes integer-promoted vectors.
13663   // Performing this optimization before may create bit-casts which
13664   // will be type-legalized to complex code sequences.
13665   // We perform this optimization only before the operation legalizer because we
13666   // may introduce illegal operations.
13667   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13668     return SDValue();
13669
13670   unsigned NumInScalars = N->getNumOperands();
13671   SDLoc DL(N);
13672   EVT VT = N->getValueType(0);
13673
13674   // Check to see if this is a BUILD_VECTOR of a bunch of values
13675   // which come from any_extend or zero_extend nodes. If so, we can create
13676   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13677   // optimizations. We do not handle sign-extend because we can't fill the sign
13678   // using shuffles.
13679   EVT SourceType = MVT::Other;
13680   bool AllAnyExt = true;
13681
13682   for (unsigned i = 0; i != NumInScalars; ++i) {
13683     SDValue In = N->getOperand(i);
13684     // Ignore undef inputs.
13685     if (In.isUndef()) continue;
13686
13687     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13688     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13689
13690     // Abort if the element is not an extension.
13691     if (!ZeroExt && !AnyExt) {
13692       SourceType = MVT::Other;
13693       break;
13694     }
13695
13696     // The input is a ZeroExt or AnyExt. Check the original type.
13697     EVT InTy = In.getOperand(0).getValueType();
13698
13699     // Check that all of the widened source types are the same.
13700     if (SourceType == MVT::Other)
13701       // First time.
13702       SourceType = InTy;
13703     else if (InTy != SourceType) {
13704       // Multiple income types. Abort.
13705       SourceType = MVT::Other;
13706       break;
13707     }
13708
13709     // Check if all of the extends are ANY_EXTENDs.
13710     AllAnyExt &= AnyExt;
13711   }
13712
13713   // In order to have valid types, all of the inputs must be extended from the
13714   // same source type and all of the inputs must be any or zero extend.
13715   // Scalar sizes must be a power of two.
13716   EVT OutScalarTy = VT.getScalarType();
13717   bool ValidTypes = SourceType != MVT::Other &&
13718                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13719                  isPowerOf2_32(SourceType.getSizeInBits());
13720
13721   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13722   // turn into a single shuffle instruction.
13723   if (!ValidTypes)
13724     return SDValue();
13725
13726   bool isLE = DAG.getDataLayout().isLittleEndian();
13727   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13728   assert(ElemRatio > 1 && "Invalid element size ratio");
13729   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13730                                DAG.getConstant(0, DL, SourceType);
13731
13732   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13733   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13734
13735   // Populate the new build_vector
13736   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13737     SDValue Cast = N->getOperand(i);
13738     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13739             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13740             Cast.isUndef()) && "Invalid cast opcode");
13741     SDValue In;
13742     if (Cast.isUndef())
13743       In = DAG.getUNDEF(SourceType);
13744     else
13745       In = Cast->getOperand(0);
13746     unsigned Index = isLE ? (i * ElemRatio) :
13747                             (i * ElemRatio + (ElemRatio - 1));
13748
13749     assert(Index < Ops.size() && "Invalid index");
13750     Ops[Index] = In;
13751   }
13752
13753   // The type of the new BUILD_VECTOR node.
13754   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13755   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13756          "Invalid vector size");
13757   // Check if the new vector type is legal.
13758   if (!isTypeLegal(VecVT)) return SDValue();
13759
13760   // Make the new BUILD_VECTOR.
13761   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13762
13763   // The new BUILD_VECTOR node has the potential to be further optimized.
13764   AddToWorklist(BV.getNode());
13765   // Bitcast to the desired type.
13766   return DAG.getBitcast(VT, BV);
13767 }
13768
13769 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13770   EVT VT = N->getValueType(0);
13771
13772   unsigned NumInScalars = N->getNumOperands();
13773   SDLoc DL(N);
13774
13775   EVT SrcVT = MVT::Other;
13776   unsigned Opcode = ISD::DELETED_NODE;
13777   unsigned NumDefs = 0;
13778
13779   for (unsigned i = 0; i != NumInScalars; ++i) {
13780     SDValue In = N->getOperand(i);
13781     unsigned Opc = In.getOpcode();
13782
13783     if (Opc == ISD::UNDEF)
13784       continue;
13785
13786     // If all scalar values are floats and converted from integers.
13787     if (Opcode == ISD::DELETED_NODE &&
13788         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13789       Opcode = Opc;
13790     }
13791
13792     if (Opc != Opcode)
13793       return SDValue();
13794
13795     EVT InVT = In.getOperand(0).getValueType();
13796
13797     // If all scalar values are typed differently, bail out. It's chosen to
13798     // simplify BUILD_VECTOR of integer types.
13799     if (SrcVT == MVT::Other)
13800       SrcVT = InVT;
13801     if (SrcVT != InVT)
13802       return SDValue();
13803     NumDefs++;
13804   }
13805
13806   // If the vector has just one element defined, it's not worth to fold it into
13807   // a vectorized one.
13808   if (NumDefs < 2)
13809     return SDValue();
13810
13811   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13812          && "Should only handle conversion from integer to float.");
13813   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13814
13815   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13816
13817   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13818     return SDValue();
13819
13820   // Just because the floating-point vector type is legal does not necessarily
13821   // mean that the corresponding integer vector type is.
13822   if (!isTypeLegal(NVT))
13823     return SDValue();
13824
13825   SmallVector<SDValue, 8> Opnds;
13826   for (unsigned i = 0; i != NumInScalars; ++i) {
13827     SDValue In = N->getOperand(i);
13828
13829     if (In.isUndef())
13830       Opnds.push_back(DAG.getUNDEF(SrcVT));
13831     else
13832       Opnds.push_back(In.getOperand(0));
13833   }
13834   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13835   AddToWorklist(BV.getNode());
13836
13837   return DAG.getNode(Opcode, DL, VT, BV);
13838 }
13839
13840 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13841                                            ArrayRef<int> VectorMask,
13842                                            SDValue VecIn1, SDValue VecIn2,
13843                                            unsigned LeftIdx) {
13844   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13845   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13846
13847   EVT VT = N->getValueType(0);
13848   EVT InVT1 = VecIn1.getValueType();
13849   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13850
13851   unsigned Vec2Offset = InVT1.getVectorNumElements();
13852   unsigned NumElems = VT.getVectorNumElements();
13853   unsigned ShuffleNumElems = NumElems;
13854
13855   // We can't generate a shuffle node with mismatched input and output types.
13856   // Try to make the types match the type of the output.
13857   if (InVT1 != VT || InVT2 != VT) {
13858     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13859       // If the output vector length is a multiple of both input lengths,
13860       // we can concatenate them and pad the rest with undefs.
13861       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13862       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13863       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13864       ConcatOps[0] = VecIn1;
13865       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13866       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13867       VecIn2 = SDValue();
13868     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13869       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13870         return SDValue();
13871
13872       if (!VecIn2.getNode()) {
13873         // If we only have one input vector, and it's twice the size of the
13874         // output, split it in two.
13875         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13876                              DAG.getConstant(NumElems, DL, IdxTy));
13877         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13878         // Since we now have shorter input vectors, adjust the offset of the
13879         // second vector's start.
13880         Vec2Offset = NumElems;
13881       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13882         // VecIn1 is wider than the output, and we have another, possibly
13883         // smaller input. Pad the smaller input with undefs, shuffle at the
13884         // input vector width, and extract the output.
13885         // The shuffle type is different than VT, so check legality again.
13886         if (LegalOperations &&
13887             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13888           return SDValue();
13889
13890         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13891         // lower it back into a BUILD_VECTOR. So if the inserted type is
13892         // illegal, don't even try.
13893         if (InVT1 != InVT2) {
13894           if (!TLI.isTypeLegal(InVT2))
13895             return SDValue();
13896           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13897                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13898         }
13899         ShuffleNumElems = NumElems * 2;
13900       } else {
13901         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13902         // than VecIn1. We can't handle this for now - this case will disappear
13903         // when we start sorting the vectors by type.
13904         return SDValue();
13905       }
13906     } else {
13907       // TODO: Support cases where the length mismatch isn't exactly by a
13908       // factor of 2.
13909       // TODO: Move this check upwards, so that if we have bad type
13910       // mismatches, we don't create any DAG nodes.
13911       return SDValue();
13912     }
13913   }
13914
13915   // Initialize mask to undef.
13916   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13917
13918   // Only need to run up to the number of elements actually used, not the
13919   // total number of elements in the shuffle - if we are shuffling a wider
13920   // vector, the high lanes should be set to undef.
13921   for (unsigned i = 0; i != NumElems; ++i) {
13922     if (VectorMask[i] <= 0)
13923       continue;
13924
13925     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13926     if (VectorMask[i] == (int)LeftIdx) {
13927       Mask[i] = ExtIndex;
13928     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13929       Mask[i] = Vec2Offset + ExtIndex;
13930     }
13931   }
13932
13933   // The type the input vectors may have changed above.
13934   InVT1 = VecIn1.getValueType();
13935
13936   // If we already have a VecIn2, it should have the same type as VecIn1.
13937   // If we don't, get an undef/zero vector of the appropriate type.
13938   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13939   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13940
13941   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13942   if (ShuffleNumElems > NumElems)
13943     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13944
13945   return Shuffle;
13946 }
13947
13948 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13949 // operations. If the types of the vectors we're extracting from allow it,
13950 // turn this into a vector_shuffle node.
13951 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13952   SDLoc DL(N);
13953   EVT VT = N->getValueType(0);
13954
13955   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13956   if (!isTypeLegal(VT))
13957     return SDValue();
13958
13959   // May only combine to shuffle after legalize if shuffle is legal.
13960   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13961     return SDValue();
13962
13963   bool UsesZeroVector = false;
13964   unsigned NumElems = N->getNumOperands();
13965
13966   // Record, for each element of the newly built vector, which input vector
13967   // that element comes from. -1 stands for undef, 0 for the zero vector,
13968   // and positive values for the input vectors.
13969   // VectorMask maps each element to its vector number, and VecIn maps vector
13970   // numbers to their initial SDValues.
13971
13972   SmallVector<int, 8> VectorMask(NumElems, -1);
13973   SmallVector<SDValue, 8> VecIn;
13974   VecIn.push_back(SDValue());
13975
13976   for (unsigned i = 0; i != NumElems; ++i) {
13977     SDValue Op = N->getOperand(i);
13978
13979     if (Op.isUndef())
13980       continue;
13981
13982     // See if we can use a blend with a zero vector.
13983     // TODO: Should we generalize this to a blend with an arbitrary constant
13984     // vector?
13985     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13986       UsesZeroVector = true;
13987       VectorMask[i] = 0;
13988       continue;
13989     }
13990
13991     // Not an undef or zero. If the input is something other than an
13992     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13993     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13994         !isa<ConstantSDNode>(Op.getOperand(1)))
13995       return SDValue();
13996
13997     SDValue ExtractedFromVec = Op.getOperand(0);
13998
13999     // All inputs must have the same element type as the output.
14000     if (VT.getVectorElementType() !=
14001         ExtractedFromVec.getValueType().getVectorElementType())
14002       return SDValue();
14003
14004     // Have we seen this input vector before?
14005     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14006     // a map back from SDValues to numbers isn't worth it.
14007     unsigned Idx = std::distance(
14008         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14009     if (Idx == VecIn.size())
14010       VecIn.push_back(ExtractedFromVec);
14011
14012     VectorMask[i] = Idx;
14013   }
14014
14015   // If we didn't find at least one input vector, bail out.
14016   if (VecIn.size() < 2)
14017     return SDValue();
14018
14019   // TODO: We want to sort the vectors by descending length, so that adjacent
14020   // pairs have similar length, and the longer vector is always first in the
14021   // pair.
14022
14023   // TODO: Should this fire if some of the input vectors has illegal type (like
14024   // it does now), or should we let legalization run its course first?
14025
14026   // Shuffle phase:
14027   // Take pairs of vectors, and shuffle them so that the result has elements
14028   // from these vectors in the correct places.
14029   // For example, given:
14030   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14031   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14032   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14033   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14034   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14035   // We will generate:
14036   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14037   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14038   SmallVector<SDValue, 4> Shuffles;
14039   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14040     unsigned LeftIdx = 2 * In + 1;
14041     SDValue VecLeft = VecIn[LeftIdx];
14042     SDValue VecRight =
14043         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14044
14045     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14046                                                 VecRight, LeftIdx))
14047       Shuffles.push_back(Shuffle);
14048     else
14049       return SDValue();
14050   }
14051
14052   // If we need the zero vector as an "ingredient" in the blend tree, add it
14053   // to the list of shuffles.
14054   if (UsesZeroVector)
14055     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14056                                       : DAG.getConstantFP(0.0, DL, VT));
14057
14058   // If we only have one shuffle, we're done.
14059   if (Shuffles.size() == 1)
14060     return Shuffles[0];
14061
14062   // Update the vector mask to point to the post-shuffle vectors.
14063   for (int &Vec : VectorMask)
14064     if (Vec == 0)
14065       Vec = Shuffles.size() - 1;
14066     else
14067       Vec = (Vec - 1) / 2;
14068
14069   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14070   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14071   // generate:
14072   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14073   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14074   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14075   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14076   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14077   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14078   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14079
14080   // Make sure the initial size of the shuffle list is even.
14081   if (Shuffles.size() % 2)
14082     Shuffles.push_back(DAG.getUNDEF(VT));
14083
14084   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14085     if (CurSize % 2) {
14086       Shuffles[CurSize] = DAG.getUNDEF(VT);
14087       CurSize++;
14088     }
14089     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14090       int Left = 2 * In;
14091       int Right = 2 * In + 1;
14092       SmallVector<int, 8> Mask(NumElems, -1);
14093       for (unsigned i = 0; i != NumElems; ++i) {
14094         if (VectorMask[i] == Left) {
14095           Mask[i] = i;
14096           VectorMask[i] = In;
14097         } else if (VectorMask[i] == Right) {
14098           Mask[i] = i + NumElems;
14099           VectorMask[i] = In;
14100         }
14101       }
14102
14103       Shuffles[In] =
14104           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14105     }
14106   }
14107
14108   return Shuffles[0];
14109 }
14110
14111 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14112   EVT VT = N->getValueType(0);
14113
14114   // A vector built entirely of undefs is undef.
14115   if (ISD::allOperandsUndef(N))
14116     return DAG.getUNDEF(VT);
14117
14118   // Check if we can express BUILD VECTOR via subvector extract.
14119   if (!LegalTypes && (N->getNumOperands() > 1)) {
14120     SDValue Op0 = N->getOperand(0);
14121     auto checkElem = [&](SDValue Op) -> uint64_t {
14122       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14123           (Op0.getOperand(0) == Op.getOperand(0)))
14124         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14125           return CNode->getZExtValue();
14126       return -1;
14127     };
14128
14129     int Offset = checkElem(Op0);
14130     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14131       if (Offset + i != checkElem(N->getOperand(i))) {
14132         Offset = -1;
14133         break;
14134       }
14135     }
14136
14137     if ((Offset == 0) &&
14138         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14139       return Op0.getOperand(0);
14140     if ((Offset != -1) &&
14141         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14142          0)) // IDX must be multiple of output size.
14143       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14144                          Op0.getOperand(0), Op0.getOperand(1));
14145   }
14146
14147   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14148     return V;
14149
14150   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14151     return V;
14152
14153   if (SDValue V = reduceBuildVecToShuffle(N))
14154     return V;
14155
14156   return SDValue();
14157 }
14158
14159 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14161   EVT OpVT = N->getOperand(0).getValueType();
14162
14163   // If the operands are legal vectors, leave them alone.
14164   if (TLI.isTypeLegal(OpVT))
14165     return SDValue();
14166
14167   SDLoc DL(N);
14168   EVT VT = N->getValueType(0);
14169   SmallVector<SDValue, 8> Ops;
14170
14171   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14172   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14173
14174   // Keep track of what we encounter.
14175   bool AnyInteger = false;
14176   bool AnyFP = false;
14177   for (const SDValue &Op : N->ops()) {
14178     if (ISD::BITCAST == Op.getOpcode() &&
14179         !Op.getOperand(0).getValueType().isVector())
14180       Ops.push_back(Op.getOperand(0));
14181     else if (ISD::UNDEF == Op.getOpcode())
14182       Ops.push_back(ScalarUndef);
14183     else
14184       return SDValue();
14185
14186     // Note whether we encounter an integer or floating point scalar.
14187     // If it's neither, bail out, it could be something weird like x86mmx.
14188     EVT LastOpVT = Ops.back().getValueType();
14189     if (LastOpVT.isFloatingPoint())
14190       AnyFP = true;
14191     else if (LastOpVT.isInteger())
14192       AnyInteger = true;
14193     else
14194       return SDValue();
14195   }
14196
14197   // If any of the operands is a floating point scalar bitcast to a vector,
14198   // use floating point types throughout, and bitcast everything.
14199   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14200   if (AnyFP) {
14201     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14202     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14203     if (AnyInteger) {
14204       for (SDValue &Op : Ops) {
14205         if (Op.getValueType() == SVT)
14206           continue;
14207         if (Op.isUndef())
14208           Op = ScalarUndef;
14209         else
14210           Op = DAG.getBitcast(SVT, Op);
14211       }
14212     }
14213   }
14214
14215   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14216                                VT.getSizeInBits() / SVT.getSizeInBits());
14217   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14218 }
14219
14220 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14221 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14222 // most two distinct vectors the same size as the result, attempt to turn this
14223 // into a legal shuffle.
14224 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14225   EVT VT = N->getValueType(0);
14226   EVT OpVT = N->getOperand(0).getValueType();
14227   int NumElts = VT.getVectorNumElements();
14228   int NumOpElts = OpVT.getVectorNumElements();
14229
14230   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14231   SmallVector<int, 8> Mask;
14232
14233   for (SDValue Op : N->ops()) {
14234     // Peek through any bitcast.
14235     while (Op.getOpcode() == ISD::BITCAST)
14236       Op = Op.getOperand(0);
14237
14238     // UNDEF nodes convert to UNDEF shuffle mask values.
14239     if (Op.isUndef()) {
14240       Mask.append((unsigned)NumOpElts, -1);
14241       continue;
14242     }
14243
14244     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14245       return SDValue();
14246
14247     // What vector are we extracting the subvector from and at what index?
14248     SDValue ExtVec = Op.getOperand(0);
14249
14250     // We want the EVT of the original extraction to correctly scale the
14251     // extraction index.
14252     EVT ExtVT = ExtVec.getValueType();
14253
14254     // Peek through any bitcast.
14255     while (ExtVec.getOpcode() == ISD::BITCAST)
14256       ExtVec = ExtVec.getOperand(0);
14257
14258     // UNDEF nodes convert to UNDEF shuffle mask values.
14259     if (ExtVec.isUndef()) {
14260       Mask.append((unsigned)NumOpElts, -1);
14261       continue;
14262     }
14263
14264     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14265       return SDValue();
14266     int ExtIdx = Op.getConstantOperandVal(1);
14267
14268     // Ensure that we are extracting a subvector from a vector the same
14269     // size as the result.
14270     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14271       return SDValue();
14272
14273     // Scale the subvector index to account for any bitcast.
14274     int NumExtElts = ExtVT.getVectorNumElements();
14275     if (0 == (NumExtElts % NumElts))
14276       ExtIdx /= (NumExtElts / NumElts);
14277     else if (0 == (NumElts % NumExtElts))
14278       ExtIdx *= (NumElts / NumExtElts);
14279     else
14280       return SDValue();
14281
14282     // At most we can reference 2 inputs in the final shuffle.
14283     if (SV0.isUndef() || SV0 == ExtVec) {
14284       SV0 = ExtVec;
14285       for (int i = 0; i != NumOpElts; ++i)
14286         Mask.push_back(i + ExtIdx);
14287     } else if (SV1.isUndef() || SV1 == ExtVec) {
14288       SV1 = ExtVec;
14289       for (int i = 0; i != NumOpElts; ++i)
14290         Mask.push_back(i + ExtIdx + NumElts);
14291     } else {
14292       return SDValue();
14293     }
14294   }
14295
14296   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14297     return SDValue();
14298
14299   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14300                               DAG.getBitcast(VT, SV1), Mask);
14301 }
14302
14303 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14304   // If we only have one input vector, we don't need to do any concatenation.
14305   if (N->getNumOperands() == 1)
14306     return N->getOperand(0);
14307
14308   // Check if all of the operands are undefs.
14309   EVT VT = N->getValueType(0);
14310   if (ISD::allOperandsUndef(N))
14311     return DAG.getUNDEF(VT);
14312
14313   // Optimize concat_vectors where all but the first of the vectors are undef.
14314   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14315         return Op.isUndef();
14316       })) {
14317     SDValue In = N->getOperand(0);
14318     assert(In.getValueType().isVector() && "Must concat vectors");
14319
14320     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14321     if (In->getOpcode() == ISD::BITCAST &&
14322         !In->getOperand(0)->getValueType(0).isVector()) {
14323       SDValue Scalar = In->getOperand(0);
14324
14325       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14326       // look through the trunc so we can still do the transform:
14327       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14328       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14329           !TLI.isTypeLegal(Scalar.getValueType()) &&
14330           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14331         Scalar = Scalar->getOperand(0);
14332
14333       EVT SclTy = Scalar->getValueType(0);
14334
14335       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14336         return SDValue();
14337
14338       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14339       if (VNTNumElms < 2)
14340         return SDValue();
14341
14342       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14343       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14344         return SDValue();
14345
14346       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14347       return DAG.getBitcast(VT, Res);
14348     }
14349   }
14350
14351   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14352   // We have already tested above for an UNDEF only concatenation.
14353   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14354   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14355   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14356     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14357   };
14358   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14359     SmallVector<SDValue, 8> Opnds;
14360     EVT SVT = VT.getScalarType();
14361
14362     EVT MinVT = SVT;
14363     if (!SVT.isFloatingPoint()) {
14364       // If BUILD_VECTOR are from built from integer, they may have different
14365       // operand types. Get the smallest type and truncate all operands to it.
14366       bool FoundMinVT = false;
14367       for (const SDValue &Op : N->ops())
14368         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14369           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14370           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14371           FoundMinVT = true;
14372         }
14373       assert(FoundMinVT && "Concat vector type mismatch");
14374     }
14375
14376     for (const SDValue &Op : N->ops()) {
14377       EVT OpVT = Op.getValueType();
14378       unsigned NumElts = OpVT.getVectorNumElements();
14379
14380       if (ISD::UNDEF == Op.getOpcode())
14381         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14382
14383       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14384         if (SVT.isFloatingPoint()) {
14385           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14386           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14387         } else {
14388           for (unsigned i = 0; i != NumElts; ++i)
14389             Opnds.push_back(
14390                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14391         }
14392       }
14393     }
14394
14395     assert(VT.getVectorNumElements() == Opnds.size() &&
14396            "Concat vector type mismatch");
14397     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14398   }
14399
14400   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14401   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14402     return V;
14403
14404   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14405   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14406     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14407       return V;
14408
14409   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14410   // nodes often generate nop CONCAT_VECTOR nodes.
14411   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14412   // place the incoming vectors at the exact same location.
14413   SDValue SingleSource = SDValue();
14414   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14415
14416   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14417     SDValue Op = N->getOperand(i);
14418
14419     if (Op.isUndef())
14420       continue;
14421
14422     // Check if this is the identity extract:
14423     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14424       return SDValue();
14425
14426     // Find the single incoming vector for the extract_subvector.
14427     if (SingleSource.getNode()) {
14428       if (Op.getOperand(0) != SingleSource)
14429         return SDValue();
14430     } else {
14431       SingleSource = Op.getOperand(0);
14432
14433       // Check the source type is the same as the type of the result.
14434       // If not, this concat may extend the vector, so we can not
14435       // optimize it away.
14436       if (SingleSource.getValueType() != N->getValueType(0))
14437         return SDValue();
14438     }
14439
14440     unsigned IdentityIndex = i * PartNumElem;
14441     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14442     // The extract index must be constant.
14443     if (!CS)
14444       return SDValue();
14445
14446     // Check that we are reading from the identity index.
14447     if (CS->getZExtValue() != IdentityIndex)
14448       return SDValue();
14449   }
14450
14451   if (SingleSource.getNode())
14452     return SingleSource;
14453
14454   return SDValue();
14455 }
14456
14457 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14458   EVT NVT = N->getValueType(0);
14459   SDValue V = N->getOperand(0);
14460
14461   // Extract from UNDEF is UNDEF.
14462   if (V.isUndef())
14463     return DAG.getUNDEF(NVT);
14464
14465   // Combine:
14466   //    (extract_subvec (concat V1, V2, ...), i)
14467   // Into:
14468   //    Vi if possible
14469   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14470   // type.
14471   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14472       isa<ConstantSDNode>(N->getOperand(1)) &&
14473       V->getOperand(0).getValueType() == NVT) {
14474     unsigned Idx = N->getConstantOperandVal(1);
14475     unsigned NumElems = NVT.getVectorNumElements();
14476     assert((Idx % NumElems) == 0 &&
14477            "IDX in concat is not a multiple of the result vector length.");
14478     return V->getOperand(Idx / NumElems);
14479   }
14480
14481   // Skip bitcasting
14482   if (V->getOpcode() == ISD::BITCAST)
14483     V = V.getOperand(0);
14484
14485   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14486     // Handle only simple case where vector being inserted and vector
14487     // being extracted are of same size.
14488     EVT SmallVT = V->getOperand(1).getValueType();
14489     if (!NVT.bitsEq(SmallVT))
14490       return SDValue();
14491
14492     // Only handle cases where both indexes are constants.
14493     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14494     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14495
14496     if (InsIdx && ExtIdx) {
14497       // Combine:
14498       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14499       // Into:
14500       //    indices are equal or bit offsets are equal => V1
14501       //    otherwise => (extract_subvec V1, ExtIdx)
14502       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14503           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14504         return DAG.getBitcast(NVT, V->getOperand(1));
14505       return DAG.getNode(
14506           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14507           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14508           N->getOperand(1));
14509     }
14510   }
14511
14512   return SDValue();
14513 }
14514
14515 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14516                                                  SDValue V, SelectionDAG &DAG) {
14517   SDLoc DL(V);
14518   EVT VT = V.getValueType();
14519
14520   switch (V.getOpcode()) {
14521   default:
14522     return V;
14523
14524   case ISD::CONCAT_VECTORS: {
14525     EVT OpVT = V->getOperand(0).getValueType();
14526     int OpSize = OpVT.getVectorNumElements();
14527     SmallBitVector OpUsedElements(OpSize, false);
14528     bool FoundSimplification = false;
14529     SmallVector<SDValue, 4> NewOps;
14530     NewOps.reserve(V->getNumOperands());
14531     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14532       SDValue Op = V->getOperand(i);
14533       bool OpUsed = false;
14534       for (int j = 0; j < OpSize; ++j)
14535         if (UsedElements[i * OpSize + j]) {
14536           OpUsedElements[j] = true;
14537           OpUsed = true;
14538         }
14539       NewOps.push_back(
14540           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14541                  : DAG.getUNDEF(OpVT));
14542       FoundSimplification |= Op == NewOps.back();
14543       OpUsedElements.reset();
14544     }
14545     if (FoundSimplification)
14546       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14547     return V;
14548   }
14549
14550   case ISD::INSERT_SUBVECTOR: {
14551     SDValue BaseV = V->getOperand(0);
14552     SDValue SubV = V->getOperand(1);
14553     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14554     if (!IdxN)
14555       return V;
14556
14557     int SubSize = SubV.getValueType().getVectorNumElements();
14558     int Idx = IdxN->getZExtValue();
14559     bool SubVectorUsed = false;
14560     SmallBitVector SubUsedElements(SubSize, false);
14561     for (int i = 0; i < SubSize; ++i)
14562       if (UsedElements[i + Idx]) {
14563         SubVectorUsed = true;
14564         SubUsedElements[i] = true;
14565         UsedElements[i + Idx] = false;
14566       }
14567
14568     // Now recurse on both the base and sub vectors.
14569     SDValue SimplifiedSubV =
14570         SubVectorUsed
14571             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14572             : DAG.getUNDEF(SubV.getValueType());
14573     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14574     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14575       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14576                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14577     return V;
14578   }
14579   }
14580 }
14581
14582 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14583                                        SDValue N1, SelectionDAG &DAG) {
14584   EVT VT = SVN->getValueType(0);
14585   int NumElts = VT.getVectorNumElements();
14586   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14587   for (int M : SVN->getMask())
14588     if (M >= 0 && M < NumElts)
14589       N0UsedElements[M] = true;
14590     else if (M >= NumElts)
14591       N1UsedElements[M - NumElts] = true;
14592
14593   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14594   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14595   if (S0 == N0 && S1 == N1)
14596     return SDValue();
14597
14598   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14599 }
14600
14601 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14602 // or turn a shuffle of a single concat into simpler shuffle then concat.
14603 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14604   EVT VT = N->getValueType(0);
14605   unsigned NumElts = VT.getVectorNumElements();
14606
14607   SDValue N0 = N->getOperand(0);
14608   SDValue N1 = N->getOperand(1);
14609   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14610
14611   SmallVector<SDValue, 4> Ops;
14612   EVT ConcatVT = N0.getOperand(0).getValueType();
14613   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14614   unsigned NumConcats = NumElts / NumElemsPerConcat;
14615
14616   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14617   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14618   // half vector elements.
14619   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14620       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14621                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14622     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14623                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14624     N1 = DAG.getUNDEF(ConcatVT);
14625     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14626   }
14627
14628   // Look at every vector that's inserted. We're looking for exact
14629   // subvector-sized copies from a concatenated vector
14630   for (unsigned I = 0; I != NumConcats; ++I) {
14631     // Make sure we're dealing with a copy.
14632     unsigned Begin = I * NumElemsPerConcat;
14633     bool AllUndef = true, NoUndef = true;
14634     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14635       if (SVN->getMaskElt(J) >= 0)
14636         AllUndef = false;
14637       else
14638         NoUndef = false;
14639     }
14640
14641     if (NoUndef) {
14642       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14643         return SDValue();
14644
14645       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14646         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14647           return SDValue();
14648
14649       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14650       if (FirstElt < N0.getNumOperands())
14651         Ops.push_back(N0.getOperand(FirstElt));
14652       else
14653         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14654
14655     } else if (AllUndef) {
14656       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14657     } else { // Mixed with general masks and undefs, can't do optimization.
14658       return SDValue();
14659     }
14660   }
14661
14662   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14663 }
14664
14665 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14666 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14667 //
14668 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14669 // a simplification in some sense, but it isn't appropriate in general: some
14670 // BUILD_VECTORs are substantially cheaper than others. The general case
14671 // of a BUILD_VECTOR requires inserting each element individually (or
14672 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14673 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14674 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14675 // are undef lowers to a small number of element insertions.
14676 //
14677 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14678 // We don't fold shuffles where one side is a non-zero constant, and we don't
14679 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14680 // non-constant operands. This seems to work out reasonably well in practice.
14681 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14682                                        SelectionDAG &DAG,
14683                                        const TargetLowering &TLI) {
14684   EVT VT = SVN->getValueType(0);
14685   unsigned NumElts = VT.getVectorNumElements();
14686   SDValue N0 = SVN->getOperand(0);
14687   SDValue N1 = SVN->getOperand(1);
14688
14689   if (!N0->hasOneUse() || !N1->hasOneUse())
14690     return SDValue();
14691   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14692   // discussed above.
14693   if (!N1.isUndef()) {
14694     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14695     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14696     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14697       return SDValue();
14698     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14699       return SDValue();
14700   }
14701
14702   SmallVector<SDValue, 8> Ops;
14703   SmallSet<SDValue, 16> DuplicateOps;
14704   for (int M : SVN->getMask()) {
14705     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14706     if (M >= 0) {
14707       int Idx = M < (int)NumElts ? M : M - NumElts;
14708       SDValue &S = (M < (int)NumElts ? N0 : N1);
14709       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14710         Op = S.getOperand(Idx);
14711       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14712         if (Idx == 0)
14713           Op = S.getOperand(0);
14714       } else {
14715         // Operand can't be combined - bail out.
14716         return SDValue();
14717       }
14718     }
14719
14720     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14721     // fine, but it's likely to generate low-quality code if the target can't
14722     // reconstruct an appropriate shuffle.
14723     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14724       if (!DuplicateOps.insert(Op).second)
14725         return SDValue();
14726
14727     Ops.push_back(Op);
14728   }
14729   // BUILD_VECTOR requires all inputs to be of the same type, find the
14730   // maximum type and extend them all.
14731   EVT SVT = VT.getScalarType();
14732   if (SVT.isInteger())
14733     for (SDValue &Op : Ops)
14734       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14735   if (SVT != VT.getScalarType())
14736     for (SDValue &Op : Ops)
14737       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14738                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14739                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14740   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14741 }
14742
14743 // Match shuffles that can be converted to any_vector_extend_in_reg.
14744 // This is often generated during legalization.
14745 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14746 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14747 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14748                                      SelectionDAG &DAG,
14749                                      const TargetLowering &TLI,
14750                                      bool LegalOperations) {
14751   EVT VT = SVN->getValueType(0);
14752   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14753
14754   // TODO Add support for big-endian when we have a test case.
14755   if (!VT.isInteger() || IsBigEndian)
14756     return SDValue();
14757
14758   unsigned NumElts = VT.getVectorNumElements();
14759   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14760   ArrayRef<int> Mask = SVN->getMask();
14761   SDValue N0 = SVN->getOperand(0);
14762
14763   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14764   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14765     for (unsigned i = 0; i != NumElts; ++i) {
14766       if (Mask[i] < 0)
14767         continue;
14768       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14769         continue;
14770       return false;
14771     }
14772     return true;
14773   };
14774
14775   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14776   // power-of-2 extensions as they are the most likely.
14777   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14778     if (!isAnyExtend(Scale))
14779       continue;
14780
14781     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14782     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14783     if (!LegalOperations ||
14784         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14785       return DAG.getBitcast(VT,
14786                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14787   }
14788
14789   return SDValue();
14790 }
14791
14792 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14793 // each source element of a large type into the lowest elements of a smaller
14794 // destination type. This is often generated during legalization.
14795 // If the source node itself was a '*_extend_vector_inreg' node then we should
14796 // then be able to remove it.
14797 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
14798   EVT VT = SVN->getValueType(0);
14799   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14800
14801   // TODO Add support for big-endian when we have a test case.
14802   if (!VT.isInteger() || IsBigEndian)
14803     return SDValue();
14804
14805   SDValue N0 = SVN->getOperand(0);
14806   while (N0.getOpcode() == ISD::BITCAST)
14807     N0 = N0.getOperand(0);
14808
14809   unsigned Opcode = N0.getOpcode();
14810   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14811       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14812       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14813     return SDValue();
14814
14815   SDValue N00 = N0.getOperand(0);
14816   ArrayRef<int> Mask = SVN->getMask();
14817   unsigned NumElts = VT.getVectorNumElements();
14818   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14819   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14820
14821   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14822   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14823   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14824   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14825     for (unsigned i = 0; i != NumElts; ++i) {
14826       if (Mask[i] < 0)
14827         continue;
14828       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14829         continue;
14830       return false;
14831     }
14832     return true;
14833   };
14834
14835   // At the moment we just handle the case where we've truncated back to the
14836   // same size as before the extension.
14837   // TODO: handle more extension/truncation cases as cases arise.
14838   if (EltSizeInBits != ExtSrcSizeInBits)
14839     return SDValue();
14840
14841   // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14842   // power-of-2 truncations as they are the most likely.
14843   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14844     if (isTruncate(Scale))
14845       return DAG.getBitcast(VT, N00);
14846
14847   return SDValue();
14848 }
14849
14850 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14851   EVT VT = N->getValueType(0);
14852   unsigned NumElts = VT.getVectorNumElements();
14853
14854   SDValue N0 = N->getOperand(0);
14855   SDValue N1 = N->getOperand(1);
14856
14857   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14858
14859   // Canonicalize shuffle undef, undef -> undef
14860   if (N0.isUndef() && N1.isUndef())
14861     return DAG.getUNDEF(VT);
14862
14863   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14864
14865   // Canonicalize shuffle v, v -> v, undef
14866   if (N0 == N1) {
14867     SmallVector<int, 8> NewMask;
14868     for (unsigned i = 0; i != NumElts; ++i) {
14869       int Idx = SVN->getMaskElt(i);
14870       if (Idx >= (int)NumElts) Idx -= NumElts;
14871       NewMask.push_back(Idx);
14872     }
14873     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14874   }
14875
14876   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
14877   if (N0.isUndef())
14878     return DAG.getCommutedVectorShuffle(*SVN);
14879
14880   // Remove references to rhs if it is undef
14881   if (N1.isUndef()) {
14882     bool Changed = false;
14883     SmallVector<int, 8> NewMask;
14884     for (unsigned i = 0; i != NumElts; ++i) {
14885       int Idx = SVN->getMaskElt(i);
14886       if (Idx >= (int)NumElts) {
14887         Idx = -1;
14888         Changed = true;
14889       }
14890       NewMask.push_back(Idx);
14891     }
14892     if (Changed)
14893       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14894   }
14895
14896   // If it is a splat, check if the argument vector is another splat or a
14897   // build_vector.
14898   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14899     SDNode *V = N0.getNode();
14900
14901     // If this is a bit convert that changes the element type of the vector but
14902     // not the number of vector elements, look through it.  Be careful not to
14903     // look though conversions that change things like v4f32 to v2f64.
14904     if (V->getOpcode() == ISD::BITCAST) {
14905       SDValue ConvInput = V->getOperand(0);
14906       if (ConvInput.getValueType().isVector() &&
14907           ConvInput.getValueType().getVectorNumElements() == NumElts)
14908         V = ConvInput.getNode();
14909     }
14910
14911     if (V->getOpcode() == ISD::BUILD_VECTOR) {
14912       assert(V->getNumOperands() == NumElts &&
14913              "BUILD_VECTOR has wrong number of operands");
14914       SDValue Base;
14915       bool AllSame = true;
14916       for (unsigned i = 0; i != NumElts; ++i) {
14917         if (!V->getOperand(i).isUndef()) {
14918           Base = V->getOperand(i);
14919           break;
14920         }
14921       }
14922       // Splat of <u, u, u, u>, return <u, u, u, u>
14923       if (!Base.getNode())
14924         return N0;
14925       for (unsigned i = 0; i != NumElts; ++i) {
14926         if (V->getOperand(i) != Base) {
14927           AllSame = false;
14928           break;
14929         }
14930       }
14931       // Splat of <x, x, x, x>, return <x, x, x, x>
14932       if (AllSame)
14933         return N0;
14934
14935       // Canonicalize any other splat as a build_vector.
14936       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14937       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14938       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14939
14940       // We may have jumped through bitcasts, so the type of the
14941       // BUILD_VECTOR may not match the type of the shuffle.
14942       if (V->getValueType(0) != VT)
14943         NewBV = DAG.getBitcast(VT, NewBV);
14944       return NewBV;
14945     }
14946   }
14947
14948   // There are various patterns used to build up a vector from smaller vectors,
14949   // subvectors, or elements. Scan chains of these and replace unused insertions
14950   // or components with undef.
14951   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14952     return S;
14953
14954   // Match shuffles that can be converted to any_vector_extend_in_reg.
14955   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
14956     return V;
14957
14958   // Combine "truncate_vector_in_reg" style shuffles.
14959   if (SDValue V = combineTruncationShuffle(SVN, DAG))
14960     return V;
14961
14962   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14963       Level < AfterLegalizeVectorOps &&
14964       (N1.isUndef() ||
14965       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14966        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14967     if (SDValue V = partitionShuffleOfConcats(N, DAG))
14968       return V;
14969   }
14970
14971   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14972   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14973   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14974     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14975       return Res;
14976
14977   // If this shuffle only has a single input that is a bitcasted shuffle,
14978   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
14979   // back to their original types.
14980   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
14981       N1.isUndef() && Level < AfterLegalizeVectorOps &&
14982       TLI.isTypeLegal(VT)) {
14983
14984     // Peek through the bitcast only if there is one user.
14985     SDValue BC0 = N0;
14986     while (BC0.getOpcode() == ISD::BITCAST) {
14987       if (!BC0.hasOneUse())
14988         break;
14989       BC0 = BC0.getOperand(0);
14990     }
14991
14992     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
14993       if (Scale == 1)
14994         return SmallVector<int, 8>(Mask.begin(), Mask.end());
14995
14996       SmallVector<int, 8> NewMask;
14997       for (int M : Mask)
14998         for (int s = 0; s != Scale; ++s)
14999           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15000       return NewMask;
15001     };
15002
15003     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15004       EVT SVT = VT.getScalarType();
15005       EVT InnerVT = BC0->getValueType(0);
15006       EVT InnerSVT = InnerVT.getScalarType();
15007
15008       // Determine which shuffle works with the smaller scalar type.
15009       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15010       EVT ScaleSVT = ScaleVT.getScalarType();
15011
15012       if (TLI.isTypeLegal(ScaleVT) &&
15013           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15014           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15015
15016         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15017         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15018
15019         // Scale the shuffle masks to the smaller scalar type.
15020         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15021         SmallVector<int, 8> InnerMask =
15022             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15023         SmallVector<int, 8> OuterMask =
15024             ScaleShuffleMask(SVN->getMask(), OuterScale);
15025
15026         // Merge the shuffle masks.
15027         SmallVector<int, 8> NewMask;
15028         for (int M : OuterMask)
15029           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15030
15031         // Test for shuffle mask legality over both commutations.
15032         SDValue SV0 = BC0->getOperand(0);
15033         SDValue SV1 = BC0->getOperand(1);
15034         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15035         if (!LegalMask) {
15036           std::swap(SV0, SV1);
15037           ShuffleVectorSDNode::commuteMask(NewMask);
15038           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15039         }
15040
15041         if (LegalMask) {
15042           SV0 = DAG.getBitcast(ScaleVT, SV0);
15043           SV1 = DAG.getBitcast(ScaleVT, SV1);
15044           return DAG.getBitcast(
15045               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15046         }
15047       }
15048     }
15049   }
15050
15051   // Canonicalize shuffles according to rules:
15052   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15053   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15054   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15055   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15056       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15057       TLI.isTypeLegal(VT)) {
15058     // The incoming shuffle must be of the same type as the result of the
15059     // current shuffle.
15060     assert(N1->getOperand(0).getValueType() == VT &&
15061            "Shuffle types don't match");
15062
15063     SDValue SV0 = N1->getOperand(0);
15064     SDValue SV1 = N1->getOperand(1);
15065     bool HasSameOp0 = N0 == SV0;
15066     bool IsSV1Undef = SV1.isUndef();
15067     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15068       // Commute the operands of this shuffle so that next rule
15069       // will trigger.
15070       return DAG.getCommutedVectorShuffle(*SVN);
15071   }
15072
15073   // Try to fold according to rules:
15074   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15075   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15076   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15077   // Don't try to fold shuffles with illegal type.
15078   // Only fold if this shuffle is the only user of the other shuffle.
15079   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15080       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15081     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15082
15083     // Don't try to fold splats; they're likely to simplify somehow, or they
15084     // might be free.
15085     if (OtherSV->isSplat())
15086       return SDValue();
15087
15088     // The incoming shuffle must be of the same type as the result of the
15089     // current shuffle.
15090     assert(OtherSV->getOperand(0).getValueType() == VT &&
15091            "Shuffle types don't match");
15092
15093     SDValue SV0, SV1;
15094     SmallVector<int, 4> Mask;
15095     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15096     // operand, and SV1 as the second operand.
15097     for (unsigned i = 0; i != NumElts; ++i) {
15098       int Idx = SVN->getMaskElt(i);
15099       if (Idx < 0) {
15100         // Propagate Undef.
15101         Mask.push_back(Idx);
15102         continue;
15103       }
15104
15105       SDValue CurrentVec;
15106       if (Idx < (int)NumElts) {
15107         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15108         // shuffle mask to identify which vector is actually referenced.
15109         Idx = OtherSV->getMaskElt(Idx);
15110         if (Idx < 0) {
15111           // Propagate Undef.
15112           Mask.push_back(Idx);
15113           continue;
15114         }
15115
15116         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15117                                            : OtherSV->getOperand(1);
15118       } else {
15119         // This shuffle index references an element within N1.
15120         CurrentVec = N1;
15121       }
15122
15123       // Simple case where 'CurrentVec' is UNDEF.
15124       if (CurrentVec.isUndef()) {
15125         Mask.push_back(-1);
15126         continue;
15127       }
15128
15129       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15130       // will be the first or second operand of the combined shuffle.
15131       Idx = Idx % NumElts;
15132       if (!SV0.getNode() || SV0 == CurrentVec) {
15133         // Ok. CurrentVec is the left hand side.
15134         // Update the mask accordingly.
15135         SV0 = CurrentVec;
15136         Mask.push_back(Idx);
15137         continue;
15138       }
15139
15140       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15141       if (SV1.getNode() && SV1 != CurrentVec)
15142         return SDValue();
15143
15144       // Ok. CurrentVec is the right hand side.
15145       // Update the mask accordingly.
15146       SV1 = CurrentVec;
15147       Mask.push_back(Idx + NumElts);
15148     }
15149
15150     // Check if all indices in Mask are Undef. In case, propagate Undef.
15151     bool isUndefMask = true;
15152     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15153       isUndefMask &= Mask[i] < 0;
15154
15155     if (isUndefMask)
15156       return DAG.getUNDEF(VT);
15157
15158     if (!SV0.getNode())
15159       SV0 = DAG.getUNDEF(VT);
15160     if (!SV1.getNode())
15161       SV1 = DAG.getUNDEF(VT);
15162
15163     // Avoid introducing shuffles with illegal mask.
15164     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15165       ShuffleVectorSDNode::commuteMask(Mask);
15166
15167       if (!TLI.isShuffleMaskLegal(Mask, VT))
15168         return SDValue();
15169
15170       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15171       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15172       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15173       std::swap(SV0, SV1);
15174     }
15175
15176     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15177     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15178     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15179     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15180   }
15181
15182   return SDValue();
15183 }
15184
15185 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15186   SDValue InVal = N->getOperand(0);
15187   EVT VT = N->getValueType(0);
15188
15189   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15190   // with a VECTOR_SHUFFLE.
15191   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15192     SDValue InVec = InVal->getOperand(0);
15193     SDValue EltNo = InVal->getOperand(1);
15194
15195     // FIXME: We could support implicit truncation if the shuffle can be
15196     // scaled to a smaller vector scalar type.
15197     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15198     if (C0 && VT == InVec.getValueType() &&
15199         VT.getScalarType() == InVal.getValueType()) {
15200       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15201       int Elt = C0->getZExtValue();
15202       NewMask[0] = Elt;
15203
15204       if (TLI.isShuffleMaskLegal(NewMask, VT))
15205         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15206                                     NewMask);
15207     }
15208   }
15209
15210   return SDValue();
15211 }
15212
15213 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15214   EVT VT = N->getValueType(0);
15215   SDValue N0 = N->getOperand(0);
15216   SDValue N1 = N->getOperand(1);
15217   SDValue N2 = N->getOperand(2);
15218
15219   // If inserting an UNDEF, just return the original vector.
15220   if (N1.isUndef())
15221     return N0;
15222
15223   // If this is an insert of an extracted vector into an undef vector, we can
15224   // just use the input to the extract.
15225   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15226       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15227     return N1.getOperand(0);
15228
15229   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15230   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15231   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15232   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15233       N0.getOperand(1).getValueType() == N1.getValueType() &&
15234       N0.getOperand(2) == N2)
15235     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15236                        N1, N2);
15237
15238   if (!isa<ConstantSDNode>(N2))
15239     return SDValue();
15240
15241   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15242
15243   // Canonicalize insert_subvector dag nodes.
15244   // Example:
15245   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15246   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15247   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15248       N1.getValueType() == N0.getOperand(1).getValueType() &&
15249       isa<ConstantSDNode>(N0.getOperand(2))) {
15250     unsigned OtherIdx = N0.getConstantOperandVal(2);
15251     if (InsIdx < OtherIdx) {
15252       // Swap nodes.
15253       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15254                                   N0.getOperand(0), N1, N2);
15255       AddToWorklist(NewOp.getNode());
15256       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15257                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15258     }
15259   }
15260
15261   // If the input vector is a concatenation, and the insert replaces
15262   // one of the pieces, we can optimize into a single concat_vectors.
15263   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15264       N0.getOperand(0).getValueType() == N1.getValueType()) {
15265     unsigned Factor = N1.getValueType().getVectorNumElements();
15266
15267     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15268     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15269
15270     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15271   }
15272
15273   return SDValue();
15274 }
15275
15276 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15277   SDValue N0 = N->getOperand(0);
15278
15279   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15280   if (N0->getOpcode() == ISD::FP16_TO_FP)
15281     return N0->getOperand(0);
15282
15283   return SDValue();
15284 }
15285
15286 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15287   SDValue N0 = N->getOperand(0);
15288
15289   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15290   if (N0->getOpcode() == ISD::AND) {
15291     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15292     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15293       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15294                          N0.getOperand(0));
15295     }
15296   }
15297
15298   return SDValue();
15299 }
15300
15301 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15302 /// with the destination vector and a zero vector.
15303 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15304 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15305 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15306   EVT VT = N->getValueType(0);
15307   SDValue LHS = N->getOperand(0);
15308   SDValue RHS = N->getOperand(1);
15309   SDLoc DL(N);
15310
15311   // Make sure we're not running after operation legalization where it
15312   // may have custom lowered the vector shuffles.
15313   if (LegalOperations)
15314     return SDValue();
15315
15316   if (N->getOpcode() != ISD::AND)
15317     return SDValue();
15318
15319   if (RHS.getOpcode() == ISD::BITCAST)
15320     RHS = RHS.getOperand(0);
15321
15322   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15323     return SDValue();
15324
15325   EVT RVT = RHS.getValueType();
15326   unsigned NumElts = RHS.getNumOperands();
15327
15328   // Attempt to create a valid clear mask, splitting the mask into
15329   // sub elements and checking to see if each is
15330   // all zeros or all ones - suitable for shuffle masking.
15331   auto BuildClearMask = [&](int Split) {
15332     int NumSubElts = NumElts * Split;
15333     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15334
15335     SmallVector<int, 8> Indices;
15336     for (int i = 0; i != NumSubElts; ++i) {
15337       int EltIdx = i / Split;
15338       int SubIdx = i % Split;
15339       SDValue Elt = RHS.getOperand(EltIdx);
15340       if (Elt.isUndef()) {
15341         Indices.push_back(-1);
15342         continue;
15343       }
15344
15345       APInt Bits;
15346       if (isa<ConstantSDNode>(Elt))
15347         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15348       else if (isa<ConstantFPSDNode>(Elt))
15349         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15350       else
15351         return SDValue();
15352
15353       // Extract the sub element from the constant bit mask.
15354       if (DAG.getDataLayout().isBigEndian()) {
15355         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15356       } else {
15357         Bits.lshrInPlace(SubIdx * NumSubBits);
15358       }
15359
15360       if (Split > 1)
15361         Bits = Bits.trunc(NumSubBits);
15362
15363       if (Bits.isAllOnesValue())
15364         Indices.push_back(i);
15365       else if (Bits == 0)
15366         Indices.push_back(i + NumSubElts);
15367       else
15368         return SDValue();
15369     }
15370
15371     // Let's see if the target supports this vector_shuffle.
15372     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15373     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15374     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15375       return SDValue();
15376
15377     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15378     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15379                                                    DAG.getBitcast(ClearVT, LHS),
15380                                                    Zero, Indices));
15381   };
15382
15383   // Determine maximum split level (byte level masking).
15384   int MaxSplit = 1;
15385   if (RVT.getScalarSizeInBits() % 8 == 0)
15386     MaxSplit = RVT.getScalarSizeInBits() / 8;
15387
15388   for (int Split = 1; Split <= MaxSplit; ++Split)
15389     if (RVT.getScalarSizeInBits() % Split == 0)
15390       if (SDValue S = BuildClearMask(Split))
15391         return S;
15392
15393   return SDValue();
15394 }
15395
15396 /// Visit a binary vector operation, like ADD.
15397 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15398   assert(N->getValueType(0).isVector() &&
15399          "SimplifyVBinOp only works on vectors!");
15400
15401   SDValue LHS = N->getOperand(0);
15402   SDValue RHS = N->getOperand(1);
15403   SDValue Ops[] = {LHS, RHS};
15404
15405   // See if we can constant fold the vector operation.
15406   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15407           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15408     return Fold;
15409
15410   // Try to convert a constant mask AND into a shuffle clear mask.
15411   if (SDValue Shuffle = XformToShuffleWithZero(N))
15412     return Shuffle;
15413
15414   // Type legalization might introduce new shuffles in the DAG.
15415   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15416   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15417   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15418       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15419       LHS.getOperand(1).isUndef() &&
15420       RHS.getOperand(1).isUndef()) {
15421     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15422     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15423
15424     if (SVN0->getMask().equals(SVN1->getMask())) {
15425       EVT VT = N->getValueType(0);
15426       SDValue UndefVector = LHS.getOperand(1);
15427       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15428                                      LHS.getOperand(0), RHS.getOperand(0),
15429                                      N->getFlags());
15430       AddUsersToWorklist(N);
15431       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15432                                   SVN0->getMask());
15433     }
15434   }
15435
15436   return SDValue();
15437 }
15438
15439 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15440                                     SDValue N2) {
15441   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15442
15443   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15444                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15445
15446   // If we got a simplified select_cc node back from SimplifySelectCC, then
15447   // break it down into a new SETCC node, and a new SELECT node, and then return
15448   // the SELECT node, since we were called with a SELECT node.
15449   if (SCC.getNode()) {
15450     // Check to see if we got a select_cc back (to turn into setcc/select).
15451     // Otherwise, just return whatever node we got back, like fabs.
15452     if (SCC.getOpcode() == ISD::SELECT_CC) {
15453       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15454                                   N0.getValueType(),
15455                                   SCC.getOperand(0), SCC.getOperand(1),
15456                                   SCC.getOperand(4));
15457       AddToWorklist(SETCC.getNode());
15458       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15459                            SCC.getOperand(2), SCC.getOperand(3));
15460     }
15461
15462     return SCC;
15463   }
15464   return SDValue();
15465 }
15466
15467 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15468 /// being selected between, see if we can simplify the select.  Callers of this
15469 /// should assume that TheSelect is deleted if this returns true.  As such, they
15470 /// should return the appropriate thing (e.g. the node) back to the top-level of
15471 /// the DAG combiner loop to avoid it being looked at.
15472 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15473                                     SDValue RHS) {
15474
15475   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15476   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15477   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15478     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15479       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15480       SDValue Sqrt = RHS;
15481       ISD::CondCode CC;
15482       SDValue CmpLHS;
15483       const ConstantFPSDNode *Zero = nullptr;
15484
15485       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15486         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15487         CmpLHS = TheSelect->getOperand(0);
15488         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15489       } else {
15490         // SELECT or VSELECT
15491         SDValue Cmp = TheSelect->getOperand(0);
15492         if (Cmp.getOpcode() == ISD::SETCC) {
15493           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15494           CmpLHS = Cmp.getOperand(0);
15495           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15496         }
15497       }
15498       if (Zero && Zero->isZero() &&
15499           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15500           CC == ISD::SETULT || CC == ISD::SETLT)) {
15501         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15502         CombineTo(TheSelect, Sqrt);
15503         return true;
15504       }
15505     }
15506   }
15507   // Cannot simplify select with vector condition
15508   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15509
15510   // If this is a select from two identical things, try to pull the operation
15511   // through the select.
15512   if (LHS.getOpcode() != RHS.getOpcode() ||
15513       !LHS.hasOneUse() || !RHS.hasOneUse())
15514     return false;
15515
15516   // If this is a load and the token chain is identical, replace the select
15517   // of two loads with a load through a select of the address to load from.
15518   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15519   // constants have been dropped into the constant pool.
15520   if (LHS.getOpcode() == ISD::LOAD) {
15521     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15522     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15523
15524     // Token chains must be identical.
15525     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15526         // Do not let this transformation reduce the number of volatile loads.
15527         LLD->isVolatile() || RLD->isVolatile() ||
15528         // FIXME: If either is a pre/post inc/dec load,
15529         // we'd need to split out the address adjustment.
15530         LLD->isIndexed() || RLD->isIndexed() ||
15531         // If this is an EXTLOAD, the VT's must match.
15532         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15533         // If this is an EXTLOAD, the kind of extension must match.
15534         (LLD->getExtensionType() != RLD->getExtensionType() &&
15535          // The only exception is if one of the extensions is anyext.
15536          LLD->getExtensionType() != ISD::EXTLOAD &&
15537          RLD->getExtensionType() != ISD::EXTLOAD) ||
15538         // FIXME: this discards src value information.  This is
15539         // over-conservative. It would be beneficial to be able to remember
15540         // both potential memory locations.  Since we are discarding
15541         // src value info, don't do the transformation if the memory
15542         // locations are not in the default address space.
15543         LLD->getPointerInfo().getAddrSpace() != 0 ||
15544         RLD->getPointerInfo().getAddrSpace() != 0 ||
15545         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15546                                       LLD->getBasePtr().getValueType()))
15547       return false;
15548
15549     // Check that the select condition doesn't reach either load.  If so,
15550     // folding this will induce a cycle into the DAG.  If not, this is safe to
15551     // xform, so create a select of the addresses.
15552     SDValue Addr;
15553     if (TheSelect->getOpcode() == ISD::SELECT) {
15554       SDNode *CondNode = TheSelect->getOperand(0).getNode();
15555       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15556           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15557         return false;
15558       // The loads must not depend on one another.
15559       if (LLD->isPredecessorOf(RLD) ||
15560           RLD->isPredecessorOf(LLD))
15561         return false;
15562       Addr = DAG.getSelect(SDLoc(TheSelect),
15563                            LLD->getBasePtr().getValueType(),
15564                            TheSelect->getOperand(0), LLD->getBasePtr(),
15565                            RLD->getBasePtr());
15566     } else {  // Otherwise SELECT_CC
15567       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15568       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15569
15570       if ((LLD->hasAnyUseOfValue(1) &&
15571            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15572           (RLD->hasAnyUseOfValue(1) &&
15573            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15574         return false;
15575
15576       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15577                          LLD->getBasePtr().getValueType(),
15578                          TheSelect->getOperand(0),
15579                          TheSelect->getOperand(1),
15580                          LLD->getBasePtr(), RLD->getBasePtr(),
15581                          TheSelect->getOperand(4));
15582     }
15583
15584     SDValue Load;
15585     // It is safe to replace the two loads if they have different alignments,
15586     // but the new load must be the minimum (most restrictive) alignment of the
15587     // inputs.
15588     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15589     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15590     if (!RLD->isInvariant())
15591       MMOFlags &= ~MachineMemOperand::MOInvariant;
15592     if (!RLD->isDereferenceable())
15593       MMOFlags &= ~MachineMemOperand::MODereferenceable;
15594     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15595       // FIXME: Discards pointer and AA info.
15596       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15597                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15598                          MMOFlags);
15599     } else {
15600       // FIXME: Discards pointer and AA info.
15601       Load = DAG.getExtLoad(
15602           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15603                                                   : LLD->getExtensionType(),
15604           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15605           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15606     }
15607
15608     // Users of the select now use the result of the load.
15609     CombineTo(TheSelect, Load);
15610
15611     // Users of the old loads now use the new load's chain.  We know the
15612     // old-load value is dead now.
15613     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15614     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15615     return true;
15616   }
15617
15618   return false;
15619 }
15620
15621 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15622 /// bitwise 'and'.
15623 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15624                                             SDValue N1, SDValue N2, SDValue N3,
15625                                             ISD::CondCode CC) {
15626   // If this is a select where the false operand is zero and the compare is a
15627   // check of the sign bit, see if we can perform the "gzip trick":
15628   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15629   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15630   EVT XType = N0.getValueType();
15631   EVT AType = N2.getValueType();
15632   if (!isNullConstant(N3) || !XType.bitsGE(AType))
15633     return SDValue();
15634
15635   // If the comparison is testing for a positive value, we have to invert
15636   // the sign bit mask, so only do that transform if the target has a bitwise
15637   // 'and not' instruction (the invert is free).
15638   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15639     // (X > -1) ? A : 0
15640     // (X >  0) ? X : 0 <-- This is canonical signed max.
15641     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15642       return SDValue();
15643   } else if (CC == ISD::SETLT) {
15644     // (X <  0) ? A : 0
15645     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
15646     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15647       return SDValue();
15648   } else {
15649     return SDValue();
15650   }
15651
15652   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15653   // constant.
15654   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15655   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15656   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15657     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15658     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15659     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15660     AddToWorklist(Shift.getNode());
15661
15662     if (XType.bitsGT(AType)) {
15663       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15664       AddToWorklist(Shift.getNode());
15665     }
15666
15667     if (CC == ISD::SETGT)
15668       Shift = DAG.getNOT(DL, Shift, AType);
15669
15670     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15671   }
15672
15673   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15674   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15675   AddToWorklist(Shift.getNode());
15676
15677   if (XType.bitsGT(AType)) {
15678     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15679     AddToWorklist(Shift.getNode());
15680   }
15681
15682   if (CC == ISD::SETGT)
15683     Shift = DAG.getNOT(DL, Shift, AType);
15684
15685   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15686 }
15687
15688 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15689 /// where 'cond' is the comparison specified by CC.
15690 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15691                                       SDValue N2, SDValue N3, ISD::CondCode CC,
15692                                       bool NotExtCompare) {
15693   // (x ? y : y) -> y.
15694   if (N2 == N3) return N2;
15695
15696   EVT VT = N2.getValueType();
15697   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15698   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15699
15700   // Determine if the condition we're dealing with is constant
15701   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15702                               N0, N1, CC, DL, false);
15703   if (SCC.getNode()) AddToWorklist(SCC.getNode());
15704
15705   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15706     // fold select_cc true, x, y -> x
15707     // fold select_cc false, x, y -> y
15708     return !SCCC->isNullValue() ? N2 : N3;
15709   }
15710
15711   // Check to see if we can simplify the select into an fabs node
15712   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15713     // Allow either -0.0 or 0.0
15714     if (CFP->isZero()) {
15715       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15716       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15717           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15718           N2 == N3.getOperand(0))
15719         return DAG.getNode(ISD::FABS, DL, VT, N0);
15720
15721       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15722       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15723           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15724           N2.getOperand(0) == N3)
15725         return DAG.getNode(ISD::FABS, DL, VT, N3);
15726     }
15727   }
15728
15729   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15730   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15731   // in it.  This is a win when the constant is not otherwise available because
15732   // it replaces two constant pool loads with one.  We only do this if the FP
15733   // type is known to be legal, because if it isn't, then we are before legalize
15734   // types an we want the other legalization to happen first (e.g. to avoid
15735   // messing with soft float) and if the ConstantFP is not legal, because if
15736   // it is legal, we may not need to store the FP constant in a constant pool.
15737   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15738     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15739       if (TLI.isTypeLegal(N2.getValueType()) &&
15740           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15741                TargetLowering::Legal &&
15742            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15743            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15744           // If both constants have multiple uses, then we won't need to do an
15745           // extra load, they are likely around in registers for other users.
15746           (TV->hasOneUse() || FV->hasOneUse())) {
15747         Constant *Elts[] = {
15748           const_cast<ConstantFP*>(FV->getConstantFPValue()),
15749           const_cast<ConstantFP*>(TV->getConstantFPValue())
15750         };
15751         Type *FPTy = Elts[0]->getType();
15752         const DataLayout &TD = DAG.getDataLayout();
15753
15754         // Create a ConstantArray of the two constants.
15755         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15756         SDValue CPIdx =
15757             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15758                                 TD.getPrefTypeAlignment(FPTy));
15759         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15760
15761         // Get the offsets to the 0 and 1 element of the array so that we can
15762         // select between them.
15763         SDValue Zero = DAG.getIntPtrConstant(0, DL);
15764         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15765         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15766
15767         SDValue Cond = DAG.getSetCC(DL,
15768                                     getSetCCResultType(N0.getValueType()),
15769                                     N0, N1, CC);
15770         AddToWorklist(Cond.getNode());
15771         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15772                                           Cond, One, Zero);
15773         AddToWorklist(CstOffset.getNode());
15774         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15775                             CstOffset);
15776         AddToWorklist(CPIdx.getNode());
15777         return DAG.getLoad(
15778             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15779             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15780             Alignment);
15781       }
15782     }
15783
15784   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15785     return V;
15786
15787   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15788   // where y is has a single bit set.
15789   // A plaintext description would be, we can turn the SELECT_CC into an AND
15790   // when the condition can be materialized as an all-ones register.  Any
15791   // single bit-test can be materialized as an all-ones register with
15792   // shift-left and shift-right-arith.
15793   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15794       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15795     SDValue AndLHS = N0->getOperand(0);
15796     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15797     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15798       // Shift the tested bit over the sign bit.
15799       const APInt &AndMask = ConstAndRHS->getAPIntValue();
15800       SDValue ShlAmt =
15801         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15802                         getShiftAmountTy(AndLHS.getValueType()));
15803       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15804
15805       // Now arithmetic right shift it all the way over, so the result is either
15806       // all-ones, or zero.
15807       SDValue ShrAmt =
15808         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15809                         getShiftAmountTy(Shl.getValueType()));
15810       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15811
15812       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15813     }
15814   }
15815
15816   // fold select C, 16, 0 -> shl C, 4
15817   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15818       TLI.getBooleanContents(N0.getValueType()) ==
15819           TargetLowering::ZeroOrOneBooleanContent) {
15820
15821     // If the caller doesn't want us to simplify this into a zext of a compare,
15822     // don't do it.
15823     if (NotExtCompare && N2C->isOne())
15824       return SDValue();
15825
15826     // Get a SetCC of the condition
15827     // NOTE: Don't create a SETCC if it's not legal on this target.
15828     if (!LegalOperations ||
15829         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15830       SDValue Temp, SCC;
15831       // cast from setcc result type to select result type
15832       if (LegalTypes) {
15833         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15834                             N0, N1, CC);
15835         if (N2.getValueType().bitsLT(SCC.getValueType()))
15836           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15837                                         N2.getValueType());
15838         else
15839           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15840                              N2.getValueType(), SCC);
15841       } else {
15842         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15843         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15844                            N2.getValueType(), SCC);
15845       }
15846
15847       AddToWorklist(SCC.getNode());
15848       AddToWorklist(Temp.getNode());
15849
15850       if (N2C->isOne())
15851         return Temp;
15852
15853       // shl setcc result by log2 n2c
15854       return DAG.getNode(
15855           ISD::SHL, DL, N2.getValueType(), Temp,
15856           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15857                           getShiftAmountTy(Temp.getValueType())));
15858     }
15859   }
15860
15861   // Check to see if this is an integer abs.
15862   // select_cc setg[te] X,  0,  X, -X ->
15863   // select_cc setgt    X, -1,  X, -X ->
15864   // select_cc setl[te] X,  0, -X,  X ->
15865   // select_cc setlt    X,  1, -X,  X ->
15866   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15867   if (N1C) {
15868     ConstantSDNode *SubC = nullptr;
15869     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15870          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15871         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15872       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15873     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15874               (N1C->isOne() && CC == ISD::SETLT)) &&
15875              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15876       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15877
15878     EVT XType = N0.getValueType();
15879     if (SubC && SubC->isNullValue() && XType.isInteger()) {
15880       SDLoc DL(N0);
15881       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15882                                   N0,
15883                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
15884                                          getShiftAmountTy(N0.getValueType())));
15885       SDValue Add = DAG.getNode(ISD::ADD, DL,
15886                                 XType, N0, Shift);
15887       AddToWorklist(Shift.getNode());
15888       AddToWorklist(Add.getNode());
15889       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15890     }
15891   }
15892
15893   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15894   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15895   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15896   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15897   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15898   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15899   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15900   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15901   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15902     SDValue ValueOnZero = N2;
15903     SDValue Count = N3;
15904     // If the condition is NE instead of E, swap the operands.
15905     if (CC == ISD::SETNE)
15906       std::swap(ValueOnZero, Count);
15907     // Check if the value on zero is a constant equal to the bits in the type.
15908     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15909       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15910         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15911         // legal, combine to just cttz.
15912         if ((Count.getOpcode() == ISD::CTTZ ||
15913              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15914             N0 == Count.getOperand(0) &&
15915             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15916           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15917         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15918         // legal, combine to just ctlz.
15919         if ((Count.getOpcode() == ISD::CTLZ ||
15920              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15921             N0 == Count.getOperand(0) &&
15922             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15923           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15924       }
15925     }
15926   }
15927
15928   return SDValue();
15929 }
15930
15931 /// This is a stub for TargetLowering::SimplifySetCC.
15932 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15933                                    ISD::CondCode Cond, const SDLoc &DL,
15934                                    bool foldBooleans) {
15935   TargetLowering::DAGCombinerInfo
15936     DagCombineInfo(DAG, Level, false, this);
15937   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15938 }
15939
15940 /// Given an ISD::SDIV node expressing a divide by constant, return
15941 /// a DAG expression to select that will generate the same value by multiplying
15942 /// by a magic number.
15943 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15944 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15945   // when optimising for minimum size, we don't want to expand a div to a mul
15946   // and a shift.
15947   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15948     return SDValue();
15949
15950   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15951   if (!C)
15952     return SDValue();
15953
15954   // Avoid division by zero.
15955   if (C->isNullValue())
15956     return SDValue();
15957
15958   std::vector<SDNode*> Built;
15959   SDValue S =
15960       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15961
15962   for (SDNode *N : Built)
15963     AddToWorklist(N);
15964   return S;
15965 }
15966
15967 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15968 /// DAG expression that will generate the same value by right shifting.
15969 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15970   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15971   if (!C)
15972     return SDValue();
15973
15974   // Avoid division by zero.
15975   if (C->isNullValue())
15976     return SDValue();
15977
15978   std::vector<SDNode *> Built;
15979   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
15980
15981   for (SDNode *N : Built)
15982     AddToWorklist(N);
15983   return S;
15984 }
15985
15986 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
15987 /// expression that will generate the same value by multiplying by a magic
15988 /// number.
15989 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15990 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
15991   // when optimising for minimum size, we don't want to expand a div to a mul
15992   // and a shift.
15993   if (DAG.getMachineFunction().getFunction()->optForMinSize())
15994     return SDValue();
15995
15996   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15997   if (!C)
15998     return SDValue();
15999
16000   // Avoid division by zero.
16001   if (C->isNullValue())
16002     return SDValue();
16003
16004   std::vector<SDNode*> Built;
16005   SDValue S =
16006       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16007
16008   for (SDNode *N : Built)
16009     AddToWorklist(N);
16010   return S;
16011 }
16012
16013 /// Determines the LogBase2 value for a non-null input value using the
16014 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16015 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16016   EVT VT = V.getValueType();
16017   unsigned EltBits = VT.getScalarSizeInBits();
16018   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16019   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16020   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16021   return LogBase2;
16022 }
16023
16024 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16025 /// For the reciprocal, we need to find the zero of the function:
16026 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16027 ///     =>
16028 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16029 ///     does not require additional intermediate precision]
16030 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16031   if (Level >= AfterLegalizeDAG)
16032     return SDValue();
16033
16034   // TODO: Handle half and/or extended types?
16035   EVT VT = Op.getValueType();
16036   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16037     return SDValue();
16038
16039   // If estimates are explicitly disabled for this function, we're done.
16040   MachineFunction &MF = DAG.getMachineFunction();
16041   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16042   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16043     return SDValue();
16044
16045   // Estimates may be explicitly enabled for this type with a custom number of
16046   // refinement steps.
16047   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16048   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16049     AddToWorklist(Est.getNode());
16050
16051     if (Iterations) {
16052       EVT VT = Op.getValueType();
16053       SDLoc DL(Op);
16054       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16055
16056       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16057       for (int i = 0; i < Iterations; ++i) {
16058         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16059         AddToWorklist(NewEst.getNode());
16060
16061         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16062         AddToWorklist(NewEst.getNode());
16063
16064         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16065         AddToWorklist(NewEst.getNode());
16066
16067         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16068         AddToWorklist(Est.getNode());
16069       }
16070     }
16071     return Est;
16072   }
16073
16074   return SDValue();
16075 }
16076
16077 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16078 /// For the reciprocal sqrt, we need to find the zero of the function:
16079 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16080 ///     =>
16081 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16082 /// As a result, we precompute A/2 prior to the iteration loop.
16083 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16084                                          unsigned Iterations,
16085                                          SDNodeFlags Flags, bool Reciprocal) {
16086   EVT VT = Arg.getValueType();
16087   SDLoc DL(Arg);
16088   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16089
16090   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16091   // this entire sequence requires only one FP constant.
16092   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16093   AddToWorklist(HalfArg.getNode());
16094
16095   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16096   AddToWorklist(HalfArg.getNode());
16097
16098   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16099   for (unsigned i = 0; i < Iterations; ++i) {
16100     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16101     AddToWorklist(NewEst.getNode());
16102
16103     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16104     AddToWorklist(NewEst.getNode());
16105
16106     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16107     AddToWorklist(NewEst.getNode());
16108
16109     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16110     AddToWorklist(Est.getNode());
16111   }
16112
16113   // If non-reciprocal square root is requested, multiply the result by Arg.
16114   if (!Reciprocal) {
16115     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16116     AddToWorklist(Est.getNode());
16117   }
16118
16119   return Est;
16120 }
16121
16122 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16123 /// For the reciprocal sqrt, we need to find the zero of the function:
16124 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16125 ///     =>
16126 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16127 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16128                                          unsigned Iterations,
16129                                          SDNodeFlags Flags, bool Reciprocal) {
16130   EVT VT = Arg.getValueType();
16131   SDLoc DL(Arg);
16132   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16133   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16134
16135   // This routine must enter the loop below to work correctly
16136   // when (Reciprocal == false).
16137   assert(Iterations > 0);
16138
16139   // Newton iterations for reciprocal square root:
16140   // E = (E * -0.5) * ((A * E) * E + -3.0)
16141   for (unsigned i = 0; i < Iterations; ++i) {
16142     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16143     AddToWorklist(AE.getNode());
16144
16145     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16146     AddToWorklist(AEE.getNode());
16147
16148     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16149     AddToWorklist(RHS.getNode());
16150
16151     // When calculating a square root at the last iteration build:
16152     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16153     // (notice a common subexpression)
16154     SDValue LHS;
16155     if (Reciprocal || (i + 1) < Iterations) {
16156       // RSQRT: LHS = (E * -0.5)
16157       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16158     } else {
16159       // SQRT: LHS = (A * E) * -0.5
16160       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16161     }
16162     AddToWorklist(LHS.getNode());
16163
16164     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16165     AddToWorklist(Est.getNode());
16166   }
16167
16168   return Est;
16169 }
16170
16171 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16172 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16173 /// Op can be zero.
16174 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16175                                            bool Reciprocal) {
16176   if (Level >= AfterLegalizeDAG)
16177     return SDValue();
16178
16179   // TODO: Handle half and/or extended types?
16180   EVT VT = Op.getValueType();
16181   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16182     return SDValue();
16183
16184   // If estimates are explicitly disabled for this function, we're done.
16185   MachineFunction &MF = DAG.getMachineFunction();
16186   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16187   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16188     return SDValue();
16189
16190   // Estimates may be explicitly enabled for this type with a custom number of
16191   // refinement steps.
16192   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16193
16194   bool UseOneConstNR = false;
16195   if (SDValue Est =
16196       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16197                           Reciprocal)) {
16198     AddToWorklist(Est.getNode());
16199
16200     if (Iterations) {
16201       Est = UseOneConstNR
16202             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16203             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16204
16205       if (!Reciprocal) {
16206         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16207         // Select out this case and force the answer to 0.0.
16208         EVT VT = Op.getValueType();
16209         SDLoc DL(Op);
16210
16211         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16212         EVT CCVT = getSetCCResultType(VT);
16213         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16214         AddToWorklist(ZeroCmp.getNode());
16215
16216         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16217                           ZeroCmp, FPZero, Est);
16218         AddToWorklist(Est.getNode());
16219       }
16220     }
16221     return Est;
16222   }
16223
16224   return SDValue();
16225 }
16226
16227 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16228   return buildSqrtEstimateImpl(Op, Flags, true);
16229 }
16230
16231 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16232   return buildSqrtEstimateImpl(Op, Flags, false);
16233 }
16234
16235 /// Return true if base is a frame index, which is known not to alias with
16236 /// anything but itself.  Provides base object and offset as results.
16237 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16238                            const GlobalValue *&GV, const void *&CV) {
16239   // Assume it is a primitive operation.
16240   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16241
16242   // If it's an adding a simple constant then integrate the offset.
16243   if (Base.getOpcode() == ISD::ADD) {
16244     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16245       Base = Base.getOperand(0);
16246       Offset += C->getSExtValue();
16247     }
16248   }
16249
16250   // Return the underlying GlobalValue, and update the Offset.  Return false
16251   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16252   // by multiple nodes with different offsets.
16253   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16254     GV = G->getGlobal();
16255     Offset += G->getOffset();
16256     return false;
16257   }
16258
16259   // Return the underlying Constant value, and update the Offset.  Return false
16260   // for ConstantSDNodes since the same constant pool entry may be represented
16261   // by multiple nodes with different offsets.
16262   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16263     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16264                                          : (const void *)C->getConstVal();
16265     Offset += C->getOffset();
16266     return false;
16267   }
16268   // If it's any of the following then it can't alias with anything but itself.
16269   return isa<FrameIndexSDNode>(Base);
16270 }
16271
16272 /// Return true if there is any possibility that the two addresses overlap.
16273 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16274   // If they are the same then they must be aliases.
16275   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16276
16277   // If they are both volatile then they cannot be reordered.
16278   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16279
16280   // If one operation reads from invariant memory, and the other may store, they
16281   // cannot alias. These should really be checking the equivalent of mayWrite,
16282   // but it only matters for memory nodes other than load /store.
16283   if (Op0->isInvariant() && Op1->writeMem())
16284     return false;
16285
16286   if (Op1->isInvariant() && Op0->writeMem())
16287     return false;
16288
16289   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16290   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16291
16292   // Check for BaseIndexOffset matching.
16293   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16294   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16295   if (BasePtr0.equalBaseIndex(BasePtr1))
16296     return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) ||
16297              (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset));
16298
16299   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16300   // modified to use BaseIndexOffset.
16301
16302   // Gather base node and offset information.
16303   SDValue Base0, Base1;
16304   int64_t Offset0, Offset1;
16305   const GlobalValue *GV0, *GV1;
16306   const void *CV0, *CV1;
16307   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16308                                       Base0, Offset0, GV0, CV0);
16309   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16310                                       Base1, Offset1, GV1, CV1);
16311
16312   // If they have the same base address, then check to see if they overlap.
16313   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16314     return !((Offset0 + NumBytes0) <= Offset1 ||
16315              (Offset1 + NumBytes1) <= Offset0);
16316
16317   // It is possible for different frame indices to alias each other, mostly
16318   // when tail call optimization reuses return address slots for arguments.
16319   // To catch this case, look up the actual index of frame indices to compute
16320   // the real alias relationship.
16321   if (IsFrameIndex0 && IsFrameIndex1) {
16322     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16323     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16324     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16325     return !((Offset0 + NumBytes0) <= Offset1 ||
16326              (Offset1 + NumBytes1) <= Offset0);
16327   }
16328
16329   // Otherwise, if we know what the bases are, and they aren't identical, then
16330   // we know they cannot alias.
16331   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16332     return false;
16333
16334   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16335   // compared to the size and offset of the access, we may be able to prove they
16336   // do not alias. This check is conservative for now to catch cases created by
16337   // splitting vector types.
16338   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16339   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16340   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16341   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16342   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16343       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16344     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16345     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16346
16347     // There is no overlap between these relatively aligned accesses of similar
16348     // size. Return no alias.
16349     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16350         (OffAlign1 + NumBytes1) <= OffAlign0)
16351       return false;
16352   }
16353
16354   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16355                    ? CombinerGlobalAA
16356                    : DAG.getSubtarget().useAA();
16357 #ifndef NDEBUG
16358   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16359       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16360     UseAA = false;
16361 #endif
16362
16363   if (UseAA &&
16364       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16365     // Use alias analysis information.
16366     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16367     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16368     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16369     AliasResult AAResult =
16370         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16371                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16372                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16373                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
16374     if (AAResult == NoAlias)
16375       return false;
16376   }
16377
16378   // Otherwise we have to assume they alias.
16379   return true;
16380 }
16381
16382 /// Walk up chain skipping non-aliasing memory nodes,
16383 /// looking for aliasing nodes and adding them to the Aliases vector.
16384 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16385                                    SmallVectorImpl<SDValue> &Aliases) {
16386   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16387   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16388
16389   // Get alias information for node.
16390   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16391
16392   // Starting off.
16393   Chains.push_back(OriginalChain);
16394   unsigned Depth = 0;
16395
16396   // Look at each chain and determine if it is an alias.  If so, add it to the
16397   // aliases list.  If not, then continue up the chain looking for the next
16398   // candidate.
16399   while (!Chains.empty()) {
16400     SDValue Chain = Chains.pop_back_val();
16401
16402     // For TokenFactor nodes, look at each operand and only continue up the
16403     // chain until we reach the depth limit.
16404     //
16405     // FIXME: The depth check could be made to return the last non-aliasing
16406     // chain we found before we hit a tokenfactor rather than the original
16407     // chain.
16408     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16409       Aliases.clear();
16410       Aliases.push_back(OriginalChain);
16411       return;
16412     }
16413
16414     // Don't bother if we've been before.
16415     if (!Visited.insert(Chain.getNode()).second)
16416       continue;
16417
16418     switch (Chain.getOpcode()) {
16419     case ISD::EntryToken:
16420       // Entry token is ideal chain operand, but handled in FindBetterChain.
16421       break;
16422
16423     case ISD::LOAD:
16424     case ISD::STORE: {
16425       // Get alias information for Chain.
16426       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16427           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16428
16429       // If chain is alias then stop here.
16430       if (!(IsLoad && IsOpLoad) &&
16431           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16432         Aliases.push_back(Chain);
16433       } else {
16434         // Look further up the chain.
16435         Chains.push_back(Chain.getOperand(0));
16436         ++Depth;
16437       }
16438       break;
16439     }
16440
16441     case ISD::TokenFactor:
16442       // We have to check each of the operands of the token factor for "small"
16443       // token factors, so we queue them up.  Adding the operands to the queue
16444       // (stack) in reverse order maintains the original order and increases the
16445       // likelihood that getNode will find a matching token factor (CSE.)
16446       if (Chain.getNumOperands() > 16) {
16447         Aliases.push_back(Chain);
16448         break;
16449       }
16450       for (unsigned n = Chain.getNumOperands(); n;)
16451         Chains.push_back(Chain.getOperand(--n));
16452       ++Depth;
16453       break;
16454
16455     case ISD::CopyFromReg:
16456       // Forward past CopyFromReg.
16457       Chains.push_back(Chain.getOperand(0));
16458       ++Depth;
16459       break;
16460
16461     default:
16462       // For all other instructions we will just have to take what we can get.
16463       Aliases.push_back(Chain);
16464       break;
16465     }
16466   }
16467 }
16468
16469 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16470 /// (aliasing node.)
16471 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16472   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16473
16474   // Accumulate all the aliases to this node.
16475   GatherAllAliases(N, OldChain, Aliases);
16476
16477   // If no operands then chain to entry token.
16478   if (Aliases.size() == 0)
16479     return DAG.getEntryNode();
16480
16481   // If a single operand then chain to it.  We don't need to revisit it.
16482   if (Aliases.size() == 1)
16483     return Aliases[0];
16484
16485   // Construct a custom tailored token factor.
16486   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16487 }
16488
16489 // This function tries to collect a bunch of potentially interesting
16490 // nodes to improve the chains of, all at once. This might seem
16491 // redundant, as this function gets called when visiting every store
16492 // node, so why not let the work be done on each store as it's visited?
16493 //
16494 // I believe this is mainly important because MergeConsecutiveStores
16495 // is unable to deal with merging stores of different sizes, so unless
16496 // we improve the chains of all the potential candidates up-front
16497 // before running MergeConsecutiveStores, it might only see some of
16498 // the nodes that will eventually be candidates, and then not be able
16499 // to go from a partially-merged state to the desired final
16500 // fully-merged state.
16501 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16502   // This holds the base pointer, index, and the offset in bytes from the base
16503   // pointer.
16504   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16505
16506   // We must have a base and an offset.
16507   if (!BasePtr.Base.getNode())
16508     return false;
16509
16510   // Do not handle stores to undef base pointers.
16511   if (BasePtr.Base.isUndef())
16512     return false;
16513
16514   SmallVector<StoreSDNode *, 8> ChainedStores;
16515   ChainedStores.push_back(St);
16516
16517   // Walk up the chain and look for nodes with offsets from the same
16518   // base pointer. Stop when reaching an instruction with a different kind
16519   // or instruction which has a different base pointer.
16520   StoreSDNode *Index = St;
16521   while (Index) {
16522     // If the chain has more than one use, then we can't reorder the mem ops.
16523     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16524       break;
16525
16526     if (Index->isVolatile() || Index->isIndexed())
16527       break;
16528
16529     // Find the base pointer and offset for this memory node.
16530     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16531
16532     // Check that the base pointer is the same as the original one.
16533     if (!Ptr.equalBaseIndex(BasePtr))
16534       break;
16535
16536     // Walk up the chain to find the next store node, ignoring any
16537     // intermediate loads. Any other kind of node will halt the loop.
16538     SDNode *NextInChain = Index->getChain().getNode();
16539     while (true) {
16540       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16541         // We found a store node. Use it for the next iteration.
16542         if (STn->isVolatile() || STn->isIndexed()) {
16543           Index = nullptr;
16544           break;
16545         }
16546         ChainedStores.push_back(STn);
16547         Index = STn;
16548         break;
16549       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16550         NextInChain = Ldn->getChain().getNode();
16551         continue;
16552       } else {
16553         Index = nullptr;
16554         break;
16555       }
16556     } // end while
16557   }
16558
16559   // At this point, ChainedStores lists all of the Store nodes
16560   // reachable by iterating up through chain nodes matching the above
16561   // conditions.  For each such store identified, try to find an
16562   // earlier chain to attach the store to which won't violate the
16563   // required ordering.
16564   bool MadeChangeToSt = false;
16565   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16566
16567   for (StoreSDNode *ChainedStore : ChainedStores) {
16568     SDValue Chain = ChainedStore->getChain();
16569     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16570
16571     if (Chain != BetterChain) {
16572       if (ChainedStore == St)
16573         MadeChangeToSt = true;
16574       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16575     }
16576   }
16577
16578   // Do all replacements after finding the replacements to make to avoid making
16579   // the chains more complicated by introducing new TokenFactors.
16580   for (auto Replacement : BetterChains)
16581     replaceStoreChain(Replacement.first, Replacement.second);
16582
16583   return MadeChangeToSt;
16584 }
16585
16586 /// This is the entry point for the file.
16587 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
16588                            CodeGenOpt::Level OptLevel) {
16589   /// This is the main entry point to this class.
16590   DAGCombiner(*this, AA, OptLevel).Run(Level);
16591 }