]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[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 *AA, CodeGenOpt::Level OL)
500         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
501           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
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   // If we've changed things around then replace token factor.
1733   if (Changed) {
1734     SDValue Result;
1735     if (Ops.empty()) {
1736       // The entry token is the only possible outcome.
1737       Result = DAG.getEntryNode();
1738     } else {
1739       if (DidPruneOps) {
1740         SmallVector<SDValue, 8> PrunedOps;
1741         //
1742         for (const SDValue &Op : Ops) {
1743           if (SeenChains.count(Op.getNode()) == 0)
1744             PrunedOps.push_back(Op);
1745         }
1746         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1747       } else {
1748         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1749       }
1750     }
1751     return Result;
1752   }
1753   return SDValue();
1754 }
1755
1756 /// MERGE_VALUES can always be eliminated.
1757 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1758   WorklistRemover DeadNodes(*this);
1759   // Replacing results may cause a different MERGE_VALUES to suddenly
1760   // be CSE'd with N, and carry its uses with it. Iterate until no
1761   // uses remain, to ensure that the node can be safely deleted.
1762   // First add the users of this node to the work list so that they
1763   // can be tried again once they have new operands.
1764   AddUsersToWorklist(N);
1765   do {
1766     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1767       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1768   } while (!N->use_empty());
1769   deleteAndRecombine(N);
1770   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1771 }
1772
1773 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1774 /// ConstantSDNode pointer else nullptr.
1775 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1776   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1777   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1778 }
1779
1780 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1781   auto BinOpcode = BO->getOpcode();
1782   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1783           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1784           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1785           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1786           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1787           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1788           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1789           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1790           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1791          "Unexpected binary operator");
1792
1793   // Bail out if any constants are opaque because we can't constant fold those.
1794   SDValue C1 = BO->getOperand(1);
1795   if (!isConstantOrConstantVector(C1, true) &&
1796       !isConstantFPBuildVectorOrConstantFP(C1))
1797     return SDValue();
1798
1799   // Don't do this unless the old select is going away. We want to eliminate the
1800   // binary operator, not replace a binop with a select.
1801   // TODO: Handle ISD::SELECT_CC.
1802   SDValue Sel = BO->getOperand(0);
1803   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1804     return SDValue();
1805
1806   SDValue CT = Sel.getOperand(1);
1807   if (!isConstantOrConstantVector(CT, true) &&
1808       !isConstantFPBuildVectorOrConstantFP(CT))
1809     return SDValue();
1810
1811   SDValue CF = Sel.getOperand(2);
1812   if (!isConstantOrConstantVector(CF, true) &&
1813       !isConstantFPBuildVectorOrConstantFP(CF))
1814     return SDValue();
1815
1816   // We have a select-of-constants followed by a binary operator with a
1817   // constant. Eliminate the binop by pulling the constant math into the select.
1818   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1819   EVT VT = Sel.getValueType();
1820   SDLoc DL(Sel);
1821   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1822   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1823           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1824          "Failed to constant fold a binop with constant operands");
1825
1826   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1827   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1828           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1829          "Failed to constant fold a binop with constant operands");
1830
1831   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1832 }
1833
1834 SDValue DAGCombiner::visitADD(SDNode *N) {
1835   SDValue N0 = N->getOperand(0);
1836   SDValue N1 = N->getOperand(1);
1837   EVT VT = N0.getValueType();
1838   SDLoc DL(N);
1839
1840   // fold vector ops
1841   if (VT.isVector()) {
1842     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1843       return FoldedVOp;
1844
1845     // fold (add x, 0) -> x, vector edition
1846     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1847       return N0;
1848     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1849       return N1;
1850   }
1851
1852   // fold (add x, undef) -> undef
1853   if (N0.isUndef())
1854     return N0;
1855
1856   if (N1.isUndef())
1857     return N1;
1858
1859   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1860     // canonicalize constant to RHS
1861     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1862       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1863     // fold (add c1, c2) -> c1+c2
1864     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1865                                       N1.getNode());
1866   }
1867
1868   // fold (add x, 0) -> x
1869   if (isNullConstant(N1))
1870     return N0;
1871
1872   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1873     // fold ((c1-A)+c2) -> (c1+c2)-A
1874     if (N0.getOpcode() == ISD::SUB &&
1875         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1876       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1877       return DAG.getNode(ISD::SUB, DL, VT,
1878                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1879                          N0.getOperand(1));
1880     }
1881
1882     // add (sext i1 X), 1 -> zext (not i1 X)
1883     // We don't transform this pattern:
1884     //   add (zext i1 X), -1 -> sext (not i1 X)
1885     // because most (?) targets generate better code for the zext form.
1886     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1887         isOneConstantOrOneSplatConstant(N1)) {
1888       SDValue X = N0.getOperand(0);
1889       if ((!LegalOperations ||
1890            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1891             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1892           X.getScalarValueSizeInBits() == 1) {
1893         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1894         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1895       }
1896     }
1897   }
1898
1899   if (SDValue NewSel = foldBinOpIntoSelect(N))
1900     return NewSel;
1901
1902   // reassociate add
1903   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1904     return RADD;
1905
1906   // fold ((0-A) + B) -> B-A
1907   if (N0.getOpcode() == ISD::SUB &&
1908       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1909     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1910
1911   // fold (A + (0-B)) -> A-B
1912   if (N1.getOpcode() == ISD::SUB &&
1913       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1914     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1915
1916   // fold (A+(B-A)) -> B
1917   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1918     return N1.getOperand(0);
1919
1920   // fold ((B-A)+A) -> B
1921   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1922     return N0.getOperand(0);
1923
1924   // fold (A+(B-(A+C))) to (B-C)
1925   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1926       N0 == N1.getOperand(1).getOperand(0))
1927     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1928                        N1.getOperand(1).getOperand(1));
1929
1930   // fold (A+(B-(C+A))) to (B-C)
1931   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1932       N0 == N1.getOperand(1).getOperand(1))
1933     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1934                        N1.getOperand(1).getOperand(0));
1935
1936   // fold (A+((B-A)+or-C)) to (B+or-C)
1937   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1938       N1.getOperand(0).getOpcode() == ISD::SUB &&
1939       N0 == N1.getOperand(0).getOperand(1))
1940     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1941                        N1.getOperand(1));
1942
1943   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1944   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1945     SDValue N00 = N0.getOperand(0);
1946     SDValue N01 = N0.getOperand(1);
1947     SDValue N10 = N1.getOperand(0);
1948     SDValue N11 = N1.getOperand(1);
1949
1950     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1951       return DAG.getNode(ISD::SUB, DL, VT,
1952                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1953                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1954   }
1955
1956   if (SimplifyDemandedBits(SDValue(N, 0)))
1957     return SDValue(N, 0);
1958
1959   // fold (a+b) -> (a|b) iff a and b share no bits.
1960   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1961       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1962     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1963
1964   if (SDValue Combined = visitADDLike(N0, N1, N))
1965     return Combined;
1966
1967   if (SDValue Combined = visitADDLike(N1, N0, N))
1968     return Combined;
1969
1970   return SDValue();
1971 }
1972
1973 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1974   EVT VT = N0.getValueType();
1975   SDLoc DL(LocReference);
1976
1977   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1978   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1979       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1980     return DAG.getNode(ISD::SUB, DL, VT, N0,
1981                        DAG.getNode(ISD::SHL, DL, VT,
1982                                    N1.getOperand(0).getOperand(1),
1983                                    N1.getOperand(1)));
1984
1985   if (N1.getOpcode() == ISD::AND) {
1986     SDValue AndOp0 = N1.getOperand(0);
1987     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1988     unsigned DestBits = VT.getScalarSizeInBits();
1989
1990     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1991     // and similar xforms where the inner op is either ~0 or 0.
1992     if (NumSignBits == DestBits &&
1993         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1994       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
1995   }
1996
1997   // add (sext i1), X -> sub X, (zext i1)
1998   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1999       N0.getOperand(0).getValueType() == MVT::i1 &&
2000       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2001     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2002     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2003   }
2004
2005   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2006   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2007     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2008     if (TN->getVT() == MVT::i1) {
2009       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2010                                  DAG.getConstant(1, DL, VT));
2011       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2012     }
2013   }
2014
2015   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2016   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2017     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2018                        N0, N1.getOperand(0), N1.getOperand(2));
2019
2020   return SDValue();
2021 }
2022
2023 SDValue DAGCombiner::visitADDC(SDNode *N) {
2024   SDValue N0 = N->getOperand(0);
2025   SDValue N1 = N->getOperand(1);
2026   EVT VT = N0.getValueType();
2027   SDLoc DL(N);
2028
2029   // If the flag result is dead, turn this into an ADD.
2030   if (!N->hasAnyUseOfValue(1))
2031     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2032                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2033
2034   // canonicalize constant to RHS.
2035   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2036   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2037   if (N0C && !N1C)
2038     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2039
2040   // fold (addc x, 0) -> x + no carry out
2041   if (isNullConstant(N1))
2042     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2043                                         DL, MVT::Glue));
2044
2045   // If it cannot overflow, transform into an add.
2046   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2047     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2048                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2049
2050   return SDValue();
2051 }
2052
2053 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2054   SDValue N0 = N->getOperand(0);
2055   SDValue N1 = N->getOperand(1);
2056   EVT VT = N0.getValueType();
2057   if (VT.isVector())
2058     return SDValue();
2059
2060   EVT CarryVT = N->getValueType(1);
2061   SDLoc DL(N);
2062
2063   // If the flag result is dead, turn this into an ADD.
2064   if (!N->hasAnyUseOfValue(1))
2065     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2066                      DAG.getUNDEF(CarryVT));
2067
2068   // canonicalize constant to RHS.
2069   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2070   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2071   if (N0C && !N1C)
2072     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2073
2074   // fold (uaddo x, 0) -> x + no carry out
2075   if (isNullConstant(N1))
2076     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2077
2078   // If it cannot overflow, transform into an add.
2079   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2080     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2081                      DAG.getConstant(0, DL, CarryVT));
2082
2083   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2084     return Combined;
2085
2086   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2087     return Combined;
2088
2089   return SDValue();
2090 }
2091
2092 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2093   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2094   // If Y + 1 cannot overflow.
2095   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2096     SDValue Y = N1.getOperand(0);
2097     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2098     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2099       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2100                          N1.getOperand(2));
2101   }
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitADDE(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   SDValue CarryIn = N->getOperand(2);
2110
2111   // canonicalize constant to RHS
2112   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2113   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2114   if (N0C && !N1C)
2115     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2116                        N1, N0, CarryIn);
2117
2118   // fold (adde x, y, false) -> (addc x, y)
2119   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2120     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2121
2122   return SDValue();
2123 }
2124
2125 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2126   SDValue N0 = N->getOperand(0);
2127   SDValue N1 = N->getOperand(1);
2128   SDValue CarryIn = N->getOperand(2);
2129   SDLoc DL(N);
2130
2131   // canonicalize constant to RHS
2132   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2133   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2134   if (N0C && !N1C)
2135     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2136
2137   // fold (addcarry x, y, false) -> (uaddo x, y)
2138   if (isNullConstant(CarryIn))
2139     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2140
2141   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2142   if (isNullConstant(N0) && isNullConstant(N1)) {
2143     EVT VT = N0.getValueType();
2144     EVT CarryVT = CarryIn.getValueType();
2145     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2146     AddToWorklist(CarryExt.getNode());
2147     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2148                                     DAG.getConstant(1, DL, VT)),
2149                      DAG.getConstant(0, DL, CarryVT));
2150   }
2151
2152   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2153     return Combined;
2154
2155   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2156     return Combined;
2157
2158   return SDValue();
2159 }
2160
2161 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2162                                        SDNode *N) {
2163   // Iff the flag result is dead:
2164   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2165   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) &&
2166       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2167     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2168                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2169
2170   return SDValue();
2171 }
2172
2173 // Since it may not be valid to emit a fold to zero for vector initializers
2174 // check if we can before folding.
2175 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2176                              SelectionDAG &DAG, bool LegalOperations,
2177                              bool LegalTypes) {
2178   if (!VT.isVector())
2179     return DAG.getConstant(0, DL, VT);
2180   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2181     return DAG.getConstant(0, DL, VT);
2182   return SDValue();
2183 }
2184
2185 SDValue DAGCombiner::visitSUB(SDNode *N) {
2186   SDValue N0 = N->getOperand(0);
2187   SDValue N1 = N->getOperand(1);
2188   EVT VT = N0.getValueType();
2189   SDLoc DL(N);
2190
2191   // fold vector ops
2192   if (VT.isVector()) {
2193     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2194       return FoldedVOp;
2195
2196     // fold (sub x, 0) -> x, vector edition
2197     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2198       return N0;
2199   }
2200
2201   // fold (sub x, x) -> 0
2202   // FIXME: Refactor this and xor and other similar operations together.
2203   if (N0 == N1)
2204     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2205   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2206       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2207     // fold (sub c1, c2) -> c1-c2
2208     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2209                                       N1.getNode());
2210   }
2211
2212   if (SDValue NewSel = foldBinOpIntoSelect(N))
2213     return NewSel;
2214
2215   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2216
2217   // fold (sub x, c) -> (add x, -c)
2218   if (N1C) {
2219     return DAG.getNode(ISD::ADD, DL, VT, N0,
2220                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2221   }
2222
2223   if (isNullConstantOrNullSplatConstant(N0)) {
2224     unsigned BitWidth = VT.getScalarSizeInBits();
2225     // Right-shifting everything out but the sign bit followed by negation is
2226     // the same as flipping arithmetic/logical shift type without the negation:
2227     // -(X >>u 31) -> (X >>s 31)
2228     // -(X >>s 31) -> (X >>u 31)
2229     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2230       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2231       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2232         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2233         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2234           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2235       }
2236     }
2237
2238     // 0 - X --> 0 if the sub is NUW.
2239     if (N->getFlags().hasNoUnsignedWrap())
2240       return N0;
2241
2242     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2243       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2244       // N1 must be 0 because negating the minimum signed value is undefined.
2245       if (N->getFlags().hasNoSignedWrap())
2246         return N0;
2247
2248       // 0 - X --> X if X is 0 or the minimum signed value.
2249       return N1;
2250     }
2251   }
2252
2253   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2254   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2255     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2256
2257   // fold A-(A-B) -> B
2258   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2259     return N1.getOperand(1);
2260
2261   // fold (A+B)-A -> B
2262   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2263     return N0.getOperand(1);
2264
2265   // fold (A+B)-B -> A
2266   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2267     return N0.getOperand(0);
2268
2269   // fold C2-(A+C1) -> (C2-C1)-A
2270   if (N1.getOpcode() == ISD::ADD) {
2271     SDValue N11 = N1.getOperand(1);
2272     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2273         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2274       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2275       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2276     }
2277   }
2278
2279   // fold ((A+(B+or-C))-B) -> A+or-C
2280   if (N0.getOpcode() == ISD::ADD &&
2281       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2282        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2283       N0.getOperand(1).getOperand(0) == N1)
2284     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2285                        N0.getOperand(1).getOperand(1));
2286
2287   // fold ((A+(C+B))-B) -> A+C
2288   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2289       N0.getOperand(1).getOperand(1) == N1)
2290     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2291                        N0.getOperand(1).getOperand(0));
2292
2293   // fold ((A-(B-C))-C) -> A-B
2294   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2295       N0.getOperand(1).getOperand(1) == N1)
2296     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2297                        N0.getOperand(1).getOperand(0));
2298
2299   // If either operand of a sub is undef, the result is undef
2300   if (N0.isUndef())
2301     return N0;
2302   if (N1.isUndef())
2303     return N1;
2304
2305   // If the relocation model supports it, consider symbol offsets.
2306   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2307     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2308       // fold (sub Sym, c) -> Sym-c
2309       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2310         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2311                                     GA->getOffset() -
2312                                         (uint64_t)N1C->getSExtValue());
2313       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2314       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2315         if (GA->getGlobal() == GB->getGlobal())
2316           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2317                                  DL, VT);
2318     }
2319
2320   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2321   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2322     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2323     if (TN->getVT() == MVT::i1) {
2324       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2325                                  DAG.getConstant(1, DL, VT));
2326       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2327     }
2328   }
2329
2330   return SDValue();
2331 }
2332
2333 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2334   SDValue N0 = N->getOperand(0);
2335   SDValue N1 = N->getOperand(1);
2336   EVT VT = N0.getValueType();
2337   SDLoc DL(N);
2338
2339   // If the flag result is dead, turn this into an SUB.
2340   if (!N->hasAnyUseOfValue(1))
2341     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2342                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2343
2344   // fold (subc x, x) -> 0 + no borrow
2345   if (N0 == N1)
2346     return CombineTo(N, DAG.getConstant(0, DL, VT),
2347                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2348
2349   // fold (subc x, 0) -> x + no borrow
2350   if (isNullConstant(N1))
2351     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2352
2353   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2354   if (isAllOnesConstant(N0))
2355     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2356                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2357
2358   return SDValue();
2359 }
2360
2361 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2362   SDValue N0 = N->getOperand(0);
2363   SDValue N1 = N->getOperand(1);
2364   EVT VT = N0.getValueType();
2365   if (VT.isVector())
2366     return SDValue();
2367
2368   EVT CarryVT = N->getValueType(1);
2369   SDLoc DL(N);
2370
2371   // If the flag result is dead, turn this into an SUB.
2372   if (!N->hasAnyUseOfValue(1))
2373     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2374                      DAG.getUNDEF(CarryVT));
2375
2376   // fold (usubo x, x) -> 0 + no borrow
2377   if (N0 == N1)
2378     return CombineTo(N, DAG.getConstant(0, DL, VT),
2379                      DAG.getConstant(0, DL, CarryVT));
2380
2381   // fold (usubo x, 0) -> x + no borrow
2382   if (isNullConstant(N1))
2383     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2384
2385   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2386   if (isAllOnesConstant(N0))
2387     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2388                      DAG.getConstant(0, DL, CarryVT));
2389
2390   return SDValue();
2391 }
2392
2393 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2394   SDValue N0 = N->getOperand(0);
2395   SDValue N1 = N->getOperand(1);
2396   SDValue CarryIn = N->getOperand(2);
2397
2398   // fold (sube x, y, false) -> (subc x, y)
2399   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2400     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2401
2402   return SDValue();
2403 }
2404
2405 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2406   SDValue N0 = N->getOperand(0);
2407   SDValue N1 = N->getOperand(1);
2408   SDValue CarryIn = N->getOperand(2);
2409
2410   // fold (subcarry x, y, false) -> (usubo x, y)
2411   if (isNullConstant(CarryIn))
2412     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitMUL(SDNode *N) {
2418   SDValue N0 = N->getOperand(0);
2419   SDValue N1 = N->getOperand(1);
2420   EVT VT = N0.getValueType();
2421
2422   // fold (mul x, undef) -> 0
2423   if (N0.isUndef() || N1.isUndef())
2424     return DAG.getConstant(0, SDLoc(N), VT);
2425
2426   bool N0IsConst = false;
2427   bool N1IsConst = false;
2428   bool N1IsOpaqueConst = false;
2429   bool N0IsOpaqueConst = false;
2430   APInt ConstValue0, ConstValue1;
2431   // fold vector ops
2432   if (VT.isVector()) {
2433     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2434       return FoldedVOp;
2435
2436     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2437     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2438   } else {
2439     N0IsConst = isa<ConstantSDNode>(N0);
2440     if (N0IsConst) {
2441       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2442       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2443     }
2444     N1IsConst = isa<ConstantSDNode>(N1);
2445     if (N1IsConst) {
2446       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2447       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2448     }
2449   }
2450
2451   // fold (mul c1, c2) -> c1*c2
2452   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2453     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2454                                       N0.getNode(), N1.getNode());
2455
2456   // canonicalize constant to RHS (vector doesn't have to splat)
2457   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2458      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2459     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2460   // fold (mul x, 0) -> 0
2461   if (N1IsConst && ConstValue1 == 0)
2462     return N1;
2463   // We require a splat of the entire scalar bit width for non-contiguous
2464   // bit patterns.
2465   bool IsFullSplat =
2466     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2467   // fold (mul x, 1) -> x
2468   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2469     return N0;
2470
2471   if (SDValue NewSel = foldBinOpIntoSelect(N))
2472     return NewSel;
2473
2474   // fold (mul x, -1) -> 0-x
2475   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2476     SDLoc DL(N);
2477     return DAG.getNode(ISD::SUB, DL, VT,
2478                        DAG.getConstant(0, DL, VT), N0);
2479   }
2480   // fold (mul x, (1 << c)) -> x << c
2481   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2482       IsFullSplat) {
2483     SDLoc DL(N);
2484     return DAG.getNode(ISD::SHL, DL, VT, N0,
2485                        DAG.getConstant(ConstValue1.logBase2(), DL,
2486                                        getShiftAmountTy(N0.getValueType())));
2487   }
2488   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2489   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2490       IsFullSplat) {
2491     unsigned Log2Val = (-ConstValue1).logBase2();
2492     SDLoc DL(N);
2493     // FIXME: If the input is something that is easily negated (e.g. a
2494     // single-use add), we should put the negate there.
2495     return DAG.getNode(ISD::SUB, DL, VT,
2496                        DAG.getConstant(0, DL, VT),
2497                        DAG.getNode(ISD::SHL, DL, VT, N0,
2498                             DAG.getConstant(Log2Val, DL,
2499                                       getShiftAmountTy(N0.getValueType()))));
2500   }
2501
2502   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2503   if (N0.getOpcode() == ISD::SHL &&
2504       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2505       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2506     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2507     if (isConstantOrConstantVector(C3))
2508       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2509   }
2510
2511   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2512   // use.
2513   {
2514     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2515
2516     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2517     if (N0.getOpcode() == ISD::SHL &&
2518         isConstantOrConstantVector(N0.getOperand(1)) &&
2519         N0.getNode()->hasOneUse()) {
2520       Sh = N0; Y = N1;
2521     } else if (N1.getOpcode() == ISD::SHL &&
2522                isConstantOrConstantVector(N1.getOperand(1)) &&
2523                N1.getNode()->hasOneUse()) {
2524       Sh = N1; Y = N0;
2525     }
2526
2527     if (Sh.getNode()) {
2528       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2529       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2530     }
2531   }
2532
2533   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2534   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2535       N0.getOpcode() == ISD::ADD &&
2536       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2537       isMulAddWithConstProfitable(N, N0, N1))
2538       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2539                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2540                                      N0.getOperand(0), N1),
2541                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2542                                      N0.getOperand(1), N1));
2543
2544   // reassociate mul
2545   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2546     return RMUL;
2547
2548   return SDValue();
2549 }
2550
2551 /// Return true if divmod libcall is available.
2552 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2553                                      const TargetLowering &TLI) {
2554   RTLIB::Libcall LC;
2555   EVT NodeType = Node->getValueType(0);
2556   if (!NodeType.isSimple())
2557     return false;
2558   switch (NodeType.getSimpleVT().SimpleTy) {
2559   default: return false; // No libcall for vector types.
2560   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2561   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2562   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2563   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2564   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2565   }
2566
2567   return TLI.getLibcallName(LC) != nullptr;
2568 }
2569
2570 /// Issue divrem if both quotient and remainder are needed.
2571 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2572   if (Node->use_empty())
2573     return SDValue(); // This is a dead node, leave it alone.
2574
2575   unsigned Opcode = Node->getOpcode();
2576   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2577   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2578
2579   // DivMod lib calls can still work on non-legal types if using lib-calls.
2580   EVT VT = Node->getValueType(0);
2581   if (VT.isVector() || !VT.isInteger())
2582     return SDValue();
2583
2584   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2585     return SDValue();
2586
2587   // If DIVREM is going to get expanded into a libcall,
2588   // but there is no libcall available, then don't combine.
2589   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2590       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2591     return SDValue();
2592
2593   // If div is legal, it's better to do the normal expansion
2594   unsigned OtherOpcode = 0;
2595   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2596     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2597     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2598       return SDValue();
2599   } else {
2600     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2601     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2602       return SDValue();
2603   }
2604
2605   SDValue Op0 = Node->getOperand(0);
2606   SDValue Op1 = Node->getOperand(1);
2607   SDValue combined;
2608   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2609          UE = Op0.getNode()->use_end(); UI != UE;) {
2610     SDNode *User = *UI++;
2611     if (User == Node || User->use_empty())
2612       continue;
2613     // Convert the other matching node(s), too;
2614     // otherwise, the DIVREM may get target-legalized into something
2615     // target-specific that we won't be able to recognize.
2616     unsigned UserOpc = User->getOpcode();
2617     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2618         User->getOperand(0) == Op0 &&
2619         User->getOperand(1) == Op1) {
2620       if (!combined) {
2621         if (UserOpc == OtherOpcode) {
2622           SDVTList VTs = DAG.getVTList(VT, VT);
2623           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2624         } else if (UserOpc == DivRemOpc) {
2625           combined = SDValue(User, 0);
2626         } else {
2627           assert(UserOpc == Opcode);
2628           continue;
2629         }
2630       }
2631       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2632         CombineTo(User, combined);
2633       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2634         CombineTo(User, combined.getValue(1));
2635     }
2636   }
2637   return combined;
2638 }
2639
2640 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2641   SDValue N0 = N->getOperand(0);
2642   SDValue N1 = N->getOperand(1);
2643   EVT VT = N->getValueType(0);
2644   SDLoc DL(N);
2645
2646   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2647     return DAG.getUNDEF(VT);
2648
2649   // undef / X -> 0
2650   // undef % X -> 0
2651   if (N0.isUndef())
2652     return DAG.getConstant(0, DL, VT);
2653
2654   return SDValue();
2655 }
2656
2657 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2658   SDValue N0 = N->getOperand(0);
2659   SDValue N1 = N->getOperand(1);
2660   EVT VT = N->getValueType(0);
2661
2662   // fold vector ops
2663   if (VT.isVector())
2664     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2665       return FoldedVOp;
2666
2667   SDLoc DL(N);
2668
2669   // fold (sdiv c1, c2) -> c1/c2
2670   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2671   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2672   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2673     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2674   // fold (sdiv X, 1) -> X
2675   if (N1C && N1C->isOne())
2676     return N0;
2677   // fold (sdiv X, -1) -> 0-X
2678   if (N1C && N1C->isAllOnesValue())
2679     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2680
2681   if (SDValue V = simplifyDivRem(N, DAG))
2682     return V;
2683
2684   if (SDValue NewSel = foldBinOpIntoSelect(N))
2685     return NewSel;
2686
2687   // If we know the sign bits of both operands are zero, strength reduce to a
2688   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2689   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2690     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2691
2692   // fold (sdiv X, pow2) -> simple ops after legalize
2693   // FIXME: We check for the exact bit here because the generic lowering gives
2694   // better results in that case. The target-specific lowering should learn how
2695   // to handle exact sdivs efficiently.
2696   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2697       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2698                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2699     // Target-specific implementation of sdiv x, pow2.
2700     if (SDValue Res = BuildSDIVPow2(N))
2701       return Res;
2702
2703     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2704
2705     // Splat the sign bit into the register
2706     SDValue SGN =
2707         DAG.getNode(ISD::SRA, DL, VT, N0,
2708                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2709                                     getShiftAmountTy(N0.getValueType())));
2710     AddToWorklist(SGN.getNode());
2711
2712     // Add (N0 < 0) ? abs2 - 1 : 0;
2713     SDValue SRL =
2714         DAG.getNode(ISD::SRL, DL, VT, SGN,
2715                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2716                                     getShiftAmountTy(SGN.getValueType())));
2717     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2718     AddToWorklist(SRL.getNode());
2719     AddToWorklist(ADD.getNode());    // Divide by pow2
2720     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2721                   DAG.getConstant(lg2, DL,
2722                                   getShiftAmountTy(ADD.getValueType())));
2723
2724     // If we're dividing by a positive value, we're done.  Otherwise, we must
2725     // negate the result.
2726     if (N1C->getAPIntValue().isNonNegative())
2727       return SRA;
2728
2729     AddToWorklist(SRA.getNode());
2730     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2731   }
2732
2733   // If integer divide is expensive and we satisfy the requirements, emit an
2734   // alternate sequence.  Targets may check function attributes for size/speed
2735   // trade-offs.
2736   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2737   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2738     if (SDValue Op = BuildSDIV(N))
2739       return Op;
2740
2741   // sdiv, srem -> sdivrem
2742   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2743   // true.  Otherwise, we break the simplification logic in visitREM().
2744   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2745     if (SDValue DivRem = useDivRem(N))
2746         return DivRem;
2747
2748   return SDValue();
2749 }
2750
2751 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2752   SDValue N0 = N->getOperand(0);
2753   SDValue N1 = N->getOperand(1);
2754   EVT VT = N->getValueType(0);
2755
2756   // fold vector ops
2757   if (VT.isVector())
2758     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2759       return FoldedVOp;
2760
2761   SDLoc DL(N);
2762
2763   // fold (udiv c1, c2) -> c1/c2
2764   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2765   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2766   if (N0C && N1C)
2767     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2768                                                     N0C, N1C))
2769       return Folded;
2770
2771   if (SDValue V = simplifyDivRem(N, DAG))
2772     return V;
2773
2774   if (SDValue NewSel = foldBinOpIntoSelect(N))
2775     return NewSel;
2776
2777   // fold (udiv x, (1 << c)) -> x >>u c
2778   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2779       DAG.isKnownToBeAPowerOfTwo(N1)) {
2780     SDValue LogBase2 = BuildLogBase2(N1, DL);
2781     AddToWorklist(LogBase2.getNode());
2782
2783     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2784     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2785     AddToWorklist(Trunc.getNode());
2786     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2787   }
2788
2789   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2790   if (N1.getOpcode() == ISD::SHL) {
2791     SDValue N10 = N1.getOperand(0);
2792     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2793         DAG.isKnownToBeAPowerOfTwo(N10)) {
2794       SDValue LogBase2 = BuildLogBase2(N10, DL);
2795       AddToWorklist(LogBase2.getNode());
2796
2797       EVT ADDVT = N1.getOperand(1).getValueType();
2798       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2799       AddToWorklist(Trunc.getNode());
2800       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2801       AddToWorklist(Add.getNode());
2802       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2803     }
2804   }
2805
2806   // fold (udiv x, c) -> alternate
2807   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2808   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2809     if (SDValue Op = BuildUDIV(N))
2810       return Op;
2811
2812   // sdiv, srem -> sdivrem
2813   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2814   // true.  Otherwise, we break the simplification logic in visitREM().
2815   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2816     if (SDValue DivRem = useDivRem(N))
2817         return DivRem;
2818
2819   return SDValue();
2820 }
2821
2822 // handles ISD::SREM and ISD::UREM
2823 SDValue DAGCombiner::visitREM(SDNode *N) {
2824   unsigned Opcode = N->getOpcode();
2825   SDValue N0 = N->getOperand(0);
2826   SDValue N1 = N->getOperand(1);
2827   EVT VT = N->getValueType(0);
2828   bool isSigned = (Opcode == ISD::SREM);
2829   SDLoc DL(N);
2830
2831   // fold (rem c1, c2) -> c1%c2
2832   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2833   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2834   if (N0C && N1C)
2835     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2836       return Folded;
2837
2838   if (SDValue V = simplifyDivRem(N, DAG))
2839     return V;
2840
2841   if (SDValue NewSel = foldBinOpIntoSelect(N))
2842     return NewSel;
2843
2844   if (isSigned) {
2845     // If we know the sign bits of both operands are zero, strength reduce to a
2846     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2847     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2848       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2849   } else {
2850     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2851     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2852       // fold (urem x, pow2) -> (and x, pow2-1)
2853       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2854       AddToWorklist(Add.getNode());
2855       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2856     }
2857     if (N1.getOpcode() == ISD::SHL &&
2858         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2859       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2860       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2861       AddToWorklist(Add.getNode());
2862       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2863     }
2864   }
2865
2866   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2867
2868   // If X/C can be simplified by the division-by-constant logic, lower
2869   // X%C to the equivalent of X-X/C*C.
2870   // To avoid mangling nodes, this simplification requires that the combine()
2871   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2872   // against this by skipping the simplification if isIntDivCheap().  When
2873   // div is not cheap, combine will not return a DIVREM.  Regardless,
2874   // checking cheapness here makes sense since the simplification results in
2875   // fatter code.
2876   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2877     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2878     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2879     AddToWorklist(Div.getNode());
2880     SDValue OptimizedDiv = combine(Div.getNode());
2881     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2882       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2883              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2884       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2885       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2886       AddToWorklist(Mul.getNode());
2887       return Sub;
2888     }
2889   }
2890
2891   // sdiv, srem -> sdivrem
2892   if (SDValue DivRem = useDivRem(N))
2893     return DivRem.getValue(1);
2894
2895   return SDValue();
2896 }
2897
2898 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2899   SDValue N0 = N->getOperand(0);
2900   SDValue N1 = N->getOperand(1);
2901   EVT VT = N->getValueType(0);
2902   SDLoc DL(N);
2903
2904   // fold (mulhs x, 0) -> 0
2905   if (isNullConstant(N1))
2906     return N1;
2907   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2908   if (isOneConstant(N1)) {
2909     SDLoc DL(N);
2910     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2911                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2912                                        getShiftAmountTy(N0.getValueType())));
2913   }
2914   // fold (mulhs x, undef) -> 0
2915   if (N0.isUndef() || N1.isUndef())
2916     return DAG.getConstant(0, SDLoc(N), VT);
2917
2918   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2919   // plus a shift.
2920   if (VT.isSimple() && !VT.isVector()) {
2921     MVT Simple = VT.getSimpleVT();
2922     unsigned SimpleSize = Simple.getSizeInBits();
2923     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2924     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2925       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2926       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2927       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2928       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2929             DAG.getConstant(SimpleSize, DL,
2930                             getShiftAmountTy(N1.getValueType())));
2931       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2932     }
2933   }
2934
2935   return SDValue();
2936 }
2937
2938 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2939   SDValue N0 = N->getOperand(0);
2940   SDValue N1 = N->getOperand(1);
2941   EVT VT = N->getValueType(0);
2942   SDLoc DL(N);
2943
2944   // fold (mulhu x, 0) -> 0
2945   if (isNullConstant(N1))
2946     return N1;
2947   // fold (mulhu x, 1) -> 0
2948   if (isOneConstant(N1))
2949     return DAG.getConstant(0, DL, N0.getValueType());
2950   // fold (mulhu x, undef) -> 0
2951   if (N0.isUndef() || N1.isUndef())
2952     return DAG.getConstant(0, DL, VT);
2953
2954   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2955   // plus a shift.
2956   if (VT.isSimple() && !VT.isVector()) {
2957     MVT Simple = VT.getSimpleVT();
2958     unsigned SimpleSize = Simple.getSizeInBits();
2959     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2960     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2961       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2962       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2963       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2964       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2965             DAG.getConstant(SimpleSize, DL,
2966                             getShiftAmountTy(N1.getValueType())));
2967       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2968     }
2969   }
2970
2971   return SDValue();
2972 }
2973
2974 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2975 /// give the opcodes for the two computations that are being performed. Return
2976 /// true if a simplification was made.
2977 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2978                                                 unsigned HiOp) {
2979   // If the high half is not needed, just compute the low half.
2980   bool HiExists = N->hasAnyUseOfValue(1);
2981   if (!HiExists &&
2982       (!LegalOperations ||
2983        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2984     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2985     return CombineTo(N, Res, Res);
2986   }
2987
2988   // If the low half is not needed, just compute the high half.
2989   bool LoExists = N->hasAnyUseOfValue(0);
2990   if (!LoExists &&
2991       (!LegalOperations ||
2992        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2993     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2994     return CombineTo(N, Res, Res);
2995   }
2996
2997   // If both halves are used, return as it is.
2998   if (LoExists && HiExists)
2999     return SDValue();
3000
3001   // If the two computed results can be simplified separately, separate them.
3002   if (LoExists) {
3003     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3004     AddToWorklist(Lo.getNode());
3005     SDValue LoOpt = combine(Lo.getNode());
3006     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3007         (!LegalOperations ||
3008          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3009       return CombineTo(N, LoOpt, LoOpt);
3010   }
3011
3012   if (HiExists) {
3013     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3014     AddToWorklist(Hi.getNode());
3015     SDValue HiOpt = combine(Hi.getNode());
3016     if (HiOpt.getNode() && HiOpt != Hi &&
3017         (!LegalOperations ||
3018          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3019       return CombineTo(N, HiOpt, HiOpt);
3020   }
3021
3022   return SDValue();
3023 }
3024
3025 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3026   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3027     return Res;
3028
3029   EVT VT = N->getValueType(0);
3030   SDLoc DL(N);
3031
3032   // If the type is twice as wide is legal, transform the mulhu to a wider
3033   // multiply plus a shift.
3034   if (VT.isSimple() && !VT.isVector()) {
3035     MVT Simple = VT.getSimpleVT();
3036     unsigned SimpleSize = Simple.getSizeInBits();
3037     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3038     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3039       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3040       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3041       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3042       // Compute the high part as N1.
3043       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3044             DAG.getConstant(SimpleSize, DL,
3045                             getShiftAmountTy(Lo.getValueType())));
3046       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3047       // Compute the low part as N0.
3048       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3049       return CombineTo(N, Lo, Hi);
3050     }
3051   }
3052
3053   return SDValue();
3054 }
3055
3056 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3057   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3058     return Res;
3059
3060   EVT VT = N->getValueType(0);
3061   SDLoc DL(N);
3062
3063   // If the type is twice as wide is legal, transform the mulhu to a wider
3064   // multiply plus a shift.
3065   if (VT.isSimple() && !VT.isVector()) {
3066     MVT Simple = VT.getSimpleVT();
3067     unsigned SimpleSize = Simple.getSizeInBits();
3068     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3069     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3070       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3071       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3072       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3073       // Compute the high part as N1.
3074       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3075             DAG.getConstant(SimpleSize, DL,
3076                             getShiftAmountTy(Lo.getValueType())));
3077       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3078       // Compute the low part as N0.
3079       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3080       return CombineTo(N, Lo, Hi);
3081     }
3082   }
3083
3084   return SDValue();
3085 }
3086
3087 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3088   // (smulo x, 2) -> (saddo x, x)
3089   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3090     if (C2->getAPIntValue() == 2)
3091       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3092                          N->getOperand(0), N->getOperand(0));
3093
3094   return SDValue();
3095 }
3096
3097 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3098   // (umulo x, 2) -> (uaddo x, x)
3099   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3100     if (C2->getAPIntValue() == 2)
3101       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3102                          N->getOperand(0), N->getOperand(0));
3103
3104   return SDValue();
3105 }
3106
3107 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3108   SDValue N0 = N->getOperand(0);
3109   SDValue N1 = N->getOperand(1);
3110   EVT VT = N0.getValueType();
3111
3112   // fold vector ops
3113   if (VT.isVector())
3114     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3115       return FoldedVOp;
3116
3117   // fold (add c1, c2) -> c1+c2
3118   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3119   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3120   if (N0C && N1C)
3121     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3122
3123   // canonicalize constant to RHS
3124   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3125      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3126     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3127
3128   return SDValue();
3129 }
3130
3131 /// If this is a binary operator with two operands of the same opcode, try to
3132 /// simplify it.
3133 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3134   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3135   EVT VT = N0.getValueType();
3136   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3137
3138   // Bail early if none of these transforms apply.
3139   if (N0.getNumOperands() == 0) return SDValue();
3140
3141   // For each of OP in AND/OR/XOR:
3142   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3143   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3144   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3145   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3146   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3147   //
3148   // do not sink logical op inside of a vector extend, since it may combine
3149   // into a vsetcc.
3150   EVT Op0VT = N0.getOperand(0).getValueType();
3151   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3152        N0.getOpcode() == ISD::SIGN_EXTEND ||
3153        N0.getOpcode() == ISD::BSWAP ||
3154        // Avoid infinite looping with PromoteIntBinOp.
3155        (N0.getOpcode() == ISD::ANY_EXTEND &&
3156         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3157        (N0.getOpcode() == ISD::TRUNCATE &&
3158         (!TLI.isZExtFree(VT, Op0VT) ||
3159          !TLI.isTruncateFree(Op0VT, VT)) &&
3160         TLI.isTypeLegal(Op0VT))) &&
3161       !VT.isVector() &&
3162       Op0VT == N1.getOperand(0).getValueType() &&
3163       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3164     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3165                                  N0.getOperand(0).getValueType(),
3166                                  N0.getOperand(0), N1.getOperand(0));
3167     AddToWorklist(ORNode.getNode());
3168     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3169   }
3170
3171   // For each of OP in SHL/SRL/SRA/AND...
3172   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3173   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3174   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3175   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3176        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3177       N0.getOperand(1) == N1.getOperand(1)) {
3178     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3179                                  N0.getOperand(0).getValueType(),
3180                                  N0.getOperand(0), N1.getOperand(0));
3181     AddToWorklist(ORNode.getNode());
3182     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3183                        ORNode, N0.getOperand(1));
3184   }
3185
3186   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3187   // Only perform this optimization up until type legalization, before
3188   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3189   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3190   // we don't want to undo this promotion.
3191   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3192   // on scalars.
3193   if ((N0.getOpcode() == ISD::BITCAST ||
3194        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3195        Level <= AfterLegalizeTypes) {
3196     SDValue In0 = N0.getOperand(0);
3197     SDValue In1 = N1.getOperand(0);
3198     EVT In0Ty = In0.getValueType();
3199     EVT In1Ty = In1.getValueType();
3200     SDLoc DL(N);
3201     // If both incoming values are integers, and the original types are the
3202     // same.
3203     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3204       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3205       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3206       AddToWorklist(Op.getNode());
3207       return BC;
3208     }
3209   }
3210
3211   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3212   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3213   // If both shuffles use the same mask, and both shuffle within a single
3214   // vector, then it is worthwhile to move the swizzle after the operation.
3215   // The type-legalizer generates this pattern when loading illegal
3216   // vector types from memory. In many cases this allows additional shuffle
3217   // optimizations.
3218   // There are other cases where moving the shuffle after the xor/and/or
3219   // is profitable even if shuffles don't perform a swizzle.
3220   // If both shuffles use the same mask, and both shuffles have the same first
3221   // or second operand, then it might still be profitable to move the shuffle
3222   // after the xor/and/or operation.
3223   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3224     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3225     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3226
3227     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3228            "Inputs to shuffles are not the same type");
3229
3230     // Check that both shuffles use the same mask. The masks are known to be of
3231     // the same length because the result vector type is the same.
3232     // Check also that shuffles have only one use to avoid introducing extra
3233     // instructions.
3234     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3235         SVN0->getMask().equals(SVN1->getMask())) {
3236       SDValue ShOp = N0->getOperand(1);
3237
3238       // Don't try to fold this node if it requires introducing a
3239       // build vector of all zeros that might be illegal at this stage.
3240       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3241         if (!LegalTypes)
3242           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3243         else
3244           ShOp = SDValue();
3245       }
3246
3247       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3248       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3249       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3250       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3251         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3252                                       N0->getOperand(0), N1->getOperand(0));
3253         AddToWorklist(NewNode.getNode());
3254         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3255                                     SVN0->getMask());
3256       }
3257
3258       // Don't try to fold this node if it requires introducing a
3259       // build vector of all zeros that might be illegal at this stage.
3260       ShOp = N0->getOperand(0);
3261       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3262         if (!LegalTypes)
3263           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3264         else
3265           ShOp = SDValue();
3266       }
3267
3268       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3269       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3270       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3271       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3272         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3273                                       N0->getOperand(1), N1->getOperand(1));
3274         AddToWorklist(NewNode.getNode());
3275         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3276                                     SVN0->getMask());
3277       }
3278     }
3279   }
3280
3281   return SDValue();
3282 }
3283
3284 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3285 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3286                                        const SDLoc &DL) {
3287   SDValue LL, LR, RL, RR, N0CC, N1CC;
3288   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3289       !isSetCCEquivalent(N1, RL, RR, N1CC))
3290     return SDValue();
3291
3292   assert(N0.getValueType() == N1.getValueType() &&
3293          "Unexpected operand types for bitwise logic op");
3294   assert(LL.getValueType() == LR.getValueType() &&
3295          RL.getValueType() == RR.getValueType() &&
3296          "Unexpected operand types for setcc");
3297
3298   // If we're here post-legalization or the logic op type is not i1, the logic
3299   // op type must match a setcc result type. Also, all folds require new
3300   // operations on the left and right operands, so those types must match.
3301   EVT VT = N0.getValueType();
3302   EVT OpVT = LL.getValueType();
3303   if (LegalOperations || VT != MVT::i1)
3304     if (VT != getSetCCResultType(OpVT))
3305       return SDValue();
3306   if (OpVT != RL.getValueType())
3307     return SDValue();
3308
3309   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3310   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3311   bool IsInteger = OpVT.isInteger();
3312   if (LR == RR && CC0 == CC1 && IsInteger) {
3313     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3314     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3315
3316     // All bits clear?
3317     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3318     // All sign bits clear?
3319     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3320     // Any bits set?
3321     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3322     // Any sign bits set?
3323     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3324
3325     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3326     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3327     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3328     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3329     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3330       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3331       AddToWorklist(Or.getNode());
3332       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3333     }
3334
3335     // All bits set?
3336     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3337     // All sign bits set?
3338     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3339     // Any bits clear?
3340     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3341     // Any sign bits clear?
3342     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3343
3344     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3345     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3346     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3347     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3348     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3349       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3350       AddToWorklist(And.getNode());
3351       return DAG.getSetCC(DL, VT, And, LR, CC1);
3352     }
3353   }
3354
3355   // TODO: What is the 'or' equivalent of this fold?
3356   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3357   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3358       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3359        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3360     SDValue One = DAG.getConstant(1, DL, OpVT);
3361     SDValue Two = DAG.getConstant(2, DL, OpVT);
3362     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3363     AddToWorklist(Add.getNode());
3364     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3365   }
3366
3367   // Try more general transforms if the predicates match and the only user of
3368   // the compares is the 'and' or 'or'.
3369   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3370       N0.hasOneUse() && N1.hasOneUse()) {
3371     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3372     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3373     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3374       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3375       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3376       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3377       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3378       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3379     }
3380   }
3381
3382   // Canonicalize equivalent operands to LL == RL.
3383   if (LL == RR && LR == RL) {
3384     CC1 = ISD::getSetCCSwappedOperands(CC1);
3385     std::swap(RL, RR);
3386   }
3387
3388   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3389   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3390   if (LL == RL && LR == RR) {
3391     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3392                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3393     if (NewCC != ISD::SETCC_INVALID &&
3394         (!LegalOperations ||
3395          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3396           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3397       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3398   }
3399
3400   return SDValue();
3401 }
3402
3403 /// This contains all DAGCombine rules which reduce two values combined by
3404 /// an And operation to a single value. This makes them reusable in the context
3405 /// of visitSELECT(). Rules involving constants are not included as
3406 /// visitSELECT() already handles those cases.
3407 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3408   EVT VT = N1.getValueType();
3409   SDLoc DL(N);
3410
3411   // fold (and x, undef) -> 0
3412   if (N0.isUndef() || N1.isUndef())
3413     return DAG.getConstant(0, DL, VT);
3414
3415   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3416     return V;
3417
3418   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3419       VT.getSizeInBits() <= 64) {
3420     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3421       APInt ADDC = ADDI->getAPIntValue();
3422       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3423         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3424         // immediate for an add, but it is legal if its top c2 bits are set,
3425         // transform the ADD so the immediate doesn't need to be materialized
3426         // in a register.
3427         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3428           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3429                                              SRLI->getZExtValue());
3430           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3431             ADDC |= Mask;
3432             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3433               SDLoc DL0(N0);
3434               SDValue NewAdd =
3435                 DAG.getNode(ISD::ADD, DL0, VT,
3436                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3437               CombineTo(N0.getNode(), NewAdd);
3438               // Return N so it doesn't get rechecked!
3439               return SDValue(N, 0);
3440             }
3441           }
3442         }
3443       }
3444     }
3445   }
3446
3447   // Reduce bit extract of low half of an integer to the narrower type.
3448   // (and (srl i64:x, K), KMask) ->
3449   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3450   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3451     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3452       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3453         unsigned Size = VT.getSizeInBits();
3454         const APInt &AndMask = CAnd->getAPIntValue();
3455         unsigned ShiftBits = CShift->getZExtValue();
3456
3457         // Bail out, this node will probably disappear anyway.
3458         if (ShiftBits == 0)
3459           return SDValue();
3460
3461         unsigned MaskBits = AndMask.countTrailingOnes();
3462         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3463
3464         if (AndMask.isMask() &&
3465             // Required bits must not span the two halves of the integer and
3466             // must fit in the half size type.
3467             (ShiftBits + MaskBits <= Size / 2) &&
3468             TLI.isNarrowingProfitable(VT, HalfVT) &&
3469             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3470             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3471             TLI.isTruncateFree(VT, HalfVT) &&
3472             TLI.isZExtFree(HalfVT, VT)) {
3473           // The isNarrowingProfitable is to avoid regressions on PPC and
3474           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3475           // on downstream users of this. Those patterns could probably be
3476           // extended to handle extensions mixed in.
3477
3478           SDValue SL(N0);
3479           assert(MaskBits <= Size);
3480
3481           // Extracting the highest bit of the low half.
3482           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3483           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3484                                       N0.getOperand(0));
3485
3486           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3487           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3488           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3489           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3490           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3491         }
3492       }
3493     }
3494   }
3495
3496   return SDValue();
3497 }
3498
3499 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3500                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3501                                    bool &NarrowLoad) {
3502   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3503
3504   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3505     return false;
3506
3507   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3508   LoadedVT = LoadN->getMemoryVT();
3509
3510   if (ExtVT == LoadedVT &&
3511       (!LegalOperations ||
3512        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3513     // ZEXTLOAD will match without needing to change the size of the value being
3514     // loaded.
3515     NarrowLoad = false;
3516     return true;
3517   }
3518
3519   // Do not change the width of a volatile load.
3520   if (LoadN->isVolatile())
3521     return false;
3522
3523   // Do not generate loads of non-round integer types since these can
3524   // be expensive (and would be wrong if the type is not byte sized).
3525   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3526     return false;
3527
3528   if (LegalOperations &&
3529       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3530     return false;
3531
3532   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3533     return false;
3534
3535   NarrowLoad = true;
3536   return true;
3537 }
3538
3539 SDValue DAGCombiner::visitAND(SDNode *N) {
3540   SDValue N0 = N->getOperand(0);
3541   SDValue N1 = N->getOperand(1);
3542   EVT VT = N1.getValueType();
3543
3544   // x & x --> x
3545   if (N0 == N1)
3546     return N0;
3547
3548   // fold vector ops
3549   if (VT.isVector()) {
3550     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3551       return FoldedVOp;
3552
3553     // fold (and x, 0) -> 0, vector edition
3554     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3555       // do not return N0, because undef node may exist in N0
3556       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3557                              SDLoc(N), N0.getValueType());
3558     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3559       // do not return N1, because undef node may exist in N1
3560       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3561                              SDLoc(N), N1.getValueType());
3562
3563     // fold (and x, -1) -> x, vector edition
3564     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3565       return N1;
3566     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3567       return N0;
3568   }
3569
3570   // fold (and c1, c2) -> c1&c2
3571   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3572   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3573   if (N0C && N1C && !N1C->isOpaque())
3574     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3575   // canonicalize constant to RHS
3576   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3577      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3578     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3579   // fold (and x, -1) -> x
3580   if (isAllOnesConstant(N1))
3581     return N0;
3582   // if (and x, c) is known to be zero, return 0
3583   unsigned BitWidth = VT.getScalarSizeInBits();
3584   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3585                                    APInt::getAllOnesValue(BitWidth)))
3586     return DAG.getConstant(0, SDLoc(N), VT);
3587
3588   if (SDValue NewSel = foldBinOpIntoSelect(N))
3589     return NewSel;
3590
3591   // reassociate and
3592   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3593     return RAND;
3594   // fold (and (or x, C), D) -> D if (C & D) == D
3595   if (N1C && N0.getOpcode() == ISD::OR)
3596     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3597       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3598         return N1;
3599   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3600   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3601     SDValue N0Op0 = N0.getOperand(0);
3602     APInt Mask = ~N1C->getAPIntValue();
3603     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3604     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3605       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3606                                  N0.getValueType(), N0Op0);
3607
3608       // Replace uses of the AND with uses of the Zero extend node.
3609       CombineTo(N, Zext);
3610
3611       // We actually want to replace all uses of the any_extend with the
3612       // zero_extend, to avoid duplicating things.  This will later cause this
3613       // AND to be folded.
3614       CombineTo(N0.getNode(), Zext);
3615       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3616     }
3617   }
3618   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3619   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3620   // already be zero by virtue of the width of the base type of the load.
3621   //
3622   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3623   // more cases.
3624   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3625        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3626        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3627        N0.getOperand(0).getResNo() == 0) ||
3628       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3629     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3630                                          N0 : N0.getOperand(0) );
3631
3632     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3633     // This can be a pure constant or a vector splat, in which case we treat the
3634     // vector as a scalar and use the splat value.
3635     APInt Constant = APInt::getNullValue(1);
3636     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3637       Constant = C->getAPIntValue();
3638     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3639       APInt SplatValue, SplatUndef;
3640       unsigned SplatBitSize;
3641       bool HasAnyUndefs;
3642       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3643                                              SplatBitSize, HasAnyUndefs);
3644       if (IsSplat) {
3645         // Undef bits can contribute to a possible optimisation if set, so
3646         // set them.
3647         SplatValue |= SplatUndef;
3648
3649         // The splat value may be something like "0x00FFFFFF", which means 0 for
3650         // the first vector value and FF for the rest, repeating. We need a mask
3651         // that will apply equally to all members of the vector, so AND all the
3652         // lanes of the constant together.
3653         EVT VT = Vector->getValueType(0);
3654         unsigned BitWidth = VT.getScalarSizeInBits();
3655
3656         // If the splat value has been compressed to a bitlength lower
3657         // than the size of the vector lane, we need to re-expand it to
3658         // the lane size.
3659         if (BitWidth > SplatBitSize)
3660           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3661                SplatBitSize < BitWidth;
3662                SplatBitSize = SplatBitSize * 2)
3663             SplatValue |= SplatValue.shl(SplatBitSize);
3664
3665         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3666         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3667         if (SplatBitSize % BitWidth == 0) {
3668           Constant = APInt::getAllOnesValue(BitWidth);
3669           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3670             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3671         }
3672       }
3673     }
3674
3675     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3676     // actually legal and isn't going to get expanded, else this is a false
3677     // optimisation.
3678     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3679                                                     Load->getValueType(0),
3680                                                     Load->getMemoryVT());
3681
3682     // Resize the constant to the same size as the original memory access before
3683     // extension. If it is still the AllOnesValue then this AND is completely
3684     // unneeded.
3685     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3686
3687     bool B;
3688     switch (Load->getExtensionType()) {
3689     default: B = false; break;
3690     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3691     case ISD::ZEXTLOAD:
3692     case ISD::NON_EXTLOAD: B = true; break;
3693     }
3694
3695     if (B && Constant.isAllOnesValue()) {
3696       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3697       // preserve semantics once we get rid of the AND.
3698       SDValue NewLoad(Load, 0);
3699
3700       // Fold the AND away. NewLoad may get replaced immediately.
3701       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3702
3703       if (Load->getExtensionType() == ISD::EXTLOAD) {
3704         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3705                               Load->getValueType(0), SDLoc(Load),
3706                               Load->getChain(), Load->getBasePtr(),
3707                               Load->getOffset(), Load->getMemoryVT(),
3708                               Load->getMemOperand());
3709         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3710         if (Load->getNumValues() == 3) {
3711           // PRE/POST_INC loads have 3 values.
3712           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3713                            NewLoad.getValue(2) };
3714           CombineTo(Load, To, 3, true);
3715         } else {
3716           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3717         }
3718       }
3719
3720       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3721     }
3722   }
3723
3724   // fold (and (load x), 255) -> (zextload x, i8)
3725   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3726   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3727   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3728                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3729                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3730     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3731     LoadSDNode *LN0 = HasAnyExt
3732       ? cast<LoadSDNode>(N0.getOperand(0))
3733       : cast<LoadSDNode>(N0);
3734     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3735         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3736       auto NarrowLoad = false;
3737       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3738       EVT ExtVT, LoadedVT;
3739       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3740                            NarrowLoad)) {
3741         if (!NarrowLoad) {
3742           SDValue NewLoad =
3743             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3744                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3745                            LN0->getMemOperand());
3746           AddToWorklist(N);
3747           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3748           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3749         } else {
3750           EVT PtrType = LN0->getOperand(1).getValueType();
3751
3752           unsigned Alignment = LN0->getAlignment();
3753           SDValue NewPtr = LN0->getBasePtr();
3754
3755           // For big endian targets, we need to add an offset to the pointer
3756           // to load the correct bytes.  For little endian systems, we merely
3757           // need to read fewer bytes from the same pointer.
3758           if (DAG.getDataLayout().isBigEndian()) {
3759             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3760             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3761             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3762             SDLoc DL(LN0);
3763             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3764                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3765             Alignment = MinAlign(Alignment, PtrOff);
3766           }
3767
3768           AddToWorklist(NewPtr.getNode());
3769
3770           SDValue Load = DAG.getExtLoad(
3771               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3772               LN0->getPointerInfo(), ExtVT, Alignment,
3773               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3774           AddToWorklist(N);
3775           CombineTo(LN0, Load, Load.getValue(1));
3776           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3777         }
3778       }
3779     }
3780   }
3781
3782   if (SDValue Combined = visitANDLike(N0, N1, N))
3783     return Combined;
3784
3785   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3786   if (N0.getOpcode() == N1.getOpcode())
3787     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3788       return Tmp;
3789
3790   // Masking the negated extension of a boolean is just the zero-extended
3791   // boolean:
3792   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3793   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3794   //
3795   // Note: the SimplifyDemandedBits fold below can make an information-losing
3796   // transform, and then we have no way to find this better fold.
3797   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3798     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3799     SDValue SubRHS = N0.getOperand(1);
3800     if (SubLHS && SubLHS->isNullValue()) {
3801       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3802           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3803         return SubRHS;
3804       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3805           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3806         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3807     }
3808   }
3809
3810   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3811   // fold (and (sra)) -> (and (srl)) when possible.
3812   if (SimplifyDemandedBits(SDValue(N, 0)))
3813     return SDValue(N, 0);
3814
3815   // fold (zext_inreg (extload x)) -> (zextload x)
3816   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3817     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3818     EVT MemVT = LN0->getMemoryVT();
3819     // If we zero all the possible extended bits, then we can turn this into
3820     // a zextload if we are running before legalize or the operation is legal.
3821     unsigned BitWidth = N1.getScalarValueSizeInBits();
3822     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3823                            BitWidth - MemVT.getScalarSizeInBits())) &&
3824         ((!LegalOperations && !LN0->isVolatile()) ||
3825          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3826       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3827                                        LN0->getChain(), LN0->getBasePtr(),
3828                                        MemVT, LN0->getMemOperand());
3829       AddToWorklist(N);
3830       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3831       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3832     }
3833   }
3834   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3835   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3836       N0.hasOneUse()) {
3837     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3838     EVT MemVT = LN0->getMemoryVT();
3839     // If we zero all the possible extended bits, then we can turn this into
3840     // a zextload if we are running before legalize or the operation is legal.
3841     unsigned BitWidth = N1.getScalarValueSizeInBits();
3842     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3843                            BitWidth - MemVT.getScalarSizeInBits())) &&
3844         ((!LegalOperations && !LN0->isVolatile()) ||
3845          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3846       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3847                                        LN0->getChain(), LN0->getBasePtr(),
3848                                        MemVT, LN0->getMemOperand());
3849       AddToWorklist(N);
3850       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3851       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3852     }
3853   }
3854   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3855   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3856     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3857                                            N0.getOperand(1), false))
3858       return BSwap;
3859   }
3860
3861   return SDValue();
3862 }
3863
3864 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3865 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3866                                         bool DemandHighBits) {
3867   if (!LegalOperations)
3868     return SDValue();
3869
3870   EVT VT = N->getValueType(0);
3871   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3872     return SDValue();
3873   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3874     return SDValue();
3875
3876   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3877   bool LookPassAnd0 = false;
3878   bool LookPassAnd1 = false;
3879   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3880       std::swap(N0, N1);
3881   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3882       std::swap(N0, N1);
3883   if (N0.getOpcode() == ISD::AND) {
3884     if (!N0.getNode()->hasOneUse())
3885       return SDValue();
3886     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3887     if (!N01C || N01C->getZExtValue() != 0xFF00)
3888       return SDValue();
3889     N0 = N0.getOperand(0);
3890     LookPassAnd0 = true;
3891   }
3892
3893   if (N1.getOpcode() == ISD::AND) {
3894     if (!N1.getNode()->hasOneUse())
3895       return SDValue();
3896     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3897     if (!N11C || N11C->getZExtValue() != 0xFF)
3898       return SDValue();
3899     N1 = N1.getOperand(0);
3900     LookPassAnd1 = true;
3901   }
3902
3903   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3904     std::swap(N0, N1);
3905   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3906     return SDValue();
3907   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3908     return SDValue();
3909
3910   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3911   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3912   if (!N01C || !N11C)
3913     return SDValue();
3914   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3915     return SDValue();
3916
3917   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3918   SDValue N00 = N0->getOperand(0);
3919   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3920     if (!N00.getNode()->hasOneUse())
3921       return SDValue();
3922     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3923     if (!N001C || N001C->getZExtValue() != 0xFF)
3924       return SDValue();
3925     N00 = N00.getOperand(0);
3926     LookPassAnd0 = true;
3927   }
3928
3929   SDValue N10 = N1->getOperand(0);
3930   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3931     if (!N10.getNode()->hasOneUse())
3932       return SDValue();
3933     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3934     if (!N101C || N101C->getZExtValue() != 0xFF00)
3935       return SDValue();
3936     N10 = N10.getOperand(0);
3937     LookPassAnd1 = true;
3938   }
3939
3940   if (N00 != N10)
3941     return SDValue();
3942
3943   // Make sure everything beyond the low halfword gets set to zero since the SRL
3944   // 16 will clear the top bits.
3945   unsigned OpSizeInBits = VT.getSizeInBits();
3946   if (DemandHighBits && OpSizeInBits > 16) {
3947     // If the left-shift isn't masked out then the only way this is a bswap is
3948     // if all bits beyond the low 8 are 0. In that case the entire pattern
3949     // reduces to a left shift anyway: leave it for other parts of the combiner.
3950     if (!LookPassAnd0)
3951       return SDValue();
3952
3953     // However, if the right shift isn't masked out then it might be because
3954     // it's not needed. See if we can spot that too.
3955     if (!LookPassAnd1 &&
3956         !DAG.MaskedValueIsZero(
3957             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3958       return SDValue();
3959   }
3960
3961   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3962   if (OpSizeInBits > 16) {
3963     SDLoc DL(N);
3964     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3965                       DAG.getConstant(OpSizeInBits - 16, DL,
3966                                       getShiftAmountTy(VT)));
3967   }
3968   return Res;
3969 }
3970
3971 /// Return true if the specified node is an element that makes up a 32-bit
3972 /// packed halfword byteswap.
3973 /// ((x & 0x000000ff) << 8) |
3974 /// ((x & 0x0000ff00) >> 8) |
3975 /// ((x & 0x00ff0000) << 8) |
3976 /// ((x & 0xff000000) >> 8)
3977 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3978   if (!N.getNode()->hasOneUse())
3979     return false;
3980
3981   unsigned Opc = N.getOpcode();
3982   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3983     return false;
3984
3985   SDValue N0 = N.getOperand(0);
3986   unsigned Opc0 = N0.getOpcode();
3987   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
3988     return false;
3989
3990   ConstantSDNode *N1C = nullptr;
3991   // SHL or SRL: look upstream for AND mask operand
3992   if (Opc == ISD::AND)
3993     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3994   else if (Opc0 == ISD::AND)
3995     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3996   if (!N1C)
3997     return false;
3998
3999   unsigned MaskByteOffset;
4000   switch (N1C->getZExtValue()) {
4001   default:
4002     return false;
4003   case 0xFF:       MaskByteOffset = 0; break;
4004   case 0xFF00:     MaskByteOffset = 1; break;
4005   case 0xFF0000:   MaskByteOffset = 2; break;
4006   case 0xFF000000: MaskByteOffset = 3; break;
4007   }
4008
4009   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4010   if (Opc == ISD::AND) {
4011     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4012       // (x >> 8) & 0xff
4013       // (x >> 8) & 0xff0000
4014       if (Opc0 != ISD::SRL)
4015         return false;
4016       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4017       if (!C || C->getZExtValue() != 8)
4018         return false;
4019     } else {
4020       // (x << 8) & 0xff00
4021       // (x << 8) & 0xff000000
4022       if (Opc0 != ISD::SHL)
4023         return false;
4024       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4025       if (!C || C->getZExtValue() != 8)
4026         return false;
4027     }
4028   } else if (Opc == ISD::SHL) {
4029     // (x & 0xff) << 8
4030     // (x & 0xff0000) << 8
4031     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4032       return false;
4033     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4034     if (!C || C->getZExtValue() != 8)
4035       return false;
4036   } else { // Opc == ISD::SRL
4037     // (x & 0xff00) >> 8
4038     // (x & 0xff000000) >> 8
4039     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4040       return false;
4041     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4042     if (!C || C->getZExtValue() != 8)
4043       return false;
4044   }
4045
4046   if (Parts[MaskByteOffset])
4047     return false;
4048
4049   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4050   return true;
4051 }
4052
4053 /// Match a 32-bit packed halfword bswap. That is
4054 /// ((x & 0x000000ff) << 8) |
4055 /// ((x & 0x0000ff00) >> 8) |
4056 /// ((x & 0x00ff0000) << 8) |
4057 /// ((x & 0xff000000) >> 8)
4058 /// => (rotl (bswap x), 16)
4059 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4060   if (!LegalOperations)
4061     return SDValue();
4062
4063   EVT VT = N->getValueType(0);
4064   if (VT != MVT::i32)
4065     return SDValue();
4066   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4067     return SDValue();
4068
4069   // Look for either
4070   // (or (or (and), (and)), (or (and), (and)))
4071   // (or (or (or (and), (and)), (and)), (and))
4072   if (N0.getOpcode() != ISD::OR)
4073     return SDValue();
4074   SDValue N00 = N0.getOperand(0);
4075   SDValue N01 = N0.getOperand(1);
4076   SDNode *Parts[4] = {};
4077
4078   if (N1.getOpcode() == ISD::OR &&
4079       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4080     // (or (or (and), (and)), (or (and), (and)))
4081     if (!isBSwapHWordElement(N00, Parts))
4082       return SDValue();
4083
4084     if (!isBSwapHWordElement(N01, Parts))
4085       return SDValue();
4086     SDValue N10 = N1.getOperand(0);
4087     if (!isBSwapHWordElement(N10, Parts))
4088       return SDValue();
4089     SDValue N11 = N1.getOperand(1);
4090     if (!isBSwapHWordElement(N11, Parts))
4091       return SDValue();
4092   } else {
4093     // (or (or (or (and), (and)), (and)), (and))
4094     if (!isBSwapHWordElement(N1, Parts))
4095       return SDValue();
4096     if (!isBSwapHWordElement(N01, Parts))
4097       return SDValue();
4098     if (N00.getOpcode() != ISD::OR)
4099       return SDValue();
4100     SDValue N000 = N00.getOperand(0);
4101     if (!isBSwapHWordElement(N000, Parts))
4102       return SDValue();
4103     SDValue N001 = N00.getOperand(1);
4104     if (!isBSwapHWordElement(N001, Parts))
4105       return SDValue();
4106   }
4107
4108   // Make sure the parts are all coming from the same node.
4109   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4110     return SDValue();
4111
4112   SDLoc DL(N);
4113   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4114                               SDValue(Parts[0], 0));
4115
4116   // Result of the bswap should be rotated by 16. If it's not legal, then
4117   // do  (x << 16) | (x >> 16).
4118   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4119   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4120     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4121   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4122     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4123   return DAG.getNode(ISD::OR, DL, VT,
4124                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4125                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4126 }
4127
4128 /// This contains all DAGCombine rules which reduce two values combined by
4129 /// an Or operation to a single value \see visitANDLike().
4130 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4131   EVT VT = N1.getValueType();
4132   SDLoc DL(N);
4133
4134   // fold (or x, undef) -> -1
4135   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4136     return DAG.getAllOnesConstant(DL, VT);
4137
4138   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4139     return V;
4140
4141   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4142   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4143       // Don't increase # computations.
4144       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4145     // We can only do this xform if we know that bits from X that are set in C2
4146     // but not in C1 are already zero.  Likewise for Y.
4147     if (const ConstantSDNode *N0O1C =
4148         getAsNonOpaqueConstant(N0.getOperand(1))) {
4149       if (const ConstantSDNode *N1O1C =
4150           getAsNonOpaqueConstant(N1.getOperand(1))) {
4151         // We can only do this xform if we know that bits from X that are set in
4152         // C2 but not in C1 are already zero.  Likewise for Y.
4153         const APInt &LHSMask = N0O1C->getAPIntValue();
4154         const APInt &RHSMask = N1O1C->getAPIntValue();
4155
4156         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4157             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4158           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4159                                   N0.getOperand(0), N1.getOperand(0));
4160           return DAG.getNode(ISD::AND, DL, VT, X,
4161                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4162         }
4163       }
4164     }
4165   }
4166
4167   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4168   if (N0.getOpcode() == ISD::AND &&
4169       N1.getOpcode() == ISD::AND &&
4170       N0.getOperand(0) == N1.getOperand(0) &&
4171       // Don't increase # computations.
4172       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4173     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4174                             N0.getOperand(1), N1.getOperand(1));
4175     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 SDValue DAGCombiner::visitOR(SDNode *N) {
4182   SDValue N0 = N->getOperand(0);
4183   SDValue N1 = N->getOperand(1);
4184   EVT VT = N1.getValueType();
4185
4186   // x | x --> x
4187   if (N0 == N1)
4188     return N0;
4189
4190   // fold vector ops
4191   if (VT.isVector()) {
4192     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4193       return FoldedVOp;
4194
4195     // fold (or x, 0) -> x, vector edition
4196     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4197       return N1;
4198     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4199       return N0;
4200
4201     // fold (or x, -1) -> -1, vector edition
4202     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4203       // do not return N0, because undef node may exist in N0
4204       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4205     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4206       // do not return N1, because undef node may exist in N1
4207       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4208
4209     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4210     // Do this only if the resulting shuffle is legal.
4211     if (isa<ShuffleVectorSDNode>(N0) &&
4212         isa<ShuffleVectorSDNode>(N1) &&
4213         // Avoid folding a node with illegal type.
4214         TLI.isTypeLegal(VT)) {
4215       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4216       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4217       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4218       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4219       // Ensure both shuffles have a zero input.
4220       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4221         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4222         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4223         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4224         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4225         bool CanFold = true;
4226         int NumElts = VT.getVectorNumElements();
4227         SmallVector<int, 4> Mask(NumElts);
4228
4229         for (int i = 0; i != NumElts; ++i) {
4230           int M0 = SV0->getMaskElt(i);
4231           int M1 = SV1->getMaskElt(i);
4232
4233           // Determine if either index is pointing to a zero vector.
4234           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4235           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4236
4237           // If one element is zero and the otherside is undef, keep undef.
4238           // This also handles the case that both are undef.
4239           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4240             Mask[i] = -1;
4241             continue;
4242           }
4243
4244           // Make sure only one of the elements is zero.
4245           if (M0Zero == M1Zero) {
4246             CanFold = false;
4247             break;
4248           }
4249
4250           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4251
4252           // We have a zero and non-zero element. If the non-zero came from
4253           // SV0 make the index a LHS index. If it came from SV1, make it
4254           // a RHS index. We need to mod by NumElts because we don't care
4255           // which operand it came from in the original shuffles.
4256           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4257         }
4258
4259         if (CanFold) {
4260           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4261           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4262
4263           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4264           if (!LegalMask) {
4265             std::swap(NewLHS, NewRHS);
4266             ShuffleVectorSDNode::commuteMask(Mask);
4267             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4268           }
4269
4270           if (LegalMask)
4271             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4272         }
4273       }
4274     }
4275   }
4276
4277   // fold (or c1, c2) -> c1|c2
4278   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4280   if (N0C && N1C && !N1C->isOpaque())
4281     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4282   // canonicalize constant to RHS
4283   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4284      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4285     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4286   // fold (or x, 0) -> x
4287   if (isNullConstant(N1))
4288     return N0;
4289   // fold (or x, -1) -> -1
4290   if (isAllOnesConstant(N1))
4291     return N1;
4292
4293   if (SDValue NewSel = foldBinOpIntoSelect(N))
4294     return NewSel;
4295
4296   // fold (or x, c) -> c iff (x & ~c) == 0
4297   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4298     return N1;
4299
4300   if (SDValue Combined = visitORLike(N0, N1, N))
4301     return Combined;
4302
4303   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4304   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4305     return BSwap;
4306   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4307     return BSwap;
4308
4309   // reassociate or
4310   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4311     return ROR;
4312
4313   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4314   // iff (c1 & c2) != 0.
4315   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4316     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4317       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4318         if (SDValue COR =
4319                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4320           return DAG.getNode(
4321               ISD::AND, SDLoc(N), VT,
4322               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4323         return SDValue();
4324       }
4325     }
4326   }
4327
4328   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4329   if (N0.getOpcode() == N1.getOpcode())
4330     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4331       return Tmp;
4332
4333   // See if this is some rotate idiom.
4334   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4335     return SDValue(Rot, 0);
4336
4337   if (SDValue Load = MatchLoadCombine(N))
4338     return Load;
4339
4340   // Simplify the operands using demanded-bits information.
4341   if (SimplifyDemandedBits(SDValue(N, 0)))
4342     return SDValue(N, 0);
4343
4344   return SDValue();
4345 }
4346
4347 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4348 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4349   if (Op.getOpcode() == ISD::AND) {
4350     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4351       Mask = Op.getOperand(1);
4352       Op = Op.getOperand(0);
4353     } else {
4354       return false;
4355     }
4356   }
4357
4358   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4359     Shift = Op;
4360     return true;
4361   }
4362
4363   return false;
4364 }
4365
4366 // Return true if we can prove that, whenever Neg and Pos are both in the
4367 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4368 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4369 //
4370 //     (or (shift1 X, Neg), (shift2 X, Pos))
4371 //
4372 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4373 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4374 // to consider shift amounts with defined behavior.
4375 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4376   // If EltSize is a power of 2 then:
4377   //
4378   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4379   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4380   //
4381   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4382   // for the stronger condition:
4383   //
4384   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4385   //
4386   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4387   // we can just replace Neg with Neg' for the rest of the function.
4388   //
4389   // In other cases we check for the even stronger condition:
4390   //
4391   //     Neg == EltSize - Pos                                    [B]
4392   //
4393   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4394   // behavior if Pos == 0 (and consequently Neg == EltSize).
4395   //
4396   // We could actually use [A] whenever EltSize is a power of 2, but the
4397   // only extra cases that it would match are those uninteresting ones
4398   // where Neg and Pos are never in range at the same time.  E.g. for
4399   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4400   // as well as (sub 32, Pos), but:
4401   //
4402   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4403   //
4404   // always invokes undefined behavior for 32-bit X.
4405   //
4406   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4407   unsigned MaskLoBits = 0;
4408   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4409     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4410       if (NegC->getAPIntValue() == EltSize - 1) {
4411         Neg = Neg.getOperand(0);
4412         MaskLoBits = Log2_64(EltSize);
4413       }
4414     }
4415   }
4416
4417   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4418   if (Neg.getOpcode() != ISD::SUB)
4419     return false;
4420   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4421   if (!NegC)
4422     return false;
4423   SDValue NegOp1 = Neg.getOperand(1);
4424
4425   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4426   // Pos'.  The truncation is redundant for the purpose of the equality.
4427   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4428     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4429       if (PosC->getAPIntValue() == EltSize - 1)
4430         Pos = Pos.getOperand(0);
4431
4432   // The condition we need is now:
4433   //
4434   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4435   //
4436   // If NegOp1 == Pos then we need:
4437   //
4438   //              EltSize & Mask == NegC & Mask
4439   //
4440   // (because "x & Mask" is a truncation and distributes through subtraction).
4441   APInt Width;
4442   if (Pos == NegOp1)
4443     Width = NegC->getAPIntValue();
4444
4445   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4446   // Then the condition we want to prove becomes:
4447   //
4448   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4449   //
4450   // which, again because "x & Mask" is a truncation, becomes:
4451   //
4452   //                NegC & Mask == (EltSize - PosC) & Mask
4453   //             EltSize & Mask == (NegC + PosC) & Mask
4454   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4455     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4456       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4457     else
4458       return false;
4459   } else
4460     return false;
4461
4462   // Now we just need to check that EltSize & Mask == Width & Mask.
4463   if (MaskLoBits)
4464     // EltSize & Mask is 0 since Mask is EltSize - 1.
4465     return Width.getLoBits(MaskLoBits) == 0;
4466   return Width == EltSize;
4467 }
4468
4469 // A subroutine of MatchRotate used once we have found an OR of two opposite
4470 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4471 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4472 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4473 // Neg with outer conversions stripped away.
4474 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4475                                        SDValue Neg, SDValue InnerPos,
4476                                        SDValue InnerNeg, unsigned PosOpcode,
4477                                        unsigned NegOpcode, const SDLoc &DL) {
4478   // fold (or (shl x, (*ext y)),
4479   //          (srl x, (*ext (sub 32, y)))) ->
4480   //   (rotl x, y) or (rotr x, (sub 32, y))
4481   //
4482   // fold (or (shl x, (*ext (sub 32, y))),
4483   //          (srl x, (*ext y))) ->
4484   //   (rotr x, y) or (rotl x, (sub 32, y))
4485   EVT VT = Shifted.getValueType();
4486   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4487     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4488     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4489                        HasPos ? Pos : Neg).getNode();
4490   }
4491
4492   return nullptr;
4493 }
4494
4495 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4496 // idioms for rotate, and if the target supports rotation instructions, generate
4497 // a rot[lr].
4498 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4499   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4500   EVT VT = LHS.getValueType();
4501   if (!TLI.isTypeLegal(VT)) return nullptr;
4502
4503   // The target must have at least one rotate flavor.
4504   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4505   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4506   if (!HasROTL && !HasROTR) return nullptr;
4507
4508   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4509   SDValue LHSShift;   // The shift.
4510   SDValue LHSMask;    // AND value if any.
4511   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4512     return nullptr; // Not part of a rotate.
4513
4514   SDValue RHSShift;   // The shift.
4515   SDValue RHSMask;    // AND value if any.
4516   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4517     return nullptr; // Not part of a rotate.
4518
4519   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4520     return nullptr;   // Not shifting the same value.
4521
4522   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4523     return nullptr;   // Shifts must disagree.
4524
4525   // Canonicalize shl to left side in a shl/srl pair.
4526   if (RHSShift.getOpcode() == ISD::SHL) {
4527     std::swap(LHS, RHS);
4528     std::swap(LHSShift, RHSShift);
4529     std::swap(LHSMask, RHSMask);
4530   }
4531
4532   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4533   SDValue LHSShiftArg = LHSShift.getOperand(0);
4534   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4535   SDValue RHSShiftArg = RHSShift.getOperand(0);
4536   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4537
4538   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4539   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4540   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4541     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4542     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4543     if ((LShVal + RShVal) != EltSizeInBits)
4544       return nullptr;
4545
4546     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4547                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4548
4549     // If there is an AND of either shifted operand, apply it to the result.
4550     if (LHSMask.getNode() || RHSMask.getNode()) {
4551       SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4552
4553       if (LHSMask.getNode()) {
4554         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4555         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4556                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4557                                        DAG.getConstant(RHSBits, DL, VT)));
4558       }
4559       if (RHSMask.getNode()) {
4560         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4561         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4562                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4563                                        DAG.getConstant(LHSBits, DL, VT)));
4564       }
4565
4566       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4567     }
4568
4569     return Rot.getNode();
4570   }
4571
4572   // If there is a mask here, and we have a variable shift, we can't be sure
4573   // that we're masking out the right stuff.
4574   if (LHSMask.getNode() || RHSMask.getNode())
4575     return nullptr;
4576
4577   // If the shift amount is sign/zext/any-extended just peel it off.
4578   SDValue LExtOp0 = LHSShiftAmt;
4579   SDValue RExtOp0 = RHSShiftAmt;
4580   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4581        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4582        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4583        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4584       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4585        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4586        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4587        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4588     LExtOp0 = LHSShiftAmt.getOperand(0);
4589     RExtOp0 = RHSShiftAmt.getOperand(0);
4590   }
4591
4592   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4593                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4594   if (TryL)
4595     return TryL;
4596
4597   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4598                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4599   if (TryR)
4600     return TryR;
4601
4602   return nullptr;
4603 }
4604
4605 namespace {
4606 /// Helper struct to parse and store a memory address as base + index + offset.
4607 /// We ignore sign extensions when it is safe to do so.
4608 /// The following two expressions are not equivalent. To differentiate we need
4609 /// to store whether there was a sign extension involved in the index
4610 /// computation.
4611 ///  (load (i64 add (i64 copyfromreg %c)
4612 ///                 (i64 signextend (add (i8 load %index)
4613 ///                                      (i8 1))))
4614 /// vs
4615 ///
4616 /// (load (i64 add (i64 copyfromreg %c)
4617 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
4618 ///                                         (i32 1)))))
4619 struct BaseIndexOffset {
4620   SDValue Base;
4621   SDValue Index;
4622   int64_t Offset;
4623   bool IsIndexSignExt;
4624
4625   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4626
4627   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4628                   bool IsIndexSignExt) :
4629     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4630
4631   bool equalBaseIndex(const BaseIndexOffset &Other) {
4632     return Other.Base == Base && Other.Index == Index &&
4633       Other.IsIndexSignExt == IsIndexSignExt;
4634   }
4635
4636   /// Parses tree in Ptr for base, index, offset addresses.
4637   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4638                                int64_t PartialOffset = 0) {
4639     bool IsIndexSignExt = false;
4640
4641     // Split up a folded GlobalAddress+Offset into its component parts.
4642     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4643       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4644         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4645                                                     SDLoc(GA),
4646                                                     GA->getValueType(0),
4647                                                     /*Offset=*/PartialOffset,
4648                                                     /*isTargetGA=*/false,
4649                                                     GA->getTargetFlags()),
4650                                SDValue(),
4651                                GA->getOffset(),
4652                                IsIndexSignExt);
4653       }
4654
4655     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4656     // instruction, then it could be just the BASE or everything else we don't
4657     // know how to handle. Just use Ptr as BASE and give up.
4658     if (Ptr->getOpcode() != ISD::ADD)
4659       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4660
4661     // We know that we have at least an ADD instruction. Try to pattern match
4662     // the simple case of BASE + OFFSET.
4663     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4664       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4665       return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4666     }
4667
4668     // Inside a loop the current BASE pointer is calculated using an ADD and a
4669     // MUL instruction. In this case Ptr is the actual BASE pointer.
4670     // (i64 add (i64 %array_ptr)
4671     //          (i64 mul (i64 %induction_var)
4672     //                   (i64 %element_size)))
4673     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4674       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4675
4676     // Look at Base + Index + Offset cases.
4677     SDValue Base = Ptr->getOperand(0);
4678     SDValue IndexOffset = Ptr->getOperand(1);
4679
4680     // Skip signextends.
4681     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4682       IndexOffset = IndexOffset->getOperand(0);
4683       IsIndexSignExt = true;
4684     }
4685
4686     // Either the case of Base + Index (no offset) or something else.
4687     if (IndexOffset->getOpcode() != ISD::ADD)
4688       return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4689
4690     // Now we have the case of Base + Index + offset.
4691     SDValue Index = IndexOffset->getOperand(0);
4692     SDValue Offset = IndexOffset->getOperand(1);
4693
4694     if (!isa<ConstantSDNode>(Offset))
4695       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4696
4697     // Ignore signextends.
4698     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4699       Index = Index->getOperand(0);
4700       IsIndexSignExt = true;
4701     } else IsIndexSignExt = false;
4702
4703     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4704     return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4705   }
4706 };
4707 } // namespace
4708
4709 namespace {
4710 /// Represents known origin of an individual byte in load combine pattern. The
4711 /// value of the byte is either constant zero or comes from memory.
4712 struct ByteProvider {
4713   // For constant zero providers Load is set to nullptr. For memory providers
4714   // Load represents the node which loads the byte from memory.
4715   // ByteOffset is the offset of the byte in the value produced by the load.
4716   LoadSDNode *Load;
4717   unsigned ByteOffset;
4718
4719   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4720
4721   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4722     return ByteProvider(Load, ByteOffset);
4723   }
4724   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4725
4726   bool isConstantZero() const { return !Load; }
4727   bool isMemory() const { return Load; }
4728
4729   bool operator==(const ByteProvider &Other) const {
4730     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4731   }
4732
4733 private:
4734   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4735       : Load(Load), ByteOffset(ByteOffset) {}
4736 };
4737
4738 /// Recursively traverses the expression calculating the origin of the requested
4739 /// byte of the given value. Returns None if the provider can't be calculated.
4740 ///
4741 /// For all the values except the root of the expression verifies that the value
4742 /// has exactly one use and if it's not true return None. This way if the origin
4743 /// of the byte is returned it's guaranteed that the values which contribute to
4744 /// the byte are not used outside of this expression.
4745 ///
4746 /// Because the parts of the expression are not allowed to have more than one
4747 /// use this function iterates over trees, not DAGs. So it never visits the same
4748 /// node more than once.
4749 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4750                                                    unsigned Depth,
4751                                                    bool Root = false) {
4752   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4753   if (Depth == 10)
4754     return None;
4755
4756   if (!Root && !Op.hasOneUse())
4757     return None;
4758
4759   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4760   unsigned BitWidth = Op.getValueSizeInBits();
4761   if (BitWidth % 8 != 0)
4762     return None;
4763   unsigned ByteWidth = BitWidth / 8;
4764   assert(Index < ByteWidth && "invalid index requested");
4765   (void) ByteWidth;
4766
4767   switch (Op.getOpcode()) {
4768   case ISD::OR: {
4769     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4770     if (!LHS)
4771       return None;
4772     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4773     if (!RHS)
4774       return None;
4775
4776     if (LHS->isConstantZero())
4777       return RHS;
4778     if (RHS->isConstantZero())
4779       return LHS;
4780     return None;
4781   }
4782   case ISD::SHL: {
4783     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4784     if (!ShiftOp)
4785       return None;
4786
4787     uint64_t BitShift = ShiftOp->getZExtValue();
4788     if (BitShift % 8 != 0)
4789       return None;
4790     uint64_t ByteShift = BitShift / 8;
4791
4792     return Index < ByteShift
4793                ? ByteProvider::getConstantZero()
4794                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4795                                        Depth + 1);
4796   }
4797   case ISD::ANY_EXTEND:
4798   case ISD::SIGN_EXTEND:
4799   case ISD::ZERO_EXTEND: {
4800     SDValue NarrowOp = Op->getOperand(0);
4801     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4802     if (NarrowBitWidth % 8 != 0)
4803       return None;
4804     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4805
4806     if (Index >= NarrowByteWidth)
4807       return Op.getOpcode() == ISD::ZERO_EXTEND
4808                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4809                  : None;
4810     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4811   }
4812   case ISD::BSWAP:
4813     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4814                                  Depth + 1);
4815   case ISD::LOAD: {
4816     auto L = cast<LoadSDNode>(Op.getNode());
4817     if (L->isVolatile() || L->isIndexed())
4818       return None;
4819
4820     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4821     if (NarrowBitWidth % 8 != 0)
4822       return None;
4823     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4824
4825     if (Index >= NarrowByteWidth)
4826       return L->getExtensionType() == ISD::ZEXTLOAD
4827                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4828                  : None;
4829     return ByteProvider::getMemory(L, Index);
4830   }
4831   }
4832
4833   return None;
4834 }
4835 } // namespace
4836
4837 /// Match a pattern where a wide type scalar value is loaded by several narrow
4838 /// loads and combined by shifts and ors. Fold it into a single load or a load
4839 /// and a BSWAP if the targets supports it.
4840 ///
4841 /// Assuming little endian target:
4842 ///  i8 *a = ...
4843 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4844 /// =>
4845 ///  i32 val = *((i32)a)
4846 ///
4847 ///  i8 *a = ...
4848 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4849 /// =>
4850 ///  i32 val = BSWAP(*((i32)a))
4851 ///
4852 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4853 /// interact well with the worklist mechanism. When a part of the pattern is
4854 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4855 /// but the root node of the pattern which triggers the load combine is not
4856 /// necessarily a direct user of the changed node. For example, once the address
4857 /// of t28 load is reassociated load combine won't be triggered:
4858 ///             t25: i32 = add t4, Constant:i32<2>
4859 ///           t26: i64 = sign_extend t25
4860 ///        t27: i64 = add t2, t26
4861 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4862 ///     t29: i32 = zero_extend t28
4863 ///   t32: i32 = shl t29, Constant:i8<8>
4864 /// t33: i32 = or t23, t32
4865 /// As a possible fix visitLoad can check if the load can be a part of a load
4866 /// combine pattern and add corresponding OR roots to the worklist.
4867 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4868   assert(N->getOpcode() == ISD::OR &&
4869          "Can only match load combining against OR nodes");
4870
4871   // Handles simple types only
4872   EVT VT = N->getValueType(0);
4873   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4874     return SDValue();
4875   unsigned ByteWidth = VT.getSizeInBits() / 8;
4876
4877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4878   // Before legalize we can introduce too wide illegal loads which will be later
4879   // split into legal sized loads. This enables us to combine i64 load by i8
4880   // patterns to a couple of i32 loads on 32 bit targets.
4881   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4882     return SDValue();
4883
4884   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4885     unsigned BW, unsigned i) { return i; };
4886   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4887     unsigned BW, unsigned i) { return BW - i - 1; };
4888
4889   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4890   auto MemoryByteOffset = [&] (ByteProvider P) {
4891     assert(P.isMemory() && "Must be a memory byte provider");
4892     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4893     assert(LoadBitWidth % 8 == 0 &&
4894            "can only analyze providers for individual bytes not bit");
4895     unsigned LoadByteWidth = LoadBitWidth / 8;
4896     return IsBigEndianTarget
4897             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4898             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4899   };
4900
4901   Optional<BaseIndexOffset> Base;
4902   SDValue Chain;
4903
4904   SmallSet<LoadSDNode *, 8> Loads;
4905   Optional<ByteProvider> FirstByteProvider;
4906   int64_t FirstOffset = INT64_MAX;
4907
4908   // Check if all the bytes of the OR we are looking at are loaded from the same
4909   // base address. Collect bytes offsets from Base address in ByteOffsets.
4910   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4911   for (unsigned i = 0; i < ByteWidth; i++) {
4912     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4913     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4914       return SDValue();
4915
4916     LoadSDNode *L = P->Load;
4917     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4918            "Must be enforced by calculateByteProvider");
4919     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4920
4921     // All loads must share the same chain
4922     SDValue LChain = L->getChain();
4923     if (!Chain)
4924       Chain = LChain;
4925     else if (Chain != LChain)
4926       return SDValue();
4927
4928     // Loads must share the same base address
4929     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4930     if (!Base)
4931       Base = Ptr;
4932     else if (!Base->equalBaseIndex(Ptr))
4933       return SDValue();
4934
4935     // Calculate the offset of the current byte from the base address
4936     int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4937     ByteOffsets[i] = ByteOffsetFromBase;
4938
4939     // Remember the first byte load
4940     if (ByteOffsetFromBase < FirstOffset) {
4941       FirstByteProvider = P;
4942       FirstOffset = ByteOffsetFromBase;
4943     }
4944
4945     Loads.insert(L);
4946   }
4947   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4948          "memory, so there must be at least one load which produces the value");
4949   assert(Base && "Base address of the accessed memory location must be set");
4950   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4951
4952   // Check if the bytes of the OR we are looking at match with either big or
4953   // little endian value load
4954   bool BigEndian = true, LittleEndian = true;
4955   for (unsigned i = 0; i < ByteWidth; i++) {
4956     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4957     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4958     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4959     if (!BigEndian && !LittleEndian)
4960       return SDValue();
4961   }
4962   assert((BigEndian != LittleEndian) && "should be either or");
4963   assert(FirstByteProvider && "must be set");
4964
4965   // Ensure that the first byte is loaded from zero offset of the first load.
4966   // So the combined value can be loaded from the first load address.
4967   if (MemoryByteOffset(*FirstByteProvider) != 0)
4968     return SDValue();
4969   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4970
4971   // The node we are looking at matches with the pattern, check if we can
4972   // replace it with a single load and bswap if needed.
4973
4974   // If the load needs byte swap check if the target supports it
4975   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4976
4977   // Before legalize we can introduce illegal bswaps which will be later
4978   // converted to an explicit bswap sequence. This way we end up with a single
4979   // load and byte shuffling instead of several loads and byte shuffling.
4980   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4981     return SDValue();
4982
4983   // Check that a load of the wide type is both allowed and fast on the target
4984   bool Fast = false;
4985   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4986                                         VT, FirstLoad->getAddressSpace(),
4987                                         FirstLoad->getAlignment(), &Fast);
4988   if (!Allowed || !Fast)
4989     return SDValue();
4990
4991   SDValue NewLoad =
4992       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4993                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4994
4995   // Transfer chain users from old loads to the new load.
4996   for (LoadSDNode *L : Loads)
4997     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4998
4999   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5000 }
5001
5002 SDValue DAGCombiner::visitXOR(SDNode *N) {
5003   SDValue N0 = N->getOperand(0);
5004   SDValue N1 = N->getOperand(1);
5005   EVT VT = N0.getValueType();
5006
5007   // fold vector ops
5008   if (VT.isVector()) {
5009     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5010       return FoldedVOp;
5011
5012     // fold (xor x, 0) -> x, vector edition
5013     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5014       return N1;
5015     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5016       return N0;
5017   }
5018
5019   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5020   if (N0.isUndef() && N1.isUndef())
5021     return DAG.getConstant(0, SDLoc(N), VT);
5022   // fold (xor x, undef) -> undef
5023   if (N0.isUndef())
5024     return N0;
5025   if (N1.isUndef())
5026     return N1;
5027   // fold (xor c1, c2) -> c1^c2
5028   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5029   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5030   if (N0C && N1C)
5031     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5032   // canonicalize constant to RHS
5033   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5034      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5035     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5036   // fold (xor x, 0) -> x
5037   if (isNullConstant(N1))
5038     return N0;
5039
5040   if (SDValue NewSel = foldBinOpIntoSelect(N))
5041     return NewSel;
5042
5043   // reassociate xor
5044   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5045     return RXOR;
5046
5047   // fold !(x cc y) -> (x !cc y)
5048   SDValue LHS, RHS, CC;
5049   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5050     bool isInt = LHS.getValueType().isInteger();
5051     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5052                                                isInt);
5053
5054     if (!LegalOperations ||
5055         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5056       switch (N0.getOpcode()) {
5057       default:
5058         llvm_unreachable("Unhandled SetCC Equivalent!");
5059       case ISD::SETCC:
5060         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5061       case ISD::SELECT_CC:
5062         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5063                                N0.getOperand(3), NotCC);
5064       }
5065     }
5066   }
5067
5068   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5069   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5070       N0.getNode()->hasOneUse() &&
5071       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5072     SDValue V = N0.getOperand(0);
5073     SDLoc DL(N0);
5074     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5075                     DAG.getConstant(1, DL, V.getValueType()));
5076     AddToWorklist(V.getNode());
5077     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5078   }
5079
5080   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5081   if (isOneConstant(N1) && VT == MVT::i1 &&
5082       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5083     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5084     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5085       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5086       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5087       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5088       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5089       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5090     }
5091   }
5092   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5093   if (isAllOnesConstant(N1) &&
5094       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5095     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5096     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5097       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5098       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5099       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5100       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5101       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5102     }
5103   }
5104   // fold (xor (and x, y), y) -> (and (not x), y)
5105   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5106       N0->getOperand(1) == N1) {
5107     SDValue X = N0->getOperand(0);
5108     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5109     AddToWorklist(NotX.getNode());
5110     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5111   }
5112   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5113   if (N1C && N0.getOpcode() == ISD::XOR) {
5114     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5115       SDLoc DL(N);
5116       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5117                          DAG.getConstant(N1C->getAPIntValue() ^
5118                                          N00C->getAPIntValue(), DL, VT));
5119     }
5120     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5121       SDLoc DL(N);
5122       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5123                          DAG.getConstant(N1C->getAPIntValue() ^
5124                                          N01C->getAPIntValue(), DL, VT));
5125     }
5126   }
5127
5128   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5129   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5130   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5131       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5132       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5133     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5134       if (C->getAPIntValue() == (OpSizeInBits - 1))
5135         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5136   }
5137
5138   // fold (xor x, x) -> 0
5139   if (N0 == N1)
5140     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5141
5142   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5143   // Here is a concrete example of this equivalence:
5144   // i16   x ==  14
5145   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5146   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5147   //
5148   // =>
5149   //
5150   // i16     ~1      == 0b1111111111111110
5151   // i16 rol(~1, 14) == 0b1011111111111111
5152   //
5153   // Some additional tips to help conceptualize this transform:
5154   // - Try to see the operation as placing a single zero in a value of all ones.
5155   // - There exists no value for x which would allow the result to contain zero.
5156   // - Values of x larger than the bitwidth are undefined and do not require a
5157   //   consistent result.
5158   // - Pushing the zero left requires shifting one bits in from the right.
5159   // A rotate left of ~1 is a nice way of achieving the desired result.
5160   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5161       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5162     SDLoc DL(N);
5163     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5164                        N0.getOperand(1));
5165   }
5166
5167   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5168   if (N0.getOpcode() == N1.getOpcode())
5169     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5170       return Tmp;
5171
5172   // Simplify the expression using non-local knowledge.
5173   if (SimplifyDemandedBits(SDValue(N, 0)))
5174     return SDValue(N, 0);
5175
5176   return SDValue();
5177 }
5178
5179 /// Handle transforms common to the three shifts, when the shift amount is a
5180 /// constant.
5181 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5182   SDNode *LHS = N->getOperand(0).getNode();
5183   if (!LHS->hasOneUse()) return SDValue();
5184
5185   // We want to pull some binops through shifts, so that we have (and (shift))
5186   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5187   // thing happens with address calculations, so it's important to canonicalize
5188   // it.
5189   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5190
5191   switch (LHS->getOpcode()) {
5192   default: return SDValue();
5193   case ISD::OR:
5194   case ISD::XOR:
5195     HighBitSet = false; // We can only transform sra if the high bit is clear.
5196     break;
5197   case ISD::AND:
5198     HighBitSet = true;  // We can only transform sra if the high bit is set.
5199     break;
5200   case ISD::ADD:
5201     if (N->getOpcode() != ISD::SHL)
5202       return SDValue(); // only shl(add) not sr[al](add).
5203     HighBitSet = false; // We can only transform sra if the high bit is clear.
5204     break;
5205   }
5206
5207   // We require the RHS of the binop to be a constant and not opaque as well.
5208   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5209   if (!BinOpCst) return SDValue();
5210
5211   // FIXME: disable this unless the input to the binop is a shift by a constant
5212   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5213   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5214   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5215                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5216                  BinOpLHSVal->getOpcode() == ISD::SRL;
5217   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5218                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5219
5220   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5221       !isCopyOrSelect)
5222     return SDValue();
5223
5224   if (isCopyOrSelect && N->hasOneUse())
5225     return SDValue();
5226
5227   EVT VT = N->getValueType(0);
5228
5229   // If this is a signed shift right, and the high bit is modified by the
5230   // logical operation, do not perform the transformation. The highBitSet
5231   // boolean indicates the value of the high bit of the constant which would
5232   // cause it to be modified for this operation.
5233   if (N->getOpcode() == ISD::SRA) {
5234     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5235     if (BinOpRHSSignSet != HighBitSet)
5236       return SDValue();
5237   }
5238
5239   if (!TLI.isDesirableToCommuteWithShift(LHS))
5240     return SDValue();
5241
5242   // Fold the constants, shifting the binop RHS by the shift amount.
5243   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5244                                N->getValueType(0),
5245                                LHS->getOperand(1), N->getOperand(1));
5246   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5247
5248   // Create the new shift.
5249   SDValue NewShift = DAG.getNode(N->getOpcode(),
5250                                  SDLoc(LHS->getOperand(0)),
5251                                  VT, LHS->getOperand(0), N->getOperand(1));
5252
5253   // Create the new binop.
5254   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5255 }
5256
5257 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5258   assert(N->getOpcode() == ISD::TRUNCATE);
5259   assert(N->getOperand(0).getOpcode() == ISD::AND);
5260
5261   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5262   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5263     SDValue N01 = N->getOperand(0).getOperand(1);
5264     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5265       SDLoc DL(N);
5266       EVT TruncVT = N->getValueType(0);
5267       SDValue N00 = N->getOperand(0).getOperand(0);
5268       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5269       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5270       AddToWorklist(Trunc00.getNode());
5271       AddToWorklist(Trunc01.getNode());
5272       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5273     }
5274   }
5275
5276   return SDValue();
5277 }
5278
5279 SDValue DAGCombiner::visitRotate(SDNode *N) {
5280   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5281   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5282       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5283     if (SDValue NewOp1 =
5284             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5285       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5286                          N->getOperand(0), NewOp1);
5287   }
5288   return SDValue();
5289 }
5290
5291 SDValue DAGCombiner::visitSHL(SDNode *N) {
5292   SDValue N0 = N->getOperand(0);
5293   SDValue N1 = N->getOperand(1);
5294   EVT VT = N0.getValueType();
5295   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5296
5297   // fold vector ops
5298   if (VT.isVector()) {
5299     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5300       return FoldedVOp;
5301
5302     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5303     // If setcc produces all-one true value then:
5304     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5305     if (N1CV && N1CV->isConstant()) {
5306       if (N0.getOpcode() == ISD::AND) {
5307         SDValue N00 = N0->getOperand(0);
5308         SDValue N01 = N0->getOperand(1);
5309         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5310
5311         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5312             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5313                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5314           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5315                                                      N01CV, N1CV))
5316             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5317         }
5318       }
5319     }
5320   }
5321
5322   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5323
5324   // fold (shl c1, c2) -> c1<<c2
5325   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5326   if (N0C && N1C && !N1C->isOpaque())
5327     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5328   // fold (shl 0, x) -> 0
5329   if (isNullConstantOrNullSplatConstant(N0))
5330     return N0;
5331   // fold (shl x, c >= size(x)) -> undef
5332   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5333     return DAG.getUNDEF(VT);
5334   // fold (shl x, 0) -> x
5335   if (N1C && N1C->isNullValue())
5336     return N0;
5337   // fold (shl undef, x) -> 0
5338   if (N0.isUndef())
5339     return DAG.getConstant(0, SDLoc(N), VT);
5340
5341   if (SDValue NewSel = foldBinOpIntoSelect(N))
5342     return NewSel;
5343
5344   // if (shl x, c) is known to be zero, return 0
5345   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5346                             APInt::getAllOnesValue(OpSizeInBits)))
5347     return DAG.getConstant(0, SDLoc(N), VT);
5348   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5349   if (N1.getOpcode() == ISD::TRUNCATE &&
5350       N1.getOperand(0).getOpcode() == ISD::AND) {
5351     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5352       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5353   }
5354
5355   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5356     return SDValue(N, 0);
5357
5358   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5359   if (N1C && N0.getOpcode() == ISD::SHL) {
5360     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5361       SDLoc DL(N);
5362       APInt c1 = N0C1->getAPIntValue();
5363       APInt c2 = N1C->getAPIntValue();
5364       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5365
5366       APInt Sum = c1 + c2;
5367       if (Sum.uge(OpSizeInBits))
5368         return DAG.getConstant(0, DL, VT);
5369
5370       return DAG.getNode(
5371           ISD::SHL, DL, VT, N0.getOperand(0),
5372           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5373     }
5374   }
5375
5376   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5377   // For this to be valid, the second form must not preserve any of the bits
5378   // that are shifted out by the inner shift in the first form.  This means
5379   // the outer shift size must be >= the number of bits added by the ext.
5380   // As a corollary, we don't care what kind of ext it is.
5381   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5382               N0.getOpcode() == ISD::ANY_EXTEND ||
5383               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5384       N0.getOperand(0).getOpcode() == ISD::SHL) {
5385     SDValue N0Op0 = N0.getOperand(0);
5386     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5387       APInt c1 = N0Op0C1->getAPIntValue();
5388       APInt c2 = N1C->getAPIntValue();
5389       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5390
5391       EVT InnerShiftVT = N0Op0.getValueType();
5392       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5393       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5394         SDLoc DL(N0);
5395         APInt Sum = c1 + c2;
5396         if (Sum.uge(OpSizeInBits))
5397           return DAG.getConstant(0, DL, VT);
5398
5399         return DAG.getNode(
5400             ISD::SHL, DL, VT,
5401             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5402             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5403       }
5404     }
5405   }
5406
5407   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5408   // Only fold this if the inner zext has no other uses to avoid increasing
5409   // the total number of instructions.
5410   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5411       N0.getOperand(0).getOpcode() == ISD::SRL) {
5412     SDValue N0Op0 = N0.getOperand(0);
5413     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5414       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5415         uint64_t c1 = N0Op0C1->getZExtValue();
5416         uint64_t c2 = N1C->getZExtValue();
5417         if (c1 == c2) {
5418           SDValue NewOp0 = N0.getOperand(0);
5419           EVT CountVT = NewOp0.getOperand(1).getValueType();
5420           SDLoc DL(N);
5421           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5422                                        NewOp0,
5423                                        DAG.getConstant(c2, DL, CountVT));
5424           AddToWorklist(NewSHL.getNode());
5425           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5426         }
5427       }
5428     }
5429   }
5430
5431   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5432   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5433   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5434       N0->getFlags().hasExact()) {
5435     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5436       uint64_t C1 = N0C1->getZExtValue();
5437       uint64_t C2 = N1C->getZExtValue();
5438       SDLoc DL(N);
5439       if (C1 <= C2)
5440         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5441                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5442       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5443                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5444     }
5445   }
5446
5447   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5448   //                               (and (srl x, (sub c1, c2), MASK)
5449   // Only fold this if the inner shift has no other uses -- if it does, folding
5450   // this will increase the total number of instructions.
5451   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5452     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5453       uint64_t c1 = N0C1->getZExtValue();
5454       if (c1 < OpSizeInBits) {
5455         uint64_t c2 = N1C->getZExtValue();
5456         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5457         SDValue Shift;
5458         if (c2 > c1) {
5459           Mask <<= c2 - c1;
5460           SDLoc DL(N);
5461           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5462                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5463         } else {
5464           Mask.lshrInPlace(c1 - c2);
5465           SDLoc DL(N);
5466           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5467                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5468         }
5469         SDLoc DL(N0);
5470         return DAG.getNode(ISD::AND, DL, VT, Shift,
5471                            DAG.getConstant(Mask, DL, VT));
5472       }
5473     }
5474   }
5475
5476   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5477   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5478       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5479     SDLoc DL(N);
5480     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5481     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5482     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5483   }
5484
5485   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5486   // Variant of version done on multiply, except mul by a power of 2 is turned
5487   // into a shift.
5488   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5489       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5490       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5491     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5492     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5493     AddToWorklist(Shl0.getNode());
5494     AddToWorklist(Shl1.getNode());
5495     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5496   }
5497
5498   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5499   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5500       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5501       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5502     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5503     if (isConstantOrConstantVector(Shl))
5504       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5505   }
5506
5507   if (N1C && !N1C->isOpaque())
5508     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5509       return NewSHL;
5510
5511   return SDValue();
5512 }
5513
5514 SDValue DAGCombiner::visitSRA(SDNode *N) {
5515   SDValue N0 = N->getOperand(0);
5516   SDValue N1 = N->getOperand(1);
5517   EVT VT = N0.getValueType();
5518   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5519
5520   // Arithmetic shifting an all-sign-bit value is a no-op.
5521   // fold (sra 0, x) -> 0
5522   // fold (sra -1, x) -> -1
5523   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5524     return N0;
5525
5526   // fold vector ops
5527   if (VT.isVector())
5528     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5529       return FoldedVOp;
5530
5531   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5532
5533   // fold (sra c1, c2) -> (sra c1, c2)
5534   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5535   if (N0C && N1C && !N1C->isOpaque())
5536     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5537   // fold (sra x, c >= size(x)) -> undef
5538   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5539     return DAG.getUNDEF(VT);
5540   // fold (sra x, 0) -> x
5541   if (N1C && N1C->isNullValue())
5542     return N0;
5543
5544   if (SDValue NewSel = foldBinOpIntoSelect(N))
5545     return NewSel;
5546
5547   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5548   // sext_inreg.
5549   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5550     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5551     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5552     if (VT.isVector())
5553       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5554                                ExtVT, VT.getVectorNumElements());
5555     if ((!LegalOperations ||
5556          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5557       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5558                          N0.getOperand(0), DAG.getValueType(ExtVT));
5559   }
5560
5561   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5562   if (N1C && N0.getOpcode() == ISD::SRA) {
5563     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5564       SDLoc DL(N);
5565       APInt c1 = N0C1->getAPIntValue();
5566       APInt c2 = N1C->getAPIntValue();
5567       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5568
5569       APInt Sum = c1 + c2;
5570       if (Sum.uge(OpSizeInBits))
5571         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5572
5573       return DAG.getNode(
5574           ISD::SRA, DL, VT, N0.getOperand(0),
5575           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5576     }
5577   }
5578
5579   // fold (sra (shl X, m), (sub result_size, n))
5580   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5581   // result_size - n != m.
5582   // If truncate is free for the target sext(shl) is likely to result in better
5583   // code.
5584   if (N0.getOpcode() == ISD::SHL && N1C) {
5585     // Get the two constanst of the shifts, CN0 = m, CN = n.
5586     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5587     if (N01C) {
5588       LLVMContext &Ctx = *DAG.getContext();
5589       // Determine what the truncate's result bitsize and type would be.
5590       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5591
5592       if (VT.isVector())
5593         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5594
5595       // Determine the residual right-shift amount.
5596       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5597
5598       // If the shift is not a no-op (in which case this should be just a sign
5599       // extend already), the truncated to type is legal, sign_extend is legal
5600       // on that type, and the truncate to that type is both legal and free,
5601       // perform the transform.
5602       if ((ShiftAmt > 0) &&
5603           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5604           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5605           TLI.isTruncateFree(VT, TruncVT)) {
5606
5607         SDLoc DL(N);
5608         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5609             getShiftAmountTy(N0.getOperand(0).getValueType()));
5610         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5611                                     N0.getOperand(0), Amt);
5612         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5613                                     Shift);
5614         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5615                            N->getValueType(0), Trunc);
5616       }
5617     }
5618   }
5619
5620   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5621   if (N1.getOpcode() == ISD::TRUNCATE &&
5622       N1.getOperand(0).getOpcode() == ISD::AND) {
5623     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5624       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5625   }
5626
5627   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5628   //      if c1 is equal to the number of bits the trunc removes
5629   if (N0.getOpcode() == ISD::TRUNCATE &&
5630       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5631        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5632       N0.getOperand(0).hasOneUse() &&
5633       N0.getOperand(0).getOperand(1).hasOneUse() &&
5634       N1C) {
5635     SDValue N0Op0 = N0.getOperand(0);
5636     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5637       unsigned LargeShiftVal = LargeShift->getZExtValue();
5638       EVT LargeVT = N0Op0.getValueType();
5639
5640       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5641         SDLoc DL(N);
5642         SDValue Amt =
5643           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5644                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5645         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5646                                   N0Op0.getOperand(0), Amt);
5647         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5648       }
5649     }
5650   }
5651
5652   // Simplify, based on bits shifted out of the LHS.
5653   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5654     return SDValue(N, 0);
5655
5656
5657   // If the sign bit is known to be zero, switch this to a SRL.
5658   if (DAG.SignBitIsZero(N0))
5659     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5660
5661   if (N1C && !N1C->isOpaque())
5662     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5663       return NewSRA;
5664
5665   return SDValue();
5666 }
5667
5668 SDValue DAGCombiner::visitSRL(SDNode *N) {
5669   SDValue N0 = N->getOperand(0);
5670   SDValue N1 = N->getOperand(1);
5671   EVT VT = N0.getValueType();
5672   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5673
5674   // fold vector ops
5675   if (VT.isVector())
5676     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5677       return FoldedVOp;
5678
5679   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5680
5681   // fold (srl c1, c2) -> c1 >>u c2
5682   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5683   if (N0C && N1C && !N1C->isOpaque())
5684     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5685   // fold (srl 0, x) -> 0
5686   if (isNullConstantOrNullSplatConstant(N0))
5687     return N0;
5688   // fold (srl x, c >= size(x)) -> undef
5689   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5690     return DAG.getUNDEF(VT);
5691   // fold (srl x, 0) -> x
5692   if (N1C && N1C->isNullValue())
5693     return N0;
5694
5695   if (SDValue NewSel = foldBinOpIntoSelect(N))
5696     return NewSel;
5697
5698   // if (srl x, c) is known to be zero, return 0
5699   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5700                                    APInt::getAllOnesValue(OpSizeInBits)))
5701     return DAG.getConstant(0, SDLoc(N), VT);
5702
5703   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5704   if (N1C && N0.getOpcode() == ISD::SRL) {
5705     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5706       SDLoc DL(N);
5707       APInt c1 = N0C1->getAPIntValue();
5708       APInt c2 = N1C->getAPIntValue();
5709       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5710
5711       APInt Sum = c1 + c2;
5712       if (Sum.uge(OpSizeInBits))
5713         return DAG.getConstant(0, DL, VT);
5714
5715       return DAG.getNode(
5716           ISD::SRL, DL, VT, N0.getOperand(0),
5717           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5718     }
5719   }
5720
5721   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5722   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5723       N0.getOperand(0).getOpcode() == ISD::SRL) {
5724     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5725       uint64_t c1 = N001C->getZExtValue();
5726       uint64_t c2 = N1C->getZExtValue();
5727       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5728       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5729       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5730       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5731       if (c1 + OpSizeInBits == InnerShiftSize) {
5732         SDLoc DL(N0);
5733         if (c1 + c2 >= InnerShiftSize)
5734           return DAG.getConstant(0, DL, VT);
5735         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5736                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5737                                        N0.getOperand(0).getOperand(0),
5738                                        DAG.getConstant(c1 + c2, DL,
5739                                                        ShiftCountVT)));
5740       }
5741     }
5742   }
5743
5744   // fold (srl (shl x, c), c) -> (and x, cst2)
5745   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5746       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5747     SDLoc DL(N);
5748     SDValue Mask =
5749         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5750     AddToWorklist(Mask.getNode());
5751     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5752   }
5753
5754   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5755   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5756     // Shifting in all undef bits?
5757     EVT SmallVT = N0.getOperand(0).getValueType();
5758     unsigned BitSize = SmallVT.getScalarSizeInBits();
5759     if (N1C->getZExtValue() >= BitSize)
5760       return DAG.getUNDEF(VT);
5761
5762     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5763       uint64_t ShiftAmt = N1C->getZExtValue();
5764       SDLoc DL0(N0);
5765       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5766                                        N0.getOperand(0),
5767                           DAG.getConstant(ShiftAmt, DL0,
5768                                           getShiftAmountTy(SmallVT)));
5769       AddToWorklist(SmallShift.getNode());
5770       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5771       SDLoc DL(N);
5772       return DAG.getNode(ISD::AND, DL, VT,
5773                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5774                          DAG.getConstant(Mask, DL, VT));
5775     }
5776   }
5777
5778   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5779   // bit, which is unmodified by sra.
5780   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5781     if (N0.getOpcode() == ISD::SRA)
5782       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5783   }
5784
5785   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5786   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5787       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5788     KnownBits Known;
5789     DAG.computeKnownBits(N0.getOperand(0), Known);
5790
5791     // If any of the input bits are KnownOne, then the input couldn't be all
5792     // zeros, thus the result of the srl will always be zero.
5793     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5794
5795     // If all of the bits input the to ctlz node are known to be zero, then
5796     // the result of the ctlz is "32" and the result of the shift is one.
5797     APInt UnknownBits = ~Known.Zero;
5798     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5799
5800     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5801     if (UnknownBits.isPowerOf2()) {
5802       // Okay, we know that only that the single bit specified by UnknownBits
5803       // could be set on input to the CTLZ node. If this bit is set, the SRL
5804       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5805       // to an SRL/XOR pair, which is likely to simplify more.
5806       unsigned ShAmt = UnknownBits.countTrailingZeros();
5807       SDValue Op = N0.getOperand(0);
5808
5809       if (ShAmt) {
5810         SDLoc DL(N0);
5811         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5812                   DAG.getConstant(ShAmt, DL,
5813                                   getShiftAmountTy(Op.getValueType())));
5814         AddToWorklist(Op.getNode());
5815       }
5816
5817       SDLoc DL(N);
5818       return DAG.getNode(ISD::XOR, DL, VT,
5819                          Op, DAG.getConstant(1, DL, VT));
5820     }
5821   }
5822
5823   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5824   if (N1.getOpcode() == ISD::TRUNCATE &&
5825       N1.getOperand(0).getOpcode() == ISD::AND) {
5826     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5827       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5828   }
5829
5830   // fold operands of srl based on knowledge that the low bits are not
5831   // demanded.
5832   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5833     return SDValue(N, 0);
5834
5835   if (N1C && !N1C->isOpaque())
5836     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5837       return NewSRL;
5838
5839   // Attempt to convert a srl of a load into a narrower zero-extending load.
5840   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5841     return NarrowLoad;
5842
5843   // Here is a common situation. We want to optimize:
5844   //
5845   //   %a = ...
5846   //   %b = and i32 %a, 2
5847   //   %c = srl i32 %b, 1
5848   //   brcond i32 %c ...
5849   //
5850   // into
5851   //
5852   //   %a = ...
5853   //   %b = and %a, 2
5854   //   %c = setcc eq %b, 0
5855   //   brcond %c ...
5856   //
5857   // However when after the source operand of SRL is optimized into AND, the SRL
5858   // itself may not be optimized further. Look for it and add the BRCOND into
5859   // the worklist.
5860   if (N->hasOneUse()) {
5861     SDNode *Use = *N->use_begin();
5862     if (Use->getOpcode() == ISD::BRCOND)
5863       AddToWorklist(Use);
5864     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5865       // Also look pass the truncate.
5866       Use = *Use->use_begin();
5867       if (Use->getOpcode() == ISD::BRCOND)
5868         AddToWorklist(Use);
5869     }
5870   }
5871
5872   return SDValue();
5873 }
5874
5875 SDValue DAGCombiner::visitABS(SDNode *N) {
5876   SDValue N0 = N->getOperand(0);
5877   EVT VT = N->getValueType(0);
5878
5879   // fold (abs c1) -> c2
5880   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5881     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5882   // fold (abs (abs x)) -> (abs x)
5883   if (N0.getOpcode() == ISD::ABS)
5884     return N0;
5885   // fold (abs x) -> x iff not-negative
5886   if (DAG.SignBitIsZero(N0))
5887     return N0;
5888   return SDValue();
5889 }
5890
5891 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5892   SDValue N0 = N->getOperand(0);
5893   EVT VT = N->getValueType(0);
5894
5895   // fold (bswap c1) -> c2
5896   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5897     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5898   // fold (bswap (bswap x)) -> x
5899   if (N0.getOpcode() == ISD::BSWAP)
5900     return N0->getOperand(0);
5901   return SDValue();
5902 }
5903
5904 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5905   SDValue N0 = N->getOperand(0);
5906   EVT VT = N->getValueType(0);
5907
5908   // fold (bitreverse c1) -> c2
5909   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5910     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5911   // fold (bitreverse (bitreverse x)) -> x
5912   if (N0.getOpcode() == ISD::BITREVERSE)
5913     return N0.getOperand(0);
5914   return SDValue();
5915 }
5916
5917 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5918   SDValue N0 = N->getOperand(0);
5919   EVT VT = N->getValueType(0);
5920
5921   // fold (ctlz c1) -> c2
5922   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5923     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5924   return SDValue();
5925 }
5926
5927 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5928   SDValue N0 = N->getOperand(0);
5929   EVT VT = N->getValueType(0);
5930
5931   // fold (ctlz_zero_undef c1) -> c2
5932   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5933     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5934   return SDValue();
5935 }
5936
5937 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5938   SDValue N0 = N->getOperand(0);
5939   EVT VT = N->getValueType(0);
5940
5941   // fold (cttz c1) -> c2
5942   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5943     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5944   return SDValue();
5945 }
5946
5947 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5948   SDValue N0 = N->getOperand(0);
5949   EVT VT = N->getValueType(0);
5950
5951   // fold (cttz_zero_undef c1) -> c2
5952   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5953     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5954   return SDValue();
5955 }
5956
5957 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5958   SDValue N0 = N->getOperand(0);
5959   EVT VT = N->getValueType(0);
5960
5961   // fold (ctpop c1) -> c2
5962   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5963     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5964   return SDValue();
5965 }
5966
5967
5968 /// \brief Generate Min/Max node
5969 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5970                                    SDValue RHS, SDValue True, SDValue False,
5971                                    ISD::CondCode CC, const TargetLowering &TLI,
5972                                    SelectionDAG &DAG) {
5973   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5974     return SDValue();
5975
5976   switch (CC) {
5977   case ISD::SETOLT:
5978   case ISD::SETOLE:
5979   case ISD::SETLT:
5980   case ISD::SETLE:
5981   case ISD::SETULT:
5982   case ISD::SETULE: {
5983     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5984     if (TLI.isOperationLegal(Opcode, VT))
5985       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5986     return SDValue();
5987   }
5988   case ISD::SETOGT:
5989   case ISD::SETOGE:
5990   case ISD::SETGT:
5991   case ISD::SETGE:
5992   case ISD::SETUGT:
5993   case ISD::SETUGE: {
5994     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5995     if (TLI.isOperationLegal(Opcode, VT))
5996       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5997     return SDValue();
5998   }
5999   default:
6000     return SDValue();
6001   }
6002 }
6003
6004 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6005   SDValue Cond = N->getOperand(0);
6006   SDValue N1 = N->getOperand(1);
6007   SDValue N2 = N->getOperand(2);
6008   EVT VT = N->getValueType(0);
6009   EVT CondVT = Cond.getValueType();
6010   SDLoc DL(N);
6011
6012   if (!VT.isInteger())
6013     return SDValue();
6014
6015   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6016   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6017   if (!C1 || !C2)
6018     return SDValue();
6019
6020   // Only do this before legalization to avoid conflicting with target-specific
6021   // transforms in the other direction (create a select from a zext/sext). There
6022   // is also a target-independent combine here in DAGCombiner in the other
6023   // direction for (select Cond, -1, 0) when the condition is not i1.
6024   if (CondVT == MVT::i1 && !LegalOperations) {
6025     if (C1->isNullValue() && C2->isOne()) {
6026       // select Cond, 0, 1 --> zext (!Cond)
6027       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6028       if (VT != MVT::i1)
6029         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6030       return NotCond;
6031     }
6032     if (C1->isNullValue() && C2->isAllOnesValue()) {
6033       // select Cond, 0, -1 --> sext (!Cond)
6034       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6035       if (VT != MVT::i1)
6036         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6037       return NotCond;
6038     }
6039     if (C1->isOne() && C2->isNullValue()) {
6040       // select Cond, 1, 0 --> zext (Cond)
6041       if (VT != MVT::i1)
6042         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6043       return Cond;
6044     }
6045     if (C1->isAllOnesValue() && C2->isNullValue()) {
6046       // select Cond, -1, 0 --> sext (Cond)
6047       if (VT != MVT::i1)
6048         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6049       return Cond;
6050     }
6051
6052     // For any constants that differ by 1, we can transform the select into an
6053     // extend and add. Use a target hook because some targets may prefer to
6054     // transform in the other direction.
6055     if (TLI.convertSelectOfConstantsToMath()) {
6056       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6057         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6058         if (VT != MVT::i1)
6059           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6060         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6061       }
6062       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6063         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6064         if (VT != MVT::i1)
6065           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6066         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6067       }
6068     }
6069
6070     return SDValue();
6071   }
6072
6073   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6074   // We can't do this reliably if integer based booleans have different contents
6075   // to floating point based booleans. This is because we can't tell whether we
6076   // have an integer-based boolean or a floating-point-based boolean unless we
6077   // can find the SETCC that produced it and inspect its operands. This is
6078   // fairly easy if C is the SETCC node, but it can potentially be
6079   // undiscoverable (or not reasonably discoverable). For example, it could be
6080   // in another basic block or it could require searching a complicated
6081   // expression.
6082   if (CondVT.isInteger() &&
6083       TLI.getBooleanContents(false, true) ==
6084           TargetLowering::ZeroOrOneBooleanContent &&
6085       TLI.getBooleanContents(false, false) ==
6086           TargetLowering::ZeroOrOneBooleanContent &&
6087       C1->isNullValue() && C2->isOne()) {
6088     SDValue NotCond =
6089         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6090     if (VT.bitsEq(CondVT))
6091       return NotCond;
6092     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6093   }
6094
6095   return SDValue();
6096 }
6097
6098 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6099   SDValue N0 = N->getOperand(0);
6100   SDValue N1 = N->getOperand(1);
6101   SDValue N2 = N->getOperand(2);
6102   EVT VT = N->getValueType(0);
6103   EVT VT0 = N0.getValueType();
6104
6105   // fold (select C, X, X) -> X
6106   if (N1 == N2)
6107     return N1;
6108   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6109     // fold (select true, X, Y) -> X
6110     // fold (select false, X, Y) -> Y
6111     return !N0C->isNullValue() ? N1 : N2;
6112   }
6113   // fold (select X, X, Y) -> (or X, Y)
6114   // fold (select X, 1, Y) -> (or C, Y)
6115   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6116     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6117
6118   if (SDValue V = foldSelectOfConstants(N))
6119     return V;
6120
6121   // fold (select C, 0, X) -> (and (not C), X)
6122   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6123     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6124     AddToWorklist(NOTNode.getNode());
6125     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6126   }
6127   // fold (select C, X, 1) -> (or (not C), X)
6128   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6129     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6130     AddToWorklist(NOTNode.getNode());
6131     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6132   }
6133   // fold (select X, Y, X) -> (and X, Y)
6134   // fold (select X, Y, 0) -> (and X, Y)
6135   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6136     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6137
6138   // If we can fold this based on the true/false value, do so.
6139   if (SimplifySelectOps(N, N1, N2))
6140     return SDValue(N, 0);  // Don't revisit N.
6141
6142   if (VT0 == MVT::i1) {
6143     // The code in this block deals with the following 2 equivalences:
6144     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6145     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6146     // The target can specify its preferred form with the
6147     // shouldNormalizeToSelectSequence() callback. However we always transform
6148     // to the right anyway if we find the inner select exists in the DAG anyway
6149     // and we always transform to the left side if we know that we can further
6150     // optimize the combination of the conditions.
6151     bool normalizeToSequence
6152       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6153     // select (and Cond0, Cond1), X, Y
6154     //   -> select Cond0, (select Cond1, X, Y), Y
6155     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6156       SDValue Cond0 = N0->getOperand(0);
6157       SDValue Cond1 = N0->getOperand(1);
6158       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6159                                         N1.getValueType(), Cond1, N1, N2);
6160       if (normalizeToSequence || !InnerSelect.use_empty())
6161         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6162                            InnerSelect, N2);
6163     }
6164     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6165     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6166       SDValue Cond0 = N0->getOperand(0);
6167       SDValue Cond1 = N0->getOperand(1);
6168       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6169                                         N1.getValueType(), Cond1, N1, N2);
6170       if (normalizeToSequence || !InnerSelect.use_empty())
6171         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6172                            InnerSelect);
6173     }
6174
6175     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6176     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6177       SDValue N1_0 = N1->getOperand(0);
6178       SDValue N1_1 = N1->getOperand(1);
6179       SDValue N1_2 = N1->getOperand(2);
6180       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6181         // Create the actual and node if we can generate good code for it.
6182         if (!normalizeToSequence) {
6183           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6184                                     N0, N1_0);
6185           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6186                              N1_1, N2);
6187         }
6188         // Otherwise see if we can optimize the "and" to a better pattern.
6189         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6190           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6191                              N1_1, N2);
6192       }
6193     }
6194     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6195     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6196       SDValue N2_0 = N2->getOperand(0);
6197       SDValue N2_1 = N2->getOperand(1);
6198       SDValue N2_2 = N2->getOperand(2);
6199       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6200         // Create the actual or node if we can generate good code for it.
6201         if (!normalizeToSequence) {
6202           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6203                                    N0, N2_0);
6204           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6205                              N1, N2_2);
6206         }
6207         // Otherwise see if we can optimize to a better pattern.
6208         if (SDValue Combined = visitORLike(N0, N2_0, N))
6209           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6210                              N1, N2_2);
6211       }
6212     }
6213   }
6214
6215   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6216   if (VT0 == MVT::i1) {
6217     if (N0->getOpcode() == ISD::XOR) {
6218       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6219         SDValue Cond0 = N0->getOperand(0);
6220         if (C->isOne())
6221           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6222                              Cond0, N2, N1);
6223       }
6224     }
6225   }
6226
6227   // fold selects based on a setcc into other things, such as min/max/abs
6228   if (N0.getOpcode() == ISD::SETCC) {
6229     // select x, y (fcmp lt x, y) -> fminnum x, y
6230     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6231     //
6232     // This is OK if we don't care about what happens if either operand is a
6233     // NaN.
6234     //
6235
6236     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6237     // no signed zeros as well as no nans.
6238     const TargetOptions &Options = DAG.getTarget().Options;
6239     if (Options.UnsafeFPMath &&
6240         VT.isFloatingPoint() && N0.hasOneUse() &&
6241         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6242       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6243
6244       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6245                                                 N0.getOperand(1), N1, N2, CC,
6246                                                 TLI, DAG))
6247         return FMinMax;
6248     }
6249
6250     if ((!LegalOperations &&
6251          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6252         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6253       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6254                          N0.getOperand(0), N0.getOperand(1),
6255                          N1, N2, N0.getOperand(2));
6256     return SimplifySelect(SDLoc(N), N0, N1, N2);
6257   }
6258
6259   return SDValue();
6260 }
6261
6262 static
6263 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6264   SDLoc DL(N);
6265   EVT LoVT, HiVT;
6266   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6267
6268   // Split the inputs.
6269   SDValue Lo, Hi, LL, LH, RL, RH;
6270   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6271   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6272
6273   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6274   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6275
6276   return std::make_pair(Lo, Hi);
6277 }
6278
6279 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6280 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6281 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6282   SDLoc DL(N);
6283   SDValue Cond = N->getOperand(0);
6284   SDValue LHS = N->getOperand(1);
6285   SDValue RHS = N->getOperand(2);
6286   EVT VT = N->getValueType(0);
6287   int NumElems = VT.getVectorNumElements();
6288   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6289          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6290          Cond.getOpcode() == ISD::BUILD_VECTOR);
6291
6292   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6293   // binary ones here.
6294   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6295     return SDValue();
6296
6297   // We're sure we have an even number of elements due to the
6298   // concat_vectors we have as arguments to vselect.
6299   // Skip BV elements until we find one that's not an UNDEF
6300   // After we find an UNDEF element, keep looping until we get to half the
6301   // length of the BV and see if all the non-undef nodes are the same.
6302   ConstantSDNode *BottomHalf = nullptr;
6303   for (int i = 0; i < NumElems / 2; ++i) {
6304     if (Cond->getOperand(i)->isUndef())
6305       continue;
6306
6307     if (BottomHalf == nullptr)
6308       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6309     else if (Cond->getOperand(i).getNode() != BottomHalf)
6310       return SDValue();
6311   }
6312
6313   // Do the same for the second half of the BuildVector
6314   ConstantSDNode *TopHalf = nullptr;
6315   for (int i = NumElems / 2; i < NumElems; ++i) {
6316     if (Cond->getOperand(i)->isUndef())
6317       continue;
6318
6319     if (TopHalf == nullptr)
6320       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6321     else if (Cond->getOperand(i).getNode() != TopHalf)
6322       return SDValue();
6323   }
6324
6325   assert(TopHalf && BottomHalf &&
6326          "One half of the selector was all UNDEFs and the other was all the "
6327          "same value. This should have been addressed before this function.");
6328   return DAG.getNode(
6329       ISD::CONCAT_VECTORS, DL, VT,
6330       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6331       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6332 }
6333
6334 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6335
6336   if (Level >= AfterLegalizeTypes)
6337     return SDValue();
6338
6339   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6340   SDValue Mask = MSC->getMask();
6341   SDValue Data  = MSC->getValue();
6342   SDLoc DL(N);
6343
6344   // If the MSCATTER data type requires splitting and the mask is provided by a
6345   // SETCC, then split both nodes and its operands before legalization. This
6346   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6347   // and enables future optimizations (e.g. min/max pattern matching on X86).
6348   if (Mask.getOpcode() != ISD::SETCC)
6349     return SDValue();
6350
6351   // Check if any splitting is required.
6352   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6353       TargetLowering::TypeSplitVector)
6354     return SDValue();
6355   SDValue MaskLo, MaskHi, Lo, Hi;
6356   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6357
6358   EVT LoVT, HiVT;
6359   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6360
6361   SDValue Chain = MSC->getChain();
6362
6363   EVT MemoryVT = MSC->getMemoryVT();
6364   unsigned Alignment = MSC->getOriginalAlignment();
6365
6366   EVT LoMemVT, HiMemVT;
6367   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6368
6369   SDValue DataLo, DataHi;
6370   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6371
6372   SDValue BasePtr = MSC->getBasePtr();
6373   SDValue IndexLo, IndexHi;
6374   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6375
6376   MachineMemOperand *MMO = DAG.getMachineFunction().
6377     getMachineMemOperand(MSC->getPointerInfo(),
6378                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6379                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6380
6381   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6382   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6383                             DL, OpsLo, MMO);
6384
6385   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6386   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6387                             DL, OpsHi, MMO);
6388
6389   AddToWorklist(Lo.getNode());
6390   AddToWorklist(Hi.getNode());
6391
6392   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6393 }
6394
6395 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6396
6397   if (Level >= AfterLegalizeTypes)
6398     return SDValue();
6399
6400   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6401   SDValue Mask = MST->getMask();
6402   SDValue Data  = MST->getValue();
6403   EVT VT = Data.getValueType();
6404   SDLoc DL(N);
6405
6406   // If the MSTORE data type requires splitting and the mask is provided by a
6407   // SETCC, then split both nodes and its operands before legalization. This
6408   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6409   // and enables future optimizations (e.g. min/max pattern matching on X86).
6410   if (Mask.getOpcode() == ISD::SETCC) {
6411
6412     // Check if any splitting is required.
6413     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6414         TargetLowering::TypeSplitVector)
6415       return SDValue();
6416
6417     SDValue MaskLo, MaskHi, Lo, Hi;
6418     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6419
6420     SDValue Chain = MST->getChain();
6421     SDValue Ptr   = MST->getBasePtr();
6422
6423     EVT MemoryVT = MST->getMemoryVT();
6424     unsigned Alignment = MST->getOriginalAlignment();
6425
6426     // if Alignment is equal to the vector size,
6427     // take the half of it for the second part
6428     unsigned SecondHalfAlignment =
6429       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6430
6431     EVT LoMemVT, HiMemVT;
6432     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6433
6434     SDValue DataLo, DataHi;
6435     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6436
6437     MachineMemOperand *MMO = DAG.getMachineFunction().
6438       getMachineMemOperand(MST->getPointerInfo(),
6439                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6440                            Alignment, MST->getAAInfo(), MST->getRanges());
6441
6442     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6443                             MST->isTruncatingStore(),
6444                             MST->isCompressingStore());
6445
6446     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6447                                      MST->isCompressingStore());
6448
6449     MMO = DAG.getMachineFunction().
6450       getMachineMemOperand(MST->getPointerInfo(),
6451                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6452                            SecondHalfAlignment, MST->getAAInfo(),
6453                            MST->getRanges());
6454
6455     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6456                             MST->isTruncatingStore(),
6457                             MST->isCompressingStore());
6458
6459     AddToWorklist(Lo.getNode());
6460     AddToWorklist(Hi.getNode());
6461
6462     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6463   }
6464   return SDValue();
6465 }
6466
6467 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6468
6469   if (Level >= AfterLegalizeTypes)
6470     return SDValue();
6471
6472   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6473   SDValue Mask = MGT->getMask();
6474   SDLoc DL(N);
6475
6476   // If the MGATHER result requires splitting and the mask is provided by a
6477   // SETCC, then split both nodes and its operands before legalization. This
6478   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6479   // and enables future optimizations (e.g. min/max pattern matching on X86).
6480
6481   if (Mask.getOpcode() != ISD::SETCC)
6482     return SDValue();
6483
6484   EVT VT = N->getValueType(0);
6485
6486   // Check if any splitting is required.
6487   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6488       TargetLowering::TypeSplitVector)
6489     return SDValue();
6490
6491   SDValue MaskLo, MaskHi, Lo, Hi;
6492   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6493
6494   SDValue Src0 = MGT->getValue();
6495   SDValue Src0Lo, Src0Hi;
6496   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6497
6498   EVT LoVT, HiVT;
6499   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6500
6501   SDValue Chain = MGT->getChain();
6502   EVT MemoryVT = MGT->getMemoryVT();
6503   unsigned Alignment = MGT->getOriginalAlignment();
6504
6505   EVT LoMemVT, HiMemVT;
6506   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6507
6508   SDValue BasePtr = MGT->getBasePtr();
6509   SDValue Index = MGT->getIndex();
6510   SDValue IndexLo, IndexHi;
6511   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6512
6513   MachineMemOperand *MMO = DAG.getMachineFunction().
6514     getMachineMemOperand(MGT->getPointerInfo(),
6515                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6516                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6517
6518   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6519   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6520                             MMO);
6521
6522   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6523   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6524                             MMO);
6525
6526   AddToWorklist(Lo.getNode());
6527   AddToWorklist(Hi.getNode());
6528
6529   // Build a factor node to remember that this load is independent of the
6530   // other one.
6531   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6532                       Hi.getValue(1));
6533
6534   // Legalized the chain result - switch anything that used the old chain to
6535   // use the new one.
6536   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6537
6538   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6539
6540   SDValue RetOps[] = { GatherRes, Chain };
6541   return DAG.getMergeValues(RetOps, DL);
6542 }
6543
6544 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6545
6546   if (Level >= AfterLegalizeTypes)
6547     return SDValue();
6548
6549   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6550   SDValue Mask = MLD->getMask();
6551   SDLoc DL(N);
6552
6553   // If the MLOAD result requires splitting and the mask is provided by a
6554   // SETCC, then split both nodes and its operands before legalization. This
6555   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6556   // and enables future optimizations (e.g. min/max pattern matching on X86).
6557
6558   if (Mask.getOpcode() == ISD::SETCC) {
6559     EVT VT = N->getValueType(0);
6560
6561     // Check if any splitting is required.
6562     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6563         TargetLowering::TypeSplitVector)
6564       return SDValue();
6565
6566     SDValue MaskLo, MaskHi, Lo, Hi;
6567     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6568
6569     SDValue Src0 = MLD->getSrc0();
6570     SDValue Src0Lo, Src0Hi;
6571     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6572
6573     EVT LoVT, HiVT;
6574     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6575
6576     SDValue Chain = MLD->getChain();
6577     SDValue Ptr   = MLD->getBasePtr();
6578     EVT MemoryVT = MLD->getMemoryVT();
6579     unsigned Alignment = MLD->getOriginalAlignment();
6580
6581     // if Alignment is equal to the vector size,
6582     // take the half of it for the second part
6583     unsigned SecondHalfAlignment =
6584       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6585          Alignment/2 : Alignment;
6586
6587     EVT LoMemVT, HiMemVT;
6588     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6589
6590     MachineMemOperand *MMO = DAG.getMachineFunction().
6591     getMachineMemOperand(MLD->getPointerInfo(),
6592                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6593                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6594
6595     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6596                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6597
6598     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6599                                      MLD->isExpandingLoad());
6600
6601     MMO = DAG.getMachineFunction().
6602     getMachineMemOperand(MLD->getPointerInfo(),
6603                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6604                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6605
6606     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6607                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6608
6609     AddToWorklist(Lo.getNode());
6610     AddToWorklist(Hi.getNode());
6611
6612     // Build a factor node to remember that this load is independent of the
6613     // other one.
6614     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6615                         Hi.getValue(1));
6616
6617     // Legalized the chain result - switch anything that used the old chain to
6618     // use the new one.
6619     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6620
6621     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6622
6623     SDValue RetOps[] = { LoadRes, Chain };
6624     return DAG.getMergeValues(RetOps, DL);
6625   }
6626   return SDValue();
6627 }
6628
6629 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6630   SDValue N0 = N->getOperand(0);
6631   SDValue N1 = N->getOperand(1);
6632   SDValue N2 = N->getOperand(2);
6633   SDLoc DL(N);
6634
6635   // fold (vselect C, X, X) -> X
6636   if (N1 == N2)
6637     return N1;
6638
6639   // Canonicalize integer abs.
6640   // vselect (setg[te] X,  0),  X, -X ->
6641   // vselect (setgt    X, -1),  X, -X ->
6642   // vselect (setl[te] X,  0), -X,  X ->
6643   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6644   if (N0.getOpcode() == ISD::SETCC) {
6645     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6646     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6647     bool isAbs = false;
6648     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6649
6650     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6651          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6652         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6653       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6654     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6655              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6656       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6657
6658     if (isAbs) {
6659       EVT VT = LHS.getValueType();
6660       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6661         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6662
6663       SDValue Shift = DAG.getNode(
6664           ISD::SRA, DL, VT, LHS,
6665           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6666       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6667       AddToWorklist(Shift.getNode());
6668       AddToWorklist(Add.getNode());
6669       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6670     }
6671   }
6672
6673   if (SimplifySelectOps(N, N1, N2))
6674     return SDValue(N, 0);  // Don't revisit N.
6675
6676   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6677   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6678     return N1;
6679   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6680   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6681     return N2;
6682
6683   // The ConvertSelectToConcatVector function is assuming both the above
6684   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6685   // and addressed.
6686   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6687       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6688       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6689     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6690       return CV;
6691   }
6692
6693   return SDValue();
6694 }
6695
6696 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6697   SDValue N0 = N->getOperand(0);
6698   SDValue N1 = N->getOperand(1);
6699   SDValue N2 = N->getOperand(2);
6700   SDValue N3 = N->getOperand(3);
6701   SDValue N4 = N->getOperand(4);
6702   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6703
6704   // fold select_cc lhs, rhs, x, x, cc -> x
6705   if (N2 == N3)
6706     return N2;
6707
6708   // Determine if the condition we're dealing with is constant
6709   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6710                                   CC, SDLoc(N), false)) {
6711     AddToWorklist(SCC.getNode());
6712
6713     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6714       if (!SCCC->isNullValue())
6715         return N2;    // cond always true -> true val
6716       else
6717         return N3;    // cond always false -> false val
6718     } else if (SCC->isUndef()) {
6719       // When the condition is UNDEF, just return the first operand. This is
6720       // coherent the DAG creation, no setcc node is created in this case
6721       return N2;
6722     } else if (SCC.getOpcode() == ISD::SETCC) {
6723       // Fold to a simpler select_cc
6724       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6725                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6726                          SCC.getOperand(2));
6727     }
6728   }
6729
6730   // If we can fold this based on the true/false value, do so.
6731   if (SimplifySelectOps(N, N2, N3))
6732     return SDValue(N, 0);  // Don't revisit N.
6733
6734   // fold select_cc into other things, such as min/max/abs
6735   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6736 }
6737
6738 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6739   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6740                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6741                        SDLoc(N));
6742 }
6743
6744 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6745   SDValue LHS = N->getOperand(0);
6746   SDValue RHS = N->getOperand(1);
6747   SDValue Carry = N->getOperand(2);
6748   SDValue Cond = N->getOperand(3);
6749
6750   // If Carry is false, fold to a regular SETCC.
6751   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6752     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6753
6754   return SDValue();
6755 }
6756
6757 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6758 /// a build_vector of constants.
6759 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6760 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6761 /// Vector extends are not folded if operations are legal; this is to
6762 /// avoid introducing illegal build_vector dag nodes.
6763 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6764                                          SelectionDAG &DAG, bool LegalTypes,
6765                                          bool LegalOperations) {
6766   unsigned Opcode = N->getOpcode();
6767   SDValue N0 = N->getOperand(0);
6768   EVT VT = N->getValueType(0);
6769
6770   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6771          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6772          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6773          && "Expected EXTEND dag node in input!");
6774
6775   // fold (sext c1) -> c1
6776   // fold (zext c1) -> c1
6777   // fold (aext c1) -> c1
6778   if (isa<ConstantSDNode>(N0))
6779     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6780
6781   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6782   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6783   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6784   EVT SVT = VT.getScalarType();
6785   if (!(VT.isVector() &&
6786       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6787       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6788     return nullptr;
6789
6790   // We can fold this node into a build_vector.
6791   unsigned VTBits = SVT.getSizeInBits();
6792   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6793   SmallVector<SDValue, 8> Elts;
6794   unsigned NumElts = VT.getVectorNumElements();
6795   SDLoc DL(N);
6796
6797   for (unsigned i=0; i != NumElts; ++i) {
6798     SDValue Op = N0->getOperand(i);
6799     if (Op->isUndef()) {
6800       Elts.push_back(DAG.getUNDEF(SVT));
6801       continue;
6802     }
6803
6804     SDLoc DL(Op);
6805     // Get the constant value and if needed trunc it to the size of the type.
6806     // Nodes like build_vector might have constants wider than the scalar type.
6807     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6808     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6809       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6810     else
6811       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6812   }
6813
6814   return DAG.getBuildVector(VT, DL, Elts).getNode();
6815 }
6816
6817 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6818 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6819 // transformation. Returns true if extension are possible and the above
6820 // mentioned transformation is profitable.
6821 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6822                                     unsigned ExtOpc,
6823                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6824                                     const TargetLowering &TLI) {
6825   bool HasCopyToRegUses = false;
6826   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6827   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6828                             UE = N0.getNode()->use_end();
6829        UI != UE; ++UI) {
6830     SDNode *User = *UI;
6831     if (User == N)
6832       continue;
6833     if (UI.getUse().getResNo() != N0.getResNo())
6834       continue;
6835     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6836     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6837       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6838       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6839         // Sign bits will be lost after a zext.
6840         return false;
6841       bool Add = false;
6842       for (unsigned i = 0; i != 2; ++i) {
6843         SDValue UseOp = User->getOperand(i);
6844         if (UseOp == N0)
6845           continue;
6846         if (!isa<ConstantSDNode>(UseOp))
6847           return false;
6848         Add = true;
6849       }
6850       if (Add)
6851         ExtendNodes.push_back(User);
6852       continue;
6853     }
6854     // If truncates aren't free and there are users we can't
6855     // extend, it isn't worthwhile.
6856     if (!isTruncFree)
6857       return false;
6858     // Remember if this value is live-out.
6859     if (User->getOpcode() == ISD::CopyToReg)
6860       HasCopyToRegUses = true;
6861   }
6862
6863   if (HasCopyToRegUses) {
6864     bool BothLiveOut = false;
6865     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6866          UI != UE; ++UI) {
6867       SDUse &Use = UI.getUse();
6868       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6869         BothLiveOut = true;
6870         break;
6871       }
6872     }
6873     if (BothLiveOut)
6874       // Both unextended and extended values are live out. There had better be
6875       // a good reason for the transformation.
6876       return ExtendNodes.size();
6877   }
6878   return true;
6879 }
6880
6881 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6882                                   SDValue Trunc, SDValue ExtLoad,
6883                                   const SDLoc &DL, ISD::NodeType ExtType) {
6884   // Extend SetCC uses if necessary.
6885   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6886     SDNode *SetCC = SetCCs[i];
6887     SmallVector<SDValue, 4> Ops;
6888
6889     for (unsigned j = 0; j != 2; ++j) {
6890       SDValue SOp = SetCC->getOperand(j);
6891       if (SOp == Trunc)
6892         Ops.push_back(ExtLoad);
6893       else
6894         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6895     }
6896
6897     Ops.push_back(SetCC->getOperand(2));
6898     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6899   }
6900 }
6901
6902 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6903 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6904   SDValue N0 = N->getOperand(0);
6905   EVT DstVT = N->getValueType(0);
6906   EVT SrcVT = N0.getValueType();
6907
6908   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6909           N->getOpcode() == ISD::ZERO_EXTEND) &&
6910          "Unexpected node type (not an extend)!");
6911
6912   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6913   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6914   //   (v8i32 (sext (v8i16 (load x))))
6915   // into:
6916   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6917   //                          (v4i32 (sextload (x + 16)))))
6918   // Where uses of the original load, i.e.:
6919   //   (v8i16 (load x))
6920   // are replaced with:
6921   //   (v8i16 (truncate
6922   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6923   //                            (v4i32 (sextload (x + 16)))))))
6924   //
6925   // This combine is only applicable to illegal, but splittable, vectors.
6926   // All legal types, and illegal non-vector types, are handled elsewhere.
6927   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6928   //
6929   if (N0->getOpcode() != ISD::LOAD)
6930     return SDValue();
6931
6932   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6933
6934   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6935       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6936       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6937     return SDValue();
6938
6939   SmallVector<SDNode *, 4> SetCCs;
6940   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6941     return SDValue();
6942
6943   ISD::LoadExtType ExtType =
6944       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6945
6946   // Try to split the vector types to get down to legal types.
6947   EVT SplitSrcVT = SrcVT;
6948   EVT SplitDstVT = DstVT;
6949   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6950          SplitSrcVT.getVectorNumElements() > 1) {
6951     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6952     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6953   }
6954
6955   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6956     return SDValue();
6957
6958   SDLoc DL(N);
6959   const unsigned NumSplits =
6960       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6961   const unsigned Stride = SplitSrcVT.getStoreSize();
6962   SmallVector<SDValue, 4> Loads;
6963   SmallVector<SDValue, 4> Chains;
6964
6965   SDValue BasePtr = LN0->getBasePtr();
6966   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6967     const unsigned Offset = Idx * Stride;
6968     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6969
6970     SDValue SplitLoad = DAG.getExtLoad(
6971         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6972         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6973         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6974
6975     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6976                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6977
6978     Loads.push_back(SplitLoad.getValue(0));
6979     Chains.push_back(SplitLoad.getValue(1));
6980   }
6981
6982   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6983   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6984
6985   // Simplify TF.
6986   AddToWorklist(NewChain.getNode());
6987
6988   CombineTo(N, NewValue);
6989
6990   // Replace uses of the original load (before extension)
6991   // with a truncate of the concatenated sextloaded vectors.
6992   SDValue Trunc =
6993       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6994   CombineTo(N0.getNode(), Trunc, NewChain);
6995   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6996                   (ISD::NodeType)N->getOpcode());
6997   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6998 }
6999
7000 /// If we're narrowing or widening the result of a vector select and the final
7001 /// size is the same size as a setcc (compare) feeding the select, then try to
7002 /// apply the cast operation to the select's operands because matching vector
7003 /// sizes for a select condition and other operands should be more efficient.
7004 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7005   unsigned CastOpcode = Cast->getOpcode();
7006   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7007           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7008           CastOpcode == ISD::FP_ROUND) &&
7009          "Unexpected opcode for vector select narrowing/widening");
7010
7011   // We only do this transform before legal ops because the pattern may be
7012   // obfuscated by target-specific operations after legalization. Do not create
7013   // an illegal select op, however, because that may be difficult to lower.
7014   EVT VT = Cast->getValueType(0);
7015   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7016     return SDValue();
7017
7018   SDValue VSel = Cast->getOperand(0);
7019   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7020       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7021     return SDValue();
7022
7023   // Does the setcc have the same vector size as the casted select?
7024   SDValue SetCC = VSel.getOperand(0);
7025   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7026   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7027     return SDValue();
7028
7029   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7030   SDValue A = VSel.getOperand(1);
7031   SDValue B = VSel.getOperand(2);
7032   SDValue CastA, CastB;
7033   SDLoc DL(Cast);
7034   if (CastOpcode == ISD::FP_ROUND) {
7035     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7036     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7037     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7038   } else {
7039     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7040     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7041   }
7042   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7043 }
7044
7045 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7046   SDValue N0 = N->getOperand(0);
7047   EVT VT = N->getValueType(0);
7048   SDLoc DL(N);
7049
7050   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7051                                               LegalOperations))
7052     return SDValue(Res, 0);
7053
7054   // fold (sext (sext x)) -> (sext x)
7055   // fold (sext (aext x)) -> (sext x)
7056   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7057     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7058
7059   if (N0.getOpcode() == ISD::TRUNCATE) {
7060     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7061     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7062     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7063       SDNode *oye = N0.getOperand(0).getNode();
7064       if (NarrowLoad.getNode() != N0.getNode()) {
7065         CombineTo(N0.getNode(), NarrowLoad);
7066         // CombineTo deleted the truncate, if needed, but not what's under it.
7067         AddToWorklist(oye);
7068       }
7069       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7070     }
7071
7072     // See if the value being truncated is already sign extended.  If so, just
7073     // eliminate the trunc/sext pair.
7074     SDValue Op = N0.getOperand(0);
7075     unsigned OpBits   = Op.getScalarValueSizeInBits();
7076     unsigned MidBits  = N0.getScalarValueSizeInBits();
7077     unsigned DestBits = VT.getScalarSizeInBits();
7078     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7079
7080     if (OpBits == DestBits) {
7081       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7082       // bits, it is already ready.
7083       if (NumSignBits > DestBits-MidBits)
7084         return Op;
7085     } else if (OpBits < DestBits) {
7086       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7087       // bits, just sext from i32.
7088       if (NumSignBits > OpBits-MidBits)
7089         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7090     } else {
7091       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7092       // bits, just truncate to i32.
7093       if (NumSignBits > OpBits-MidBits)
7094         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7095     }
7096
7097     // fold (sext (truncate x)) -> (sextinreg x).
7098     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7099                                                  N0.getValueType())) {
7100       if (OpBits < DestBits)
7101         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7102       else if (OpBits > DestBits)
7103         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7104       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7105                          DAG.getValueType(N0.getValueType()));
7106     }
7107   }
7108
7109   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7110   // Only generate vector extloads when 1) they're legal, and 2) they are
7111   // deemed desirable by the target.
7112   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7113       ((!LegalOperations && !VT.isVector() &&
7114         !cast<LoadSDNode>(N0)->isVolatile()) ||
7115        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7116     bool DoXform = true;
7117     SmallVector<SDNode*, 4> SetCCs;
7118     if (!N0.hasOneUse())
7119       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7120     if (VT.isVector())
7121       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7122     if (DoXform) {
7123       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7124       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7125                                        LN0->getBasePtr(), N0.getValueType(),
7126                                        LN0->getMemOperand());
7127       CombineTo(N, ExtLoad);
7128       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7129                                   N0.getValueType(), ExtLoad);
7130       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7131       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7132       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7133     }
7134   }
7135
7136   // fold (sext (load x)) to multiple smaller sextloads.
7137   // Only on illegal but splittable vectors.
7138   if (SDValue ExtLoad = CombineExtLoad(N))
7139     return ExtLoad;
7140
7141   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7142   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7143   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7144       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7145     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7146     EVT MemVT = LN0->getMemoryVT();
7147     if ((!LegalOperations && !LN0->isVolatile()) ||
7148         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7149       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7150                                        LN0->getBasePtr(), MemVT,
7151                                        LN0->getMemOperand());
7152       CombineTo(N, ExtLoad);
7153       CombineTo(N0.getNode(),
7154                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7155                             N0.getValueType(), ExtLoad),
7156                 ExtLoad.getValue(1));
7157       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7158     }
7159   }
7160
7161   // fold (sext (and/or/xor (load x), cst)) ->
7162   //      (and/or/xor (sextload x), (sext cst))
7163   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7164        N0.getOpcode() == ISD::XOR) &&
7165       isa<LoadSDNode>(N0.getOperand(0)) &&
7166       N0.getOperand(1).getOpcode() == ISD::Constant &&
7167       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7168       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7169     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7170     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7171       bool DoXform = true;
7172       SmallVector<SDNode*, 4> SetCCs;
7173       if (!N0.hasOneUse())
7174         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7175                                           SetCCs, TLI);
7176       if (DoXform) {
7177         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7178                                          LN0->getChain(), LN0->getBasePtr(),
7179                                          LN0->getMemoryVT(),
7180                                          LN0->getMemOperand());
7181         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7182         Mask = Mask.sext(VT.getSizeInBits());
7183         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7184                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7185         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7186                                     SDLoc(N0.getOperand(0)),
7187                                     N0.getOperand(0).getValueType(), ExtLoad);
7188         CombineTo(N, And);
7189         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7190         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7191         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7192       }
7193     }
7194   }
7195
7196   if (N0.getOpcode() == ISD::SETCC) {
7197     SDValue N00 = N0.getOperand(0);
7198     SDValue N01 = N0.getOperand(1);
7199     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7200     EVT N00VT = N0.getOperand(0).getValueType();
7201
7202     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7203     // Only do this before legalize for now.
7204     if (VT.isVector() && !LegalOperations &&
7205         TLI.getBooleanContents(N00VT) ==
7206             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7207       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7208       // of the same size as the compared operands. Only optimize sext(setcc())
7209       // if this is the case.
7210       EVT SVT = getSetCCResultType(N00VT);
7211
7212       // We know that the # elements of the results is the same as the
7213       // # elements of the compare (and the # elements of the compare result
7214       // for that matter).  Check to see that they are the same size.  If so,
7215       // we know that the element size of the sext'd result matches the
7216       // element size of the compare operands.
7217       if (VT.getSizeInBits() == SVT.getSizeInBits())
7218         return DAG.getSetCC(DL, VT, N00, N01, CC);
7219
7220       // If the desired elements are smaller or larger than the source
7221       // elements, we can use a matching integer vector type and then
7222       // truncate/sign extend.
7223       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7224       if (SVT == MatchingVecType) {
7225         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7226         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7227       }
7228     }
7229
7230     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7231     // Here, T can be 1 or -1, depending on the type of the setcc and
7232     // getBooleanContents().
7233     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7234
7235     // To determine the "true" side of the select, we need to know the high bit
7236     // of the value returned by the setcc if it evaluates to true.
7237     // If the type of the setcc is i1, then the true case of the select is just
7238     // sext(i1 1), that is, -1.
7239     // If the type of the setcc is larger (say, i8) then the value of the high
7240     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7241     // of the appropriate width.
7242     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7243                                            : TLI.getConstTrueVal(DAG, VT, DL);
7244     SDValue Zero = DAG.getConstant(0, DL, VT);
7245     if (SDValue SCC =
7246             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7247       return SCC;
7248
7249     if (!VT.isVector()) {
7250       EVT SetCCVT = getSetCCResultType(N00VT);
7251       // Don't do this transform for i1 because there's a select transform
7252       // that would reverse it.
7253       // TODO: We should not do this transform at all without a target hook
7254       // because a sext is likely cheaper than a select?
7255       if (SetCCVT.getScalarSizeInBits() != 1 &&
7256           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7257         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7258         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7259       }
7260     }
7261   }
7262
7263   // fold (sext x) -> (zext x) if the sign bit is known zero.
7264   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7265       DAG.SignBitIsZero(N0))
7266     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7267
7268   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7269     return NewVSel;
7270
7271   return SDValue();
7272 }
7273
7274 // isTruncateOf - If N is a truncate of some other value, return true, record
7275 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7276 // This function computes KnownBits to avoid a duplicated call to
7277 // computeKnownBits in the caller.
7278 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7279                          KnownBits &Known) {
7280   if (N->getOpcode() == ISD::TRUNCATE) {
7281     Op = N->getOperand(0);
7282     DAG.computeKnownBits(Op, Known);
7283     return true;
7284   }
7285
7286   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7287       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7288     return false;
7289
7290   SDValue Op0 = N->getOperand(0);
7291   SDValue Op1 = N->getOperand(1);
7292   assert(Op0.getValueType() == Op1.getValueType());
7293
7294   if (isNullConstant(Op0))
7295     Op = Op1;
7296   else if (isNullConstant(Op1))
7297     Op = Op0;
7298   else
7299     return false;
7300
7301   DAG.computeKnownBits(Op, Known);
7302
7303   if (!(Known.Zero | 1).isAllOnesValue())
7304     return false;
7305
7306   return true;
7307 }
7308
7309 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7310   SDValue N0 = N->getOperand(0);
7311   EVT VT = N->getValueType(0);
7312
7313   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7314                                               LegalOperations))
7315     return SDValue(Res, 0);
7316
7317   // fold (zext (zext x)) -> (zext x)
7318   // fold (zext (aext x)) -> (zext x)
7319   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7320     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7321                        N0.getOperand(0));
7322
7323   // fold (zext (truncate x)) -> (zext x) or
7324   //      (zext (truncate x)) -> (truncate x)
7325   // This is valid when the truncated bits of x are already zero.
7326   // FIXME: We should extend this to work for vectors too.
7327   SDValue Op;
7328   KnownBits Known;
7329   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7330     APInt TruncatedBits =
7331       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7332       APInt(Op.getValueSizeInBits(), 0) :
7333       APInt::getBitsSet(Op.getValueSizeInBits(),
7334                         N0.getValueSizeInBits(),
7335                         std::min(Op.getValueSizeInBits(),
7336                                  VT.getSizeInBits()));
7337     if (TruncatedBits.isSubsetOf(Known.Zero))
7338       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7339   }
7340
7341   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7342   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7343   if (N0.getOpcode() == ISD::TRUNCATE) {
7344     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7345       SDNode *oye = N0.getOperand(0).getNode();
7346       if (NarrowLoad.getNode() != N0.getNode()) {
7347         CombineTo(N0.getNode(), NarrowLoad);
7348         // CombineTo deleted the truncate, if needed, but not what's under it.
7349         AddToWorklist(oye);
7350       }
7351       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7352     }
7353   }
7354
7355   // fold (zext (truncate x)) -> (and x, mask)
7356   if (N0.getOpcode() == ISD::TRUNCATE) {
7357     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7358     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7359     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7360       SDNode *oye = N0.getOperand(0).getNode();
7361       if (NarrowLoad.getNode() != N0.getNode()) {
7362         CombineTo(N0.getNode(), NarrowLoad);
7363         // CombineTo deleted the truncate, if needed, but not what's under it.
7364         AddToWorklist(oye);
7365       }
7366       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7367     }
7368
7369     EVT SrcVT = N0.getOperand(0).getValueType();
7370     EVT MinVT = N0.getValueType();
7371
7372     // Try to mask before the extension to avoid having to generate a larger mask,
7373     // possibly over several sub-vectors.
7374     if (SrcVT.bitsLT(VT)) {
7375       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7376                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7377         SDValue Op = N0.getOperand(0);
7378         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7379         AddToWorklist(Op.getNode());
7380         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7381       }
7382     }
7383
7384     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7385       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7386       AddToWorklist(Op.getNode());
7387       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7388     }
7389   }
7390
7391   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7392   // if either of the casts is not free.
7393   if (N0.getOpcode() == ISD::AND &&
7394       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7395       N0.getOperand(1).getOpcode() == ISD::Constant &&
7396       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7397                            N0.getValueType()) ||
7398        !TLI.isZExtFree(N0.getValueType(), VT))) {
7399     SDValue X = N0.getOperand(0).getOperand(0);
7400     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7401     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7402     Mask = Mask.zext(VT.getSizeInBits());
7403     SDLoc DL(N);
7404     return DAG.getNode(ISD::AND, DL, VT,
7405                        X, DAG.getConstant(Mask, DL, VT));
7406   }
7407
7408   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7409   // Only generate vector extloads when 1) they're legal, and 2) they are
7410   // deemed desirable by the target.
7411   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7412       ((!LegalOperations && !VT.isVector() &&
7413         !cast<LoadSDNode>(N0)->isVolatile()) ||
7414        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7415     bool DoXform = true;
7416     SmallVector<SDNode*, 4> SetCCs;
7417     if (!N0.hasOneUse())
7418       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7419     if (VT.isVector())
7420       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7421     if (DoXform) {
7422       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7423       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7424                                        LN0->getChain(),
7425                                        LN0->getBasePtr(), N0.getValueType(),
7426                                        LN0->getMemOperand());
7427
7428       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7429                                   N0.getValueType(), ExtLoad);
7430       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7431
7432       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7433                       ISD::ZERO_EXTEND);
7434       CombineTo(N, ExtLoad);
7435       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7436     }
7437   }
7438
7439   // fold (zext (load x)) to multiple smaller zextloads.
7440   // Only on illegal but splittable vectors.
7441   if (SDValue ExtLoad = CombineExtLoad(N))
7442     return ExtLoad;
7443
7444   // fold (zext (and/or/xor (load x), cst)) ->
7445   //      (and/or/xor (zextload x), (zext cst))
7446   // Unless (and (load x) cst) will match as a zextload already and has
7447   // additional users.
7448   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7449        N0.getOpcode() == ISD::XOR) &&
7450       isa<LoadSDNode>(N0.getOperand(0)) &&
7451       N0.getOperand(1).getOpcode() == ISD::Constant &&
7452       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7453       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7454     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7455     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7456       bool DoXform = true;
7457       SmallVector<SDNode*, 4> SetCCs;
7458       if (!N0.hasOneUse()) {
7459         if (N0.getOpcode() == ISD::AND) {
7460           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7461           auto NarrowLoad = false;
7462           EVT LoadResultTy = AndC->getValueType(0);
7463           EVT ExtVT, LoadedVT;
7464           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7465                                NarrowLoad))
7466             DoXform = false;
7467         }
7468         if (DoXform)
7469           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7470                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7471       }
7472       if (DoXform) {
7473         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7474                                          LN0->getChain(), LN0->getBasePtr(),
7475                                          LN0->getMemoryVT(),
7476                                          LN0->getMemOperand());
7477         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7478         Mask = Mask.zext(VT.getSizeInBits());
7479         SDLoc DL(N);
7480         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7481                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7482         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7483                                     SDLoc(N0.getOperand(0)),
7484                                     N0.getOperand(0).getValueType(), ExtLoad);
7485         CombineTo(N, And);
7486         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7487         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7488                         ISD::ZERO_EXTEND);
7489         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7490       }
7491     }
7492   }
7493
7494   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7495   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7496   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7497       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7498     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7499     EVT MemVT = LN0->getMemoryVT();
7500     if ((!LegalOperations && !LN0->isVolatile()) ||
7501         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7502       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7503                                        LN0->getChain(),
7504                                        LN0->getBasePtr(), MemVT,
7505                                        LN0->getMemOperand());
7506       CombineTo(N, ExtLoad);
7507       CombineTo(N0.getNode(),
7508                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7509                             ExtLoad),
7510                 ExtLoad.getValue(1));
7511       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7512     }
7513   }
7514
7515   if (N0.getOpcode() == ISD::SETCC) {
7516     // Only do this before legalize for now.
7517     if (!LegalOperations && VT.isVector() &&
7518         N0.getValueType().getVectorElementType() == MVT::i1) {
7519       EVT N00VT = N0.getOperand(0).getValueType();
7520       if (getSetCCResultType(N00VT) == N0.getValueType())
7521         return SDValue();
7522
7523       // We know that the # elements of the results is the same as the #
7524       // elements of the compare (and the # elements of the compare result for
7525       // that matter). Check to see that they are the same size. If so, we know
7526       // that the element size of the sext'd result matches the element size of
7527       // the compare operands.
7528       SDLoc DL(N);
7529       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7530       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7531         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7532         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7533                                      N0.getOperand(1), N0.getOperand(2));
7534         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7535       }
7536
7537       // If the desired elements are smaller or larger than the source
7538       // elements we can use a matching integer vector type and then
7539       // truncate/sign extend.
7540       EVT MatchingElementType = EVT::getIntegerVT(
7541           *DAG.getContext(), N00VT.getScalarSizeInBits());
7542       EVT MatchingVectorType = EVT::getVectorVT(
7543           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7544       SDValue VsetCC =
7545           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7546                       N0.getOperand(1), N0.getOperand(2));
7547       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7548                          VecOnes);
7549     }
7550
7551     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7552     SDLoc DL(N);
7553     if (SDValue SCC = SimplifySelectCC(
7554             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7555             DAG.getConstant(0, DL, VT),
7556             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7557       return SCC;
7558   }
7559
7560   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7561   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7562       isa<ConstantSDNode>(N0.getOperand(1)) &&
7563       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7564       N0.hasOneUse()) {
7565     SDValue ShAmt = N0.getOperand(1);
7566     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7567     if (N0.getOpcode() == ISD::SHL) {
7568       SDValue InnerZExt = N0.getOperand(0);
7569       // If the original shl may be shifting out bits, do not perform this
7570       // transformation.
7571       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7572         InnerZExt.getOperand(0).getValueSizeInBits();
7573       if (ShAmtVal > KnownZeroBits)
7574         return SDValue();
7575     }
7576
7577     SDLoc DL(N);
7578
7579     // Ensure that the shift amount is wide enough for the shifted value.
7580     if (VT.getSizeInBits() >= 256)
7581       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7582
7583     return DAG.getNode(N0.getOpcode(), DL, VT,
7584                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7585                        ShAmt);
7586   }
7587
7588   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7589     return NewVSel;
7590
7591   return SDValue();
7592 }
7593
7594 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7595   SDValue N0 = N->getOperand(0);
7596   EVT VT = N->getValueType(0);
7597
7598   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7599                                               LegalOperations))
7600     return SDValue(Res, 0);
7601
7602   // fold (aext (aext x)) -> (aext x)
7603   // fold (aext (zext x)) -> (zext x)
7604   // fold (aext (sext x)) -> (sext x)
7605   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7606       N0.getOpcode() == ISD::ZERO_EXTEND ||
7607       N0.getOpcode() == ISD::SIGN_EXTEND)
7608     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7609
7610   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7611   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7612   if (N0.getOpcode() == ISD::TRUNCATE) {
7613     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7614       SDNode *oye = N0.getOperand(0).getNode();
7615       if (NarrowLoad.getNode() != N0.getNode()) {
7616         CombineTo(N0.getNode(), NarrowLoad);
7617         // CombineTo deleted the truncate, if needed, but not what's under it.
7618         AddToWorklist(oye);
7619       }
7620       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7621     }
7622   }
7623
7624   // fold (aext (truncate x))
7625   if (N0.getOpcode() == ISD::TRUNCATE)
7626     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7627
7628   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7629   // if the trunc is not free.
7630   if (N0.getOpcode() == ISD::AND &&
7631       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7632       N0.getOperand(1).getOpcode() == ISD::Constant &&
7633       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7634                           N0.getValueType())) {
7635     SDLoc DL(N);
7636     SDValue X = N0.getOperand(0).getOperand(0);
7637     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7638     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7639     Mask = Mask.zext(VT.getSizeInBits());
7640     return DAG.getNode(ISD::AND, DL, VT,
7641                        X, DAG.getConstant(Mask, DL, VT));
7642   }
7643
7644   // fold (aext (load x)) -> (aext (truncate (extload x)))
7645   // None of the supported targets knows how to perform load and any_ext
7646   // on vectors in one instruction.  We only perform this transformation on
7647   // scalars.
7648   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7649       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7650       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7651     bool DoXform = true;
7652     SmallVector<SDNode*, 4> SetCCs;
7653     if (!N0.hasOneUse())
7654       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7655     if (DoXform) {
7656       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7657       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7658                                        LN0->getChain(),
7659                                        LN0->getBasePtr(), N0.getValueType(),
7660                                        LN0->getMemOperand());
7661       CombineTo(N, ExtLoad);
7662       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7663                                   N0.getValueType(), ExtLoad);
7664       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7665       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7666                       ISD::ANY_EXTEND);
7667       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7668     }
7669   }
7670
7671   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7672   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7673   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7674   if (N0.getOpcode() == ISD::LOAD &&
7675       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7676       N0.hasOneUse()) {
7677     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7678     ISD::LoadExtType ExtType = LN0->getExtensionType();
7679     EVT MemVT = LN0->getMemoryVT();
7680     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7681       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7682                                        VT, LN0->getChain(), LN0->getBasePtr(),
7683                                        MemVT, LN0->getMemOperand());
7684       CombineTo(N, ExtLoad);
7685       CombineTo(N0.getNode(),
7686                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7687                             N0.getValueType(), ExtLoad),
7688                 ExtLoad.getValue(1));
7689       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7690     }
7691   }
7692
7693   if (N0.getOpcode() == ISD::SETCC) {
7694     // For vectors:
7695     // aext(setcc) -> vsetcc
7696     // aext(setcc) -> truncate(vsetcc)
7697     // aext(setcc) -> aext(vsetcc)
7698     // Only do this before legalize for now.
7699     if (VT.isVector() && !LegalOperations) {
7700       EVT N0VT = N0.getOperand(0).getValueType();
7701         // We know that the # elements of the results is the same as the
7702         // # elements of the compare (and the # elements of the compare result
7703         // for that matter).  Check to see that they are the same size.  If so,
7704         // we know that the element size of the sext'd result matches the
7705         // element size of the compare operands.
7706       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7707         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7708                              N0.getOperand(1),
7709                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7710       // If the desired elements are smaller or larger than the source
7711       // elements we can use a matching integer vector type and then
7712       // truncate/any extend
7713       else {
7714         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7715         SDValue VsetCC =
7716           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7717                         N0.getOperand(1),
7718                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7719         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7720       }
7721     }
7722
7723     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7724     SDLoc DL(N);
7725     if (SDValue SCC = SimplifySelectCC(
7726             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7727             DAG.getConstant(0, DL, VT),
7728             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7729       return SCC;
7730   }
7731
7732   return SDValue();
7733 }
7734
7735 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7736   SDValue N0 = N->getOperand(0);
7737   SDValue N1 = N->getOperand(1);
7738   EVT EVT = cast<VTSDNode>(N1)->getVT();
7739
7740   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7741   if (N0.getOpcode() == ISD::AssertZext &&
7742       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7743     return N0;
7744
7745   return SDValue();
7746 }
7747
7748 /// See if the specified operand can be simplified with the knowledge that only
7749 /// the bits specified by Mask are used.  If so, return the simpler operand,
7750 /// otherwise return a null SDValue.
7751 ///
7752 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7753 /// simplify nodes with multiple uses more aggressively.)
7754 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7755   switch (V.getOpcode()) {
7756   default: break;
7757   case ISD::Constant: {
7758     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7759     assert(CV && "Const value should be ConstSDNode.");
7760     const APInt &CVal = CV->getAPIntValue();
7761     APInt NewVal = CVal & Mask;
7762     if (NewVal != CVal)
7763       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7764     break;
7765   }
7766   case ISD::OR:
7767   case ISD::XOR:
7768     // If the LHS or RHS don't contribute bits to the or, drop them.
7769     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7770       return V.getOperand(1);
7771     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7772       return V.getOperand(0);
7773     break;
7774   case ISD::SRL:
7775     // Only look at single-use SRLs.
7776     if (!V.getNode()->hasOneUse())
7777       break;
7778     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7779       // See if we can recursively simplify the LHS.
7780       unsigned Amt = RHSC->getZExtValue();
7781
7782       // Watch out for shift count overflow though.
7783       if (Amt >= Mask.getBitWidth()) break;
7784       APInt NewMask = Mask << Amt;
7785       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7786         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7787                            SimplifyLHS, V.getOperand(1));
7788     }
7789     break;
7790   case ISD::AND: {
7791     // X & -1 -> X (ignoring bits which aren't demanded).
7792     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7793     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7794       return V.getOperand(0);
7795     break;
7796   }
7797   }
7798   return SDValue();
7799 }
7800
7801 /// If the result of a wider load is shifted to right of N  bits and then
7802 /// truncated to a narrower type and where N is a multiple of number of bits of
7803 /// the narrower type, transform it to a narrower load from address + N / num of
7804 /// bits of new type. If the result is to be extended, also fold the extension
7805 /// to form a extending load.
7806 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7807   unsigned Opc = N->getOpcode();
7808
7809   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7810   SDValue N0 = N->getOperand(0);
7811   EVT VT = N->getValueType(0);
7812   EVT ExtVT = VT;
7813
7814   // This transformation isn't valid for vector loads.
7815   if (VT.isVector())
7816     return SDValue();
7817
7818   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7819   // extended to VT.
7820   if (Opc == ISD::SIGN_EXTEND_INREG) {
7821     ExtType = ISD::SEXTLOAD;
7822     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7823   } else if (Opc == ISD::SRL) {
7824     // Another special-case: SRL is basically zero-extending a narrower value.
7825     ExtType = ISD::ZEXTLOAD;
7826     N0 = SDValue(N, 0);
7827     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7828     if (!N01) return SDValue();
7829     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7830                               VT.getSizeInBits() - N01->getZExtValue());
7831   }
7832   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7833     return SDValue();
7834
7835   unsigned EVTBits = ExtVT.getSizeInBits();
7836
7837   // Do not generate loads of non-round integer types since these can
7838   // be expensive (and would be wrong if the type is not byte sized).
7839   if (!ExtVT.isRound())
7840     return SDValue();
7841
7842   unsigned ShAmt = 0;
7843   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7844     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7845       ShAmt = N01->getZExtValue();
7846       // Is the shift amount a multiple of size of VT?
7847       if ((ShAmt & (EVTBits-1)) == 0) {
7848         N0 = N0.getOperand(0);
7849         // Is the load width a multiple of size of VT?
7850         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7851           return SDValue();
7852       }
7853
7854       // At this point, we must have a load or else we can't do the transform.
7855       if (!isa<LoadSDNode>(N0)) return SDValue();
7856
7857       // Because a SRL must be assumed to *need* to zero-extend the high bits
7858       // (as opposed to anyext the high bits), we can't combine the zextload
7859       // lowering of SRL and an sextload.
7860       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7861         return SDValue();
7862
7863       // If the shift amount is larger than the input type then we're not
7864       // accessing any of the loaded bytes.  If the load was a zextload/extload
7865       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7866       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7867         return SDValue();
7868     }
7869   }
7870
7871   // If the load is shifted left (and the result isn't shifted back right),
7872   // we can fold the truncate through the shift.
7873   unsigned ShLeftAmt = 0;
7874   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7875       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7876     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7877       ShLeftAmt = N01->getZExtValue();
7878       N0 = N0.getOperand(0);
7879     }
7880   }
7881
7882   // If we haven't found a load, we can't narrow it.  Don't transform one with
7883   // multiple uses, this would require adding a new load.
7884   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7885     return SDValue();
7886
7887   // Don't change the width of a volatile load.
7888   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7889   if (LN0->isVolatile())
7890     return SDValue();
7891
7892   // Verify that we are actually reducing a load width here.
7893   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7894     return SDValue();
7895
7896   // For the transform to be legal, the load must produce only two values
7897   // (the value loaded and the chain).  Don't transform a pre-increment
7898   // load, for example, which produces an extra value.  Otherwise the
7899   // transformation is not equivalent, and the downstream logic to replace
7900   // uses gets things wrong.
7901   if (LN0->getNumValues() > 2)
7902     return SDValue();
7903
7904   // If the load that we're shrinking is an extload and we're not just
7905   // discarding the extension we can't simply shrink the load. Bail.
7906   // TODO: It would be possible to merge the extensions in some cases.
7907   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7908       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7909     return SDValue();
7910
7911   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7912     return SDValue();
7913
7914   EVT PtrType = N0.getOperand(1).getValueType();
7915
7916   if (PtrType == MVT::Untyped || PtrType.isExtended())
7917     // It's not possible to generate a constant of extended or untyped type.
7918     return SDValue();
7919
7920   // For big endian targets, we need to adjust the offset to the pointer to
7921   // load the correct bytes.
7922   if (DAG.getDataLayout().isBigEndian()) {
7923     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7924     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7925     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7926   }
7927
7928   uint64_t PtrOff = ShAmt / 8;
7929   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7930   SDLoc DL(LN0);
7931   // The original load itself didn't wrap, so an offset within it doesn't.
7932   SDNodeFlags Flags;
7933   Flags.setNoUnsignedWrap(true);
7934   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7935                                PtrType, LN0->getBasePtr(),
7936                                DAG.getConstant(PtrOff, DL, PtrType),
7937                                Flags);
7938   AddToWorklist(NewPtr.getNode());
7939
7940   SDValue Load;
7941   if (ExtType == ISD::NON_EXTLOAD)
7942     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7943                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7944                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7945   else
7946     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7947                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7948                           NewAlign, LN0->getMemOperand()->getFlags(),
7949                           LN0->getAAInfo());
7950
7951   // Replace the old load's chain with the new load's chain.
7952   WorklistRemover DeadNodes(*this);
7953   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7954
7955   // Shift the result left, if we've swallowed a left shift.
7956   SDValue Result = Load;
7957   if (ShLeftAmt != 0) {
7958     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7959     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7960       ShImmTy = VT;
7961     // If the shift amount is as large as the result size (but, presumably,
7962     // no larger than the source) then the useful bits of the result are
7963     // zero; we can't simply return the shortened shift, because the result
7964     // of that operation is undefined.
7965     SDLoc DL(N0);
7966     if (ShLeftAmt >= VT.getSizeInBits())
7967       Result = DAG.getConstant(0, DL, VT);
7968     else
7969       Result = DAG.getNode(ISD::SHL, DL, VT,
7970                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7971   }
7972
7973   // Return the new loaded value.
7974   return Result;
7975 }
7976
7977 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7978   SDValue N0 = N->getOperand(0);
7979   SDValue N1 = N->getOperand(1);
7980   EVT VT = N->getValueType(0);
7981   EVT EVT = cast<VTSDNode>(N1)->getVT();
7982   unsigned VTBits = VT.getScalarSizeInBits();
7983   unsigned EVTBits = EVT.getScalarSizeInBits();
7984
7985   if (N0.isUndef())
7986     return DAG.getUNDEF(VT);
7987
7988   // fold (sext_in_reg c1) -> c1
7989   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7990     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7991
7992   // If the input is already sign extended, just drop the extension.
7993   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7994     return N0;
7995
7996   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7997   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7998       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7999     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8000                        N0.getOperand(0), N1);
8001
8002   // fold (sext_in_reg (sext x)) -> (sext x)
8003   // fold (sext_in_reg (aext x)) -> (sext x)
8004   // if x is small enough.
8005   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8006     SDValue N00 = N0.getOperand(0);
8007     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8008         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8009       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8010   }
8011
8012   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8013   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8014        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8015        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8016       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8017     if (!LegalOperations ||
8018         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8019       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8020   }
8021
8022   // fold (sext_in_reg (zext x)) -> (sext x)
8023   // iff we are extending the source sign bit.
8024   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8025     SDValue N00 = N0.getOperand(0);
8026     if (N00.getScalarValueSizeInBits() == EVTBits &&
8027         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8028       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8029   }
8030
8031   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8032   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8033     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8034
8035   // fold operands of sext_in_reg based on knowledge that the top bits are not
8036   // demanded.
8037   if (SimplifyDemandedBits(SDValue(N, 0)))
8038     return SDValue(N, 0);
8039
8040   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8041   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8042   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8043     return NarrowLoad;
8044
8045   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8046   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8047   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8048   if (N0.getOpcode() == ISD::SRL) {
8049     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8050       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8051         // We can turn this into an SRA iff the input to the SRL is already sign
8052         // extended enough.
8053         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8054         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8055           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8056                              N0.getOperand(0), N0.getOperand(1));
8057       }
8058   }
8059
8060   // fold (sext_inreg (extload x)) -> (sextload x)
8061   if (ISD::isEXTLoad(N0.getNode()) &&
8062       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8063       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8064       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8065        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8066     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8067     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8068                                      LN0->getChain(),
8069                                      LN0->getBasePtr(), EVT,
8070                                      LN0->getMemOperand());
8071     CombineTo(N, ExtLoad);
8072     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8073     AddToWorklist(ExtLoad.getNode());
8074     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8075   }
8076   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8077   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8078       N0.hasOneUse() &&
8079       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8080       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8081        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8082     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8083     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8084                                      LN0->getChain(),
8085                                      LN0->getBasePtr(), EVT,
8086                                      LN0->getMemOperand());
8087     CombineTo(N, ExtLoad);
8088     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8089     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8090   }
8091
8092   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8093   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8094     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8095                                            N0.getOperand(1), false))
8096       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8097                          BSwap, N1);
8098   }
8099
8100   return SDValue();
8101 }
8102
8103 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8104   SDValue N0 = N->getOperand(0);
8105   EVT VT = N->getValueType(0);
8106
8107   if (N0.isUndef())
8108     return DAG.getUNDEF(VT);
8109
8110   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8111                                               LegalOperations))
8112     return SDValue(Res, 0);
8113
8114   return SDValue();
8115 }
8116
8117 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8118   SDValue N0 = N->getOperand(0);
8119   EVT VT = N->getValueType(0);
8120
8121   if (N0.isUndef())
8122     return DAG.getUNDEF(VT);
8123
8124   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8125                                               LegalOperations))
8126     return SDValue(Res, 0);
8127
8128   return SDValue();
8129 }
8130
8131 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8132   SDValue N0 = N->getOperand(0);
8133   EVT VT = N->getValueType(0);
8134   bool isLE = DAG.getDataLayout().isLittleEndian();
8135
8136   // noop truncate
8137   if (N0.getValueType() == N->getValueType(0))
8138     return N0;
8139   // fold (truncate c1) -> c1
8140   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8141     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8142   // fold (truncate (truncate x)) -> (truncate x)
8143   if (N0.getOpcode() == ISD::TRUNCATE)
8144     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8145   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8146   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8147       N0.getOpcode() == ISD::SIGN_EXTEND ||
8148       N0.getOpcode() == ISD::ANY_EXTEND) {
8149     // if the source is smaller than the dest, we still need an extend.
8150     if (N0.getOperand(0).getValueType().bitsLT(VT))
8151       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8152     // if the source is larger than the dest, than we just need the truncate.
8153     if (N0.getOperand(0).getValueType().bitsGT(VT))
8154       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8155     // if the source and dest are the same type, we can drop both the extend
8156     // and the truncate.
8157     return N0.getOperand(0);
8158   }
8159
8160   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8161   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8162     return SDValue();
8163
8164   // Fold extract-and-trunc into a narrow extract. For example:
8165   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8166   //   i32 y = TRUNCATE(i64 x)
8167   //        -- becomes --
8168   //   v16i8 b = BITCAST (v2i64 val)
8169   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8170   //
8171   // Note: We only run this optimization after type legalization (which often
8172   // creates this pattern) and before operation legalization after which
8173   // we need to be more careful about the vector instructions that we generate.
8174   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8175       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8176
8177     EVT VecTy = N0.getOperand(0).getValueType();
8178     EVT ExTy = N0.getValueType();
8179     EVT TrTy = N->getValueType(0);
8180
8181     unsigned NumElem = VecTy.getVectorNumElements();
8182     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8183
8184     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8185     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8186
8187     SDValue EltNo = N0->getOperand(1);
8188     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8189       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8190       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8191       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8192
8193       SDLoc DL(N);
8194       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8195                          DAG.getBitcast(NVT, N0.getOperand(0)),
8196                          DAG.getConstant(Index, DL, IndexTy));
8197     }
8198   }
8199
8200   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8201   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8202     EVT SrcVT = N0.getValueType();
8203     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8204         TLI.isTruncateFree(SrcVT, VT)) {
8205       SDLoc SL(N0);
8206       SDValue Cond = N0.getOperand(0);
8207       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8208       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8209       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8210     }
8211   }
8212
8213   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8214   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8215       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8216       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8217     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8218       uint64_t Amt = CAmt->getZExtValue();
8219       unsigned Size = VT.getScalarSizeInBits();
8220
8221       if (Amt < Size) {
8222         SDLoc SL(N);
8223         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8224
8225         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8226         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8227                            DAG.getConstant(Amt, SL, AmtVT));
8228       }
8229     }
8230   }
8231
8232   // Fold a series of buildvector, bitcast, and truncate if possible.
8233   // For example fold
8234   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8235   //   (2xi32 (buildvector x, y)).
8236   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8237       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8238       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8239       N0.getOperand(0).hasOneUse()) {
8240
8241     SDValue BuildVect = N0.getOperand(0);
8242     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8243     EVT TruncVecEltTy = VT.getVectorElementType();
8244
8245     // Check that the element types match.
8246     if (BuildVectEltTy == TruncVecEltTy) {
8247       // Now we only need to compute the offset of the truncated elements.
8248       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8249       unsigned TruncVecNumElts = VT.getVectorNumElements();
8250       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8251
8252       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8253              "Invalid number of elements");
8254
8255       SmallVector<SDValue, 8> Opnds;
8256       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8257         Opnds.push_back(BuildVect.getOperand(i));
8258
8259       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8260     }
8261   }
8262
8263   // See if we can simplify the input to this truncate through knowledge that
8264   // only the low bits are being used.
8265   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8266   // Currently we only perform this optimization on scalars because vectors
8267   // may have different active low bits.
8268   if (!VT.isVector()) {
8269     if (SDValue Shorter =
8270             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8271                                                      VT.getSizeInBits())))
8272       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8273   }
8274
8275   // fold (truncate (load x)) -> (smaller load x)
8276   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8277   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8278     if (SDValue Reduced = ReduceLoadWidth(N))
8279       return Reduced;
8280
8281     // Handle the case where the load remains an extending load even
8282     // after truncation.
8283     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8284       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8285       if (!LN0->isVolatile() &&
8286           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8287         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8288                                          VT, LN0->getChain(), LN0->getBasePtr(),
8289                                          LN0->getMemoryVT(),
8290                                          LN0->getMemOperand());
8291         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8292         return NewLoad;
8293       }
8294     }
8295   }
8296
8297   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8298   // where ... are all 'undef'.
8299   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8300     SmallVector<EVT, 8> VTs;
8301     SDValue V;
8302     unsigned Idx = 0;
8303     unsigned NumDefs = 0;
8304
8305     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8306       SDValue X = N0.getOperand(i);
8307       if (!X.isUndef()) {
8308         V = X;
8309         Idx = i;
8310         NumDefs++;
8311       }
8312       // Stop if more than one members are non-undef.
8313       if (NumDefs > 1)
8314         break;
8315       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8316                                      VT.getVectorElementType(),
8317                                      X.getValueType().getVectorNumElements()));
8318     }
8319
8320     if (NumDefs == 0)
8321       return DAG.getUNDEF(VT);
8322
8323     if (NumDefs == 1) {
8324       assert(V.getNode() && "The single defined operand is empty!");
8325       SmallVector<SDValue, 8> Opnds;
8326       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8327         if (i != Idx) {
8328           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8329           continue;
8330         }
8331         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8332         AddToWorklist(NV.getNode());
8333         Opnds.push_back(NV);
8334       }
8335       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8336     }
8337   }
8338
8339   // Fold truncate of a bitcast of a vector to an extract of the low vector
8340   // element.
8341   //
8342   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8343   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8344     SDValue VecSrc = N0.getOperand(0);
8345     EVT SrcVT = VecSrc.getValueType();
8346     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8347         (!LegalOperations ||
8348          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8349       SDLoc SL(N);
8350
8351       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8352       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8353                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8354     }
8355   }
8356
8357   // Simplify the operands using demanded-bits information.
8358   if (!VT.isVector() &&
8359       SimplifyDemandedBits(SDValue(N, 0)))
8360     return SDValue(N, 0);
8361
8362   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8363   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8364   // When the adde's carry is not used.
8365   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8366       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8367       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8368     SDLoc SL(N);
8369     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8370     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8371     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8372     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8373   }
8374
8375   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8376     return NewVSel;
8377
8378   return SDValue();
8379 }
8380
8381 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8382   SDValue Elt = N->getOperand(i);
8383   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8384     return Elt.getNode();
8385   return Elt.getOperand(Elt.getResNo()).getNode();
8386 }
8387
8388 /// build_pair (load, load) -> load
8389 /// if load locations are consecutive.
8390 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8391   assert(N->getOpcode() == ISD::BUILD_PAIR);
8392
8393   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8394   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8395   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8396       LD1->getAddressSpace() != LD2->getAddressSpace())
8397     return SDValue();
8398   EVT LD1VT = LD1->getValueType(0);
8399   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8400   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8401       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8402     unsigned Align = LD1->getAlignment();
8403     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8404         VT.getTypeForEVT(*DAG.getContext()));
8405
8406     if (NewAlign <= Align &&
8407         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8408       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8409                          LD1->getPointerInfo(), Align);
8410   }
8411
8412   return SDValue();
8413 }
8414
8415 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8416   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8417   // and Lo parts; on big-endian machines it doesn't.
8418   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8419 }
8420
8421 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8422                                     const TargetLowering &TLI) {
8423   // If this is not a bitcast to an FP type or if the target doesn't have
8424   // IEEE754-compliant FP logic, we're done.
8425   EVT VT = N->getValueType(0);
8426   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8427     return SDValue();
8428
8429   // TODO: Use splat values for the constant-checking below and remove this
8430   // restriction.
8431   SDValue N0 = N->getOperand(0);
8432   EVT SourceVT = N0.getValueType();
8433   if (SourceVT.isVector())
8434     return SDValue();
8435
8436   unsigned FPOpcode;
8437   APInt SignMask;
8438   switch (N0.getOpcode()) {
8439   case ISD::AND:
8440     FPOpcode = ISD::FABS;
8441     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8442     break;
8443   case ISD::XOR:
8444     FPOpcode = ISD::FNEG;
8445     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8446     break;
8447   // TODO: ISD::OR --> ISD::FNABS?
8448   default:
8449     return SDValue();
8450   }
8451
8452   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8453   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8454   SDValue LogicOp0 = N0.getOperand(0);
8455   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8456   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8457       LogicOp0.getOpcode() == ISD::BITCAST &&
8458       LogicOp0->getOperand(0).getValueType() == VT)
8459     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8460
8461   return SDValue();
8462 }
8463
8464 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8465   SDValue N0 = N->getOperand(0);
8466   EVT VT = N->getValueType(0);
8467
8468   if (N0.isUndef())
8469     return DAG.getUNDEF(VT);
8470
8471   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8472   // Only do this before legalize, since afterward the target may be depending
8473   // on the bitconvert.
8474   // First check to see if this is all constant.
8475   if (!LegalTypes &&
8476       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8477       VT.isVector()) {
8478     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8479
8480     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8481     assert(!DestEltVT.isVector() &&
8482            "Element type of vector ValueType must not be vector!");
8483     if (isSimple)
8484       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8485   }
8486
8487   // If the input is a constant, let getNode fold it.
8488   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8489     // If we can't allow illegal operations, we need to check that this is just
8490     // a fp -> int or int -> conversion and that the resulting operation will
8491     // be legal.
8492     if (!LegalOperations ||
8493         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8494          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8495         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8496          TLI.isOperationLegal(ISD::Constant, VT)))
8497       return DAG.getBitcast(VT, N0);
8498   }
8499
8500   // (conv (conv x, t1), t2) -> (conv x, t2)
8501   if (N0.getOpcode() == ISD::BITCAST)
8502     return DAG.getBitcast(VT, N0.getOperand(0));
8503
8504   // fold (conv (load x)) -> (load (conv*)x)
8505   // If the resultant load doesn't need a higher alignment than the original!
8506   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8507       // Do not change the width of a volatile load.
8508       !cast<LoadSDNode>(N0)->isVolatile() &&
8509       // Do not remove the cast if the types differ in endian layout.
8510       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8511           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8512       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8513       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8514     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8515     unsigned OrigAlign = LN0->getAlignment();
8516
8517     bool Fast = false;
8518     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8519                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8520         Fast) {
8521       SDValue Load =
8522           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8523                       LN0->getPointerInfo(), OrigAlign,
8524                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8525       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8526       return Load;
8527     }
8528   }
8529
8530   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8531     return V;
8532
8533   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8534   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8535   //
8536   // For ppc_fp128:
8537   // fold (bitcast (fneg x)) ->
8538   //     flipbit = signbit
8539   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8540   //
8541   // fold (bitcast (fabs x)) ->
8542   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8543   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8544   // This often reduces constant pool loads.
8545   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8546        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8547       N0.getNode()->hasOneUse() && VT.isInteger() &&
8548       !VT.isVector() && !N0.getValueType().isVector()) {
8549     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8550     AddToWorklist(NewConv.getNode());
8551
8552     SDLoc DL(N);
8553     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8554       assert(VT.getSizeInBits() == 128);
8555       SDValue SignBit = DAG.getConstant(
8556           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8557       SDValue FlipBit;
8558       if (N0.getOpcode() == ISD::FNEG) {
8559         FlipBit = SignBit;
8560         AddToWorklist(FlipBit.getNode());
8561       } else {
8562         assert(N0.getOpcode() == ISD::FABS);
8563         SDValue Hi =
8564             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8565                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8566                                               SDLoc(NewConv)));
8567         AddToWorklist(Hi.getNode());
8568         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8569         AddToWorklist(FlipBit.getNode());
8570       }
8571       SDValue FlipBits =
8572           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8573       AddToWorklist(FlipBits.getNode());
8574       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8575     }
8576     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8577     if (N0.getOpcode() == ISD::FNEG)
8578       return DAG.getNode(ISD::XOR, DL, VT,
8579                          NewConv, DAG.getConstant(SignBit, DL, VT));
8580     assert(N0.getOpcode() == ISD::FABS);
8581     return DAG.getNode(ISD::AND, DL, VT,
8582                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8583   }
8584
8585   // fold (bitconvert (fcopysign cst, x)) ->
8586   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8587   // Note that we don't handle (copysign x, cst) because this can always be
8588   // folded to an fneg or fabs.
8589   //
8590   // For ppc_fp128:
8591   // fold (bitcast (fcopysign cst, x)) ->
8592   //     flipbit = (and (extract_element
8593   //                     (xor (bitcast cst), (bitcast x)), 0),
8594   //                    signbit)
8595   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8596   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8597       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8598       VT.isInteger() && !VT.isVector()) {
8599     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8600     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8601     if (isTypeLegal(IntXVT)) {
8602       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8603       AddToWorklist(X.getNode());
8604
8605       // If X has a different width than the result/lhs, sext it or truncate it.
8606       unsigned VTWidth = VT.getSizeInBits();
8607       if (OrigXWidth < VTWidth) {
8608         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8609         AddToWorklist(X.getNode());
8610       } else if (OrigXWidth > VTWidth) {
8611         // To get the sign bit in the right place, we have to shift it right
8612         // before truncating.
8613         SDLoc DL(X);
8614         X = DAG.getNode(ISD::SRL, DL,
8615                         X.getValueType(), X,
8616                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8617                                         X.getValueType()));
8618         AddToWorklist(X.getNode());
8619         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8620         AddToWorklist(X.getNode());
8621       }
8622
8623       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8624         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8625         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8626         AddToWorklist(Cst.getNode());
8627         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8628         AddToWorklist(X.getNode());
8629         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8630         AddToWorklist(XorResult.getNode());
8631         SDValue XorResult64 = DAG.getNode(
8632             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8633             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8634                                   SDLoc(XorResult)));
8635         AddToWorklist(XorResult64.getNode());
8636         SDValue FlipBit =
8637             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8638                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8639         AddToWorklist(FlipBit.getNode());
8640         SDValue FlipBits =
8641             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8642         AddToWorklist(FlipBits.getNode());
8643         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8644       }
8645       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8646       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8647                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8648       AddToWorklist(X.getNode());
8649
8650       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8651       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8652                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8653       AddToWorklist(Cst.getNode());
8654
8655       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8656     }
8657   }
8658
8659   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8660   if (N0.getOpcode() == ISD::BUILD_PAIR)
8661     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8662       return CombineLD;
8663
8664   // Remove double bitcasts from shuffles - this is often a legacy of
8665   // XformToShuffleWithZero being used to combine bitmaskings (of
8666   // float vectors bitcast to integer vectors) into shuffles.
8667   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8668   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8669       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8670       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8671       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8672     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8673
8674     // If operands are a bitcast, peek through if it casts the original VT.
8675     // If operands are a constant, just bitcast back to original VT.
8676     auto PeekThroughBitcast = [&](SDValue Op) {
8677       if (Op.getOpcode() == ISD::BITCAST &&
8678           Op.getOperand(0).getValueType() == VT)
8679         return SDValue(Op.getOperand(0));
8680       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8681           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8682         return DAG.getBitcast(VT, Op);
8683       return SDValue();
8684     };
8685
8686     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8687     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8688     if (!(SV0 && SV1))
8689       return SDValue();
8690
8691     int MaskScale =
8692         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8693     SmallVector<int, 8> NewMask;
8694     for (int M : SVN->getMask())
8695       for (int i = 0; i != MaskScale; ++i)
8696         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8697
8698     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8699     if (!LegalMask) {
8700       std::swap(SV0, SV1);
8701       ShuffleVectorSDNode::commuteMask(NewMask);
8702       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8703     }
8704
8705     if (LegalMask)
8706       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8707   }
8708
8709   return SDValue();
8710 }
8711
8712 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8713   EVT VT = N->getValueType(0);
8714   return CombineConsecutiveLoads(N, VT);
8715 }
8716
8717 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8718 /// operands. DstEltVT indicates the destination element value type.
8719 SDValue DAGCombiner::
8720 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8721   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8722
8723   // If this is already the right type, we're done.
8724   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8725
8726   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8727   unsigned DstBitSize = DstEltVT.getSizeInBits();
8728
8729   // If this is a conversion of N elements of one type to N elements of another
8730   // type, convert each element.  This handles FP<->INT cases.
8731   if (SrcBitSize == DstBitSize) {
8732     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8733                               BV->getValueType(0).getVectorNumElements());
8734
8735     // Due to the FP element handling below calling this routine recursively,
8736     // we can end up with a scalar-to-vector node here.
8737     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8738       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8739                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8740
8741     SmallVector<SDValue, 8> Ops;
8742     for (SDValue Op : BV->op_values()) {
8743       // If the vector element type is not legal, the BUILD_VECTOR operands
8744       // are promoted and implicitly truncated.  Make that explicit here.
8745       if (Op.getValueType() != SrcEltVT)
8746         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8747       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8748       AddToWorklist(Ops.back().getNode());
8749     }
8750     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8751   }
8752
8753   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8754   // handle annoying details of growing/shrinking FP values, we convert them to
8755   // int first.
8756   if (SrcEltVT.isFloatingPoint()) {
8757     // Convert the input float vector to a int vector where the elements are the
8758     // same sizes.
8759     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8760     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8761     SrcEltVT = IntVT;
8762   }
8763
8764   // Now we know the input is an integer vector.  If the output is a FP type,
8765   // convert to integer first, then to FP of the right size.
8766   if (DstEltVT.isFloatingPoint()) {
8767     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8768     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8769
8770     // Next, convert to FP elements of the same size.
8771     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8772   }
8773
8774   SDLoc DL(BV);
8775
8776   // Okay, we know the src/dst types are both integers of differing types.
8777   // Handling growing first.
8778   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8779   if (SrcBitSize < DstBitSize) {
8780     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8781
8782     SmallVector<SDValue, 8> Ops;
8783     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8784          i += NumInputsPerOutput) {
8785       bool isLE = DAG.getDataLayout().isLittleEndian();
8786       APInt NewBits = APInt(DstBitSize, 0);
8787       bool EltIsUndef = true;
8788       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8789         // Shift the previously computed bits over.
8790         NewBits <<= SrcBitSize;
8791         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8792         if (Op.isUndef()) continue;
8793         EltIsUndef = false;
8794
8795         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8796                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8797       }
8798
8799       if (EltIsUndef)
8800         Ops.push_back(DAG.getUNDEF(DstEltVT));
8801       else
8802         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8803     }
8804
8805     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8806     return DAG.getBuildVector(VT, DL, Ops);
8807   }
8808
8809   // Finally, this must be the case where we are shrinking elements: each input
8810   // turns into multiple outputs.
8811   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8812   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8813                             NumOutputsPerInput*BV->getNumOperands());
8814   SmallVector<SDValue, 8> Ops;
8815
8816   for (const SDValue &Op : BV->op_values()) {
8817     if (Op.isUndef()) {
8818       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8819       continue;
8820     }
8821
8822     APInt OpVal = cast<ConstantSDNode>(Op)->
8823                   getAPIntValue().zextOrTrunc(SrcBitSize);
8824
8825     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8826       APInt ThisVal = OpVal.trunc(DstBitSize);
8827       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8828       OpVal.lshrInPlace(DstBitSize);
8829     }
8830
8831     // For big endian targets, swap the order of the pieces of each element.
8832     if (DAG.getDataLayout().isBigEndian())
8833       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8834   }
8835
8836   return DAG.getBuildVector(VT, DL, Ops);
8837 }
8838
8839 static bool isContractable(SDNode *N) {
8840   SDNodeFlags F = N->getFlags();
8841   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8842 }
8843
8844 /// Try to perform FMA combining on a given FADD node.
8845 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8846   SDValue N0 = N->getOperand(0);
8847   SDValue N1 = N->getOperand(1);
8848   EVT VT = N->getValueType(0);
8849   SDLoc SL(N);
8850
8851   const TargetOptions &Options = DAG.getTarget().Options;
8852
8853   // Floating-point multiply-add with intermediate rounding.
8854   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8855
8856   // Floating-point multiply-add without intermediate rounding.
8857   bool HasFMA =
8858       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8859       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8860
8861   // No valid opcode, do not combine.
8862   if (!HasFMAD && !HasFMA)
8863     return SDValue();
8864
8865   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8866                               Options.UnsafeFPMath || HasFMAD);
8867   // If the addition is not contractable, do not combine.
8868   if (!AllowFusionGlobally && !isContractable(N))
8869     return SDValue();
8870
8871   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8872   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8873     return SDValue();
8874
8875   // Always prefer FMAD to FMA for precision.
8876   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8877   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8878   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8879
8880   // Is the node an FMUL and contractable either due to global flags or
8881   // SDNodeFlags.
8882   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8883     if (N.getOpcode() != ISD::FMUL)
8884       return false;
8885     return AllowFusionGlobally || isContractable(N.getNode());
8886   };
8887   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8888   // prefer to fold the multiply with fewer uses.
8889   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8890     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8891       std::swap(N0, N1);
8892   }
8893
8894   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8895   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8896     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8897                        N0.getOperand(0), N0.getOperand(1), N1);
8898   }
8899
8900   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8901   // Note: Commutes FADD operands.
8902   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8903     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8904                        N1.getOperand(0), N1.getOperand(1), N0);
8905   }
8906
8907   // Look through FP_EXTEND nodes to do more combining.
8908   if (LookThroughFPExt) {
8909     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8910     if (N0.getOpcode() == ISD::FP_EXTEND) {
8911       SDValue N00 = N0.getOperand(0);
8912       if (isContractableFMUL(N00))
8913         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8914                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8915                                        N00.getOperand(0)),
8916                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8917                                        N00.getOperand(1)), N1);
8918     }
8919
8920     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8921     // Note: Commutes FADD operands.
8922     if (N1.getOpcode() == ISD::FP_EXTEND) {
8923       SDValue N10 = N1.getOperand(0);
8924       if (isContractableFMUL(N10))
8925         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8926                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8927                                        N10.getOperand(0)),
8928                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8929                                        N10.getOperand(1)), N0);
8930     }
8931   }
8932
8933   // More folding opportunities when target permits.
8934   if (Aggressive) {
8935     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8936     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8937     // are currently only supported on binary nodes.
8938     if (Options.UnsafeFPMath &&
8939         N0.getOpcode() == PreferredFusedOpcode &&
8940         N0.getOperand(2).getOpcode() == ISD::FMUL &&
8941         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8942       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8943                          N0.getOperand(0), N0.getOperand(1),
8944                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8945                                      N0.getOperand(2).getOperand(0),
8946                                      N0.getOperand(2).getOperand(1),
8947                                      N1));
8948     }
8949
8950     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8951     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8952     // are currently only supported on binary nodes.
8953     if (Options.UnsafeFPMath &&
8954         N1->getOpcode() == PreferredFusedOpcode &&
8955         N1.getOperand(2).getOpcode() == ISD::FMUL &&
8956         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8957       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8958                          N1.getOperand(0), N1.getOperand(1),
8959                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8960                                      N1.getOperand(2).getOperand(0),
8961                                      N1.getOperand(2).getOperand(1),
8962                                      N0));
8963     }
8964
8965     if (LookThroughFPExt) {
8966       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8967       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8968       auto FoldFAddFMAFPExtFMul = [&] (
8969           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8970         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8971                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8972                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8973                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8974                                        Z));
8975       };
8976       if (N0.getOpcode() == PreferredFusedOpcode) {
8977         SDValue N02 = N0.getOperand(2);
8978         if (N02.getOpcode() == ISD::FP_EXTEND) {
8979           SDValue N020 = N02.getOperand(0);
8980           if (isContractableFMUL(N020))
8981             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8982                                         N020.getOperand(0), N020.getOperand(1),
8983                                         N1);
8984         }
8985       }
8986
8987       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8988       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8989       // FIXME: This turns two single-precision and one double-precision
8990       // operation into two double-precision operations, which might not be
8991       // interesting for all targets, especially GPUs.
8992       auto FoldFAddFPExtFMAFMul = [&] (
8993           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8994         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8995                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8996                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8997                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8998                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8999                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9000                                        Z));
9001       };
9002       if (N0.getOpcode() == ISD::FP_EXTEND) {
9003         SDValue N00 = N0.getOperand(0);
9004         if (N00.getOpcode() == PreferredFusedOpcode) {
9005           SDValue N002 = N00.getOperand(2);
9006           if (isContractableFMUL(N002))
9007             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9008                                         N002.getOperand(0), N002.getOperand(1),
9009                                         N1);
9010         }
9011       }
9012
9013       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9014       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9015       if (N1.getOpcode() == PreferredFusedOpcode) {
9016         SDValue N12 = N1.getOperand(2);
9017         if (N12.getOpcode() == ISD::FP_EXTEND) {
9018           SDValue N120 = N12.getOperand(0);
9019           if (isContractableFMUL(N120))
9020             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9021                                         N120.getOperand(0), N120.getOperand(1),
9022                                         N0);
9023         }
9024       }
9025
9026       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9027       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9028       // FIXME: This turns two single-precision and one double-precision
9029       // operation into two double-precision operations, which might not be
9030       // interesting for all targets, especially GPUs.
9031       if (N1.getOpcode() == ISD::FP_EXTEND) {
9032         SDValue N10 = N1.getOperand(0);
9033         if (N10.getOpcode() == PreferredFusedOpcode) {
9034           SDValue N102 = N10.getOperand(2);
9035           if (isContractableFMUL(N102))
9036             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9037                                         N102.getOperand(0), N102.getOperand(1),
9038                                         N0);
9039         }
9040       }
9041     }
9042   }
9043
9044   return SDValue();
9045 }
9046
9047 /// Try to perform FMA combining on a given FSUB node.
9048 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9049   SDValue N0 = N->getOperand(0);
9050   SDValue N1 = N->getOperand(1);
9051   EVT VT = N->getValueType(0);
9052   SDLoc SL(N);
9053
9054   const TargetOptions &Options = DAG.getTarget().Options;
9055   // Floating-point multiply-add with intermediate rounding.
9056   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9057
9058   // Floating-point multiply-add without intermediate rounding.
9059   bool HasFMA =
9060       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9061       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9062
9063   // No valid opcode, do not combine.
9064   if (!HasFMAD && !HasFMA)
9065     return SDValue();
9066
9067   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9068                               Options.UnsafeFPMath || HasFMAD);
9069   // If the subtraction is not contractable, do not combine.
9070   if (!AllowFusionGlobally && !isContractable(N))
9071     return SDValue();
9072
9073   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9074   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9075     return SDValue();
9076
9077   // Always prefer FMAD to FMA for precision.
9078   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9079   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9080   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9081
9082   // Is the node an FMUL and contractable either due to global flags or
9083   // SDNodeFlags.
9084   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9085     if (N.getOpcode() != ISD::FMUL)
9086       return false;
9087     return AllowFusionGlobally || isContractable(N.getNode());
9088   };
9089
9090   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9091   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9092     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9093                        N0.getOperand(0), N0.getOperand(1),
9094                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9095   }
9096
9097   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9098   // Note: Commutes FSUB operands.
9099   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9100     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9101                        DAG.getNode(ISD::FNEG, SL, VT,
9102                                    N1.getOperand(0)),
9103                        N1.getOperand(1), N0);
9104
9105   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9106   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9107       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9108     SDValue N00 = N0.getOperand(0).getOperand(0);
9109     SDValue N01 = N0.getOperand(0).getOperand(1);
9110     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9111                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9112                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9113   }
9114
9115   // Look through FP_EXTEND nodes to do more combining.
9116   if (LookThroughFPExt) {
9117     // fold (fsub (fpext (fmul x, y)), z)
9118     //   -> (fma (fpext x), (fpext y), (fneg z))
9119     if (N0.getOpcode() == ISD::FP_EXTEND) {
9120       SDValue N00 = N0.getOperand(0);
9121       if (isContractableFMUL(N00))
9122         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9123                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9124                                        N00.getOperand(0)),
9125                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9126                                        N00.getOperand(1)),
9127                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9128     }
9129
9130     // fold (fsub x, (fpext (fmul y, z)))
9131     //   -> (fma (fneg (fpext y)), (fpext z), x)
9132     // Note: Commutes FSUB operands.
9133     if (N1.getOpcode() == ISD::FP_EXTEND) {
9134       SDValue N10 = N1.getOperand(0);
9135       if (isContractableFMUL(N10))
9136         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9137                            DAG.getNode(ISD::FNEG, SL, VT,
9138                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9139                                                    N10.getOperand(0))),
9140                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9141                                        N10.getOperand(1)),
9142                            N0);
9143     }
9144
9145     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9146     //   -> (fneg (fma (fpext x), (fpext y), z))
9147     // Note: This could be removed with appropriate canonicalization of the
9148     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9149     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9150     // from implementing the canonicalization in visitFSUB.
9151     if (N0.getOpcode() == ISD::FP_EXTEND) {
9152       SDValue N00 = N0.getOperand(0);
9153       if (N00.getOpcode() == ISD::FNEG) {
9154         SDValue N000 = N00.getOperand(0);
9155         if (isContractableFMUL(N000)) {
9156           return DAG.getNode(ISD::FNEG, SL, VT,
9157                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9158                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9159                                                      N000.getOperand(0)),
9160                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9161                                                      N000.getOperand(1)),
9162                                          N1));
9163         }
9164       }
9165     }
9166
9167     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9168     //   -> (fneg (fma (fpext x)), (fpext y), z)
9169     // Note: This could be removed with appropriate canonicalization of the
9170     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9171     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9172     // from implementing the canonicalization in visitFSUB.
9173     if (N0.getOpcode() == ISD::FNEG) {
9174       SDValue N00 = N0.getOperand(0);
9175       if (N00.getOpcode() == ISD::FP_EXTEND) {
9176         SDValue N000 = N00.getOperand(0);
9177         if (isContractableFMUL(N000)) {
9178           return DAG.getNode(ISD::FNEG, SL, VT,
9179                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9180                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9181                                                      N000.getOperand(0)),
9182                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9183                                                      N000.getOperand(1)),
9184                                          N1));
9185         }
9186       }
9187     }
9188
9189   }
9190
9191   // More folding opportunities when target permits.
9192   if (Aggressive) {
9193     // fold (fsub (fma x, y, (fmul u, v)), z)
9194     //   -> (fma x, y (fma u, v, (fneg z)))
9195     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9196     // are currently only supported on binary nodes.
9197     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9198         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9199         N0.getOperand(2)->hasOneUse()) {
9200       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9201                          N0.getOperand(0), N0.getOperand(1),
9202                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9203                                      N0.getOperand(2).getOperand(0),
9204                                      N0.getOperand(2).getOperand(1),
9205                                      DAG.getNode(ISD::FNEG, SL, VT,
9206                                                  N1)));
9207     }
9208
9209     // fold (fsub x, (fma y, z, (fmul u, v)))
9210     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9211     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9212     // are currently only supported on binary nodes.
9213     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9214         isContractableFMUL(N1.getOperand(2))) {
9215       SDValue N20 = N1.getOperand(2).getOperand(0);
9216       SDValue N21 = N1.getOperand(2).getOperand(1);
9217       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9218                          DAG.getNode(ISD::FNEG, SL, VT,
9219                                      N1.getOperand(0)),
9220                          N1.getOperand(1),
9221                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9222                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9223
9224                                      N21, N0));
9225     }
9226
9227     if (LookThroughFPExt) {
9228       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9229       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9230       if (N0.getOpcode() == PreferredFusedOpcode) {
9231         SDValue N02 = N0.getOperand(2);
9232         if (N02.getOpcode() == ISD::FP_EXTEND) {
9233           SDValue N020 = N02.getOperand(0);
9234           if (isContractableFMUL(N020))
9235             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9236                                N0.getOperand(0), N0.getOperand(1),
9237                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9238                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9239                                                        N020.getOperand(0)),
9240                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9241                                                        N020.getOperand(1)),
9242                                            DAG.getNode(ISD::FNEG, SL, VT,
9243                                                        N1)));
9244         }
9245       }
9246
9247       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9248       //   -> (fma (fpext x), (fpext y),
9249       //           (fma (fpext u), (fpext v), (fneg z)))
9250       // FIXME: This turns two single-precision and one double-precision
9251       // operation into two double-precision operations, which might not be
9252       // interesting for all targets, especially GPUs.
9253       if (N0.getOpcode() == ISD::FP_EXTEND) {
9254         SDValue N00 = N0.getOperand(0);
9255         if (N00.getOpcode() == PreferredFusedOpcode) {
9256           SDValue N002 = N00.getOperand(2);
9257           if (isContractableFMUL(N002))
9258             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9259                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9260                                            N00.getOperand(0)),
9261                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9262                                            N00.getOperand(1)),
9263                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9264                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9265                                                        N002.getOperand(0)),
9266                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9267                                                        N002.getOperand(1)),
9268                                            DAG.getNode(ISD::FNEG, SL, VT,
9269                                                        N1)));
9270         }
9271       }
9272
9273       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9274       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9275       if (N1.getOpcode() == PreferredFusedOpcode &&
9276         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9277         SDValue N120 = N1.getOperand(2).getOperand(0);
9278         if (isContractableFMUL(N120)) {
9279           SDValue N1200 = N120.getOperand(0);
9280           SDValue N1201 = N120.getOperand(1);
9281           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9282                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9283                              N1.getOperand(1),
9284                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9285                                          DAG.getNode(ISD::FNEG, SL, VT,
9286                                              DAG.getNode(ISD::FP_EXTEND, SL,
9287                                                          VT, N1200)),
9288                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9289                                                      N1201),
9290                                          N0));
9291         }
9292       }
9293
9294       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9295       //   -> (fma (fneg (fpext y)), (fpext z),
9296       //           (fma (fneg (fpext u)), (fpext v), x))
9297       // FIXME: This turns two single-precision and one double-precision
9298       // operation into two double-precision operations, which might not be
9299       // interesting for all targets, especially GPUs.
9300       if (N1.getOpcode() == ISD::FP_EXTEND &&
9301         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9302         SDValue N100 = N1.getOperand(0).getOperand(0);
9303         SDValue N101 = N1.getOperand(0).getOperand(1);
9304         SDValue N102 = N1.getOperand(0).getOperand(2);
9305         if (isContractableFMUL(N102)) {
9306           SDValue N1020 = N102.getOperand(0);
9307           SDValue N1021 = N102.getOperand(1);
9308           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9309                              DAG.getNode(ISD::FNEG, SL, VT,
9310                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9311                                                      N100)),
9312                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9313                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9314                                          DAG.getNode(ISD::FNEG, SL, VT,
9315                                              DAG.getNode(ISD::FP_EXTEND, SL,
9316                                                          VT, N1020)),
9317                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9318                                                      N1021),
9319                                          N0));
9320         }
9321       }
9322     }
9323   }
9324
9325   return SDValue();
9326 }
9327
9328 /// Try to perform FMA combining on a given FMUL node based on the distributive
9329 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9330 /// subtraction instead of addition).
9331 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9332   SDValue N0 = N->getOperand(0);
9333   SDValue N1 = N->getOperand(1);
9334   EVT VT = N->getValueType(0);
9335   SDLoc SL(N);
9336
9337   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9338
9339   const TargetOptions &Options = DAG.getTarget().Options;
9340
9341   // The transforms below are incorrect when x == 0 and y == inf, because the
9342   // intermediate multiplication produces a nan.
9343   if (!Options.NoInfsFPMath)
9344     return SDValue();
9345
9346   // Floating-point multiply-add without intermediate rounding.
9347   bool HasFMA =
9348       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9349       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9350       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9351
9352   // Floating-point multiply-add with intermediate rounding. This can result
9353   // in a less precise result due to the changed rounding order.
9354   bool HasFMAD = Options.UnsafeFPMath &&
9355                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9356
9357   // No valid opcode, do not combine.
9358   if (!HasFMAD && !HasFMA)
9359     return SDValue();
9360
9361   // Always prefer FMAD to FMA for precision.
9362   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9363   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9364
9365   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9366   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9367   auto FuseFADD = [&](SDValue X, SDValue Y) {
9368     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9369       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9370       if (XC1 && XC1->isExactlyValue(+1.0))
9371         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9372       if (XC1 && XC1->isExactlyValue(-1.0))
9373         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9374                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9375     }
9376     return SDValue();
9377   };
9378
9379   if (SDValue FMA = FuseFADD(N0, N1))
9380     return FMA;
9381   if (SDValue FMA = FuseFADD(N1, N0))
9382     return FMA;
9383
9384   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9385   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9386   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9387   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9388   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9389     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9390       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9391       if (XC0 && XC0->isExactlyValue(+1.0))
9392         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9393                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9394                            Y);
9395       if (XC0 && XC0->isExactlyValue(-1.0))
9396         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9397                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9398                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9399
9400       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9401       if (XC1 && XC1->isExactlyValue(+1.0))
9402         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9403                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9404       if (XC1 && XC1->isExactlyValue(-1.0))
9405         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9406     }
9407     return SDValue();
9408   };
9409
9410   if (SDValue FMA = FuseFSUB(N0, N1))
9411     return FMA;
9412   if (SDValue FMA = FuseFSUB(N1, N0))
9413     return FMA;
9414
9415   return SDValue();
9416 }
9417
9418 static bool isFMulNegTwo(SDValue &N) {
9419   if (N.getOpcode() != ISD::FMUL)
9420     return false;
9421   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9422     return CFP->isExactlyValue(-2.0);
9423   return false;
9424 }
9425
9426 SDValue DAGCombiner::visitFADD(SDNode *N) {
9427   SDValue N0 = N->getOperand(0);
9428   SDValue N1 = N->getOperand(1);
9429   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9430   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9431   EVT VT = N->getValueType(0);
9432   SDLoc DL(N);
9433   const TargetOptions &Options = DAG.getTarget().Options;
9434   const SDNodeFlags Flags = N->getFlags();
9435
9436   // fold vector ops
9437   if (VT.isVector())
9438     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9439       return FoldedVOp;
9440
9441   // fold (fadd c1, c2) -> c1 + c2
9442   if (N0CFP && N1CFP)
9443     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9444
9445   // canonicalize constant to RHS
9446   if (N0CFP && !N1CFP)
9447     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9448
9449   if (SDValue NewSel = foldBinOpIntoSelect(N))
9450     return NewSel;
9451
9452   // fold (fadd A, (fneg B)) -> (fsub A, B)
9453   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9454       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9455     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9456                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9457
9458   // fold (fadd (fneg A), B) -> (fsub B, A)
9459   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9460       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9461     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9462                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9463
9464   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9465   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9466   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9467       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9468     bool N1IsFMul = isFMulNegTwo(N1);
9469     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9470     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9471     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9472   }
9473
9474   // FIXME: Auto-upgrade the target/function-level option.
9475   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9476     // fold (fadd A, 0) -> A
9477     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9478       if (N1C->isZero())
9479         return N0;
9480   }
9481
9482   // If 'unsafe math' is enabled, fold lots of things.
9483   if (Options.UnsafeFPMath) {
9484     // No FP constant should be created after legalization as Instruction
9485     // Selection pass has a hard time dealing with FP constants.
9486     bool AllowNewConst = (Level < AfterLegalizeDAG);
9487
9488     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9489     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9490         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9491       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9492                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9493                                      Flags),
9494                          Flags);
9495
9496     // If allowed, fold (fadd (fneg x), x) -> 0.0
9497     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9498       return DAG.getConstantFP(0.0, DL, VT);
9499
9500     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9501     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9502       return DAG.getConstantFP(0.0, DL, VT);
9503
9504     // We can fold chains of FADD's of the same value into multiplications.
9505     // This transform is not safe in general because we are reducing the number
9506     // of rounding steps.
9507     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9508       if (N0.getOpcode() == ISD::FMUL) {
9509         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9510         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9511
9512         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9513         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9514           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9515                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9516           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9517         }
9518
9519         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9520         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9521             N1.getOperand(0) == N1.getOperand(1) &&
9522             N0.getOperand(0) == N1.getOperand(0)) {
9523           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9524                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9525           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9526         }
9527       }
9528
9529       if (N1.getOpcode() == ISD::FMUL) {
9530         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9531         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9532
9533         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9534         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9535           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9536                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9537           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9538         }
9539
9540         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9541         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9542             N0.getOperand(0) == N0.getOperand(1) &&
9543             N1.getOperand(0) == N0.getOperand(0)) {
9544           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9545                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9546           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9547         }
9548       }
9549
9550       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9551         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9552         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9553         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9554             (N0.getOperand(0) == N1)) {
9555           return DAG.getNode(ISD::FMUL, DL, VT,
9556                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9557         }
9558       }
9559
9560       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9561         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9562         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9563         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9564             N1.getOperand(0) == N0) {
9565           return DAG.getNode(ISD::FMUL, DL, VT,
9566                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9567         }
9568       }
9569
9570       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9571       if (AllowNewConst &&
9572           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9573           N0.getOperand(0) == N0.getOperand(1) &&
9574           N1.getOperand(0) == N1.getOperand(1) &&
9575           N0.getOperand(0) == N1.getOperand(0)) {
9576         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9577                            DAG.getConstantFP(4.0, DL, VT), Flags);
9578       }
9579     }
9580   } // enable-unsafe-fp-math
9581
9582   // FADD -> FMA combines:
9583   if (SDValue Fused = visitFADDForFMACombine(N)) {
9584     AddToWorklist(Fused.getNode());
9585     return Fused;
9586   }
9587   return SDValue();
9588 }
9589
9590 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9591   SDValue N0 = N->getOperand(0);
9592   SDValue N1 = N->getOperand(1);
9593   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9594   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9595   EVT VT = N->getValueType(0);
9596   SDLoc DL(N);
9597   const TargetOptions &Options = DAG.getTarget().Options;
9598   const SDNodeFlags Flags = N->getFlags();
9599
9600   // fold vector ops
9601   if (VT.isVector())
9602     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9603       return FoldedVOp;
9604
9605   // fold (fsub c1, c2) -> c1-c2
9606   if (N0CFP && N1CFP)
9607     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9608
9609   if (SDValue NewSel = foldBinOpIntoSelect(N))
9610     return NewSel;
9611
9612   // fold (fsub A, (fneg B)) -> (fadd A, B)
9613   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9614     return DAG.getNode(ISD::FADD, DL, VT, N0,
9615                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9616
9617   // FIXME: Auto-upgrade the target/function-level option.
9618   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9619     // (fsub 0, B) -> -B
9620     if (N0CFP && N0CFP->isZero()) {
9621       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9622         return GetNegatedExpression(N1, DAG, LegalOperations);
9623       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9624         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9625     }
9626   }
9627
9628   // If 'unsafe math' is enabled, fold lots of things.
9629   if (Options.UnsafeFPMath) {
9630     // (fsub A, 0) -> A
9631     if (N1CFP && N1CFP->isZero())
9632       return N0;
9633
9634     // (fsub x, x) -> 0.0
9635     if (N0 == N1)
9636       return DAG.getConstantFP(0.0f, DL, VT);
9637
9638     // (fsub x, (fadd x, y)) -> (fneg y)
9639     // (fsub x, (fadd y, x)) -> (fneg y)
9640     if (N1.getOpcode() == ISD::FADD) {
9641       SDValue N10 = N1->getOperand(0);
9642       SDValue N11 = N1->getOperand(1);
9643
9644       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9645         return GetNegatedExpression(N11, DAG, LegalOperations);
9646
9647       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9648         return GetNegatedExpression(N10, DAG, LegalOperations);
9649     }
9650   }
9651
9652   // FSUB -> FMA combines:
9653   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9654     AddToWorklist(Fused.getNode());
9655     return Fused;
9656   }
9657
9658   return SDValue();
9659 }
9660
9661 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9662   SDValue N0 = N->getOperand(0);
9663   SDValue N1 = N->getOperand(1);
9664   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9665   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9666   EVT VT = N->getValueType(0);
9667   SDLoc DL(N);
9668   const TargetOptions &Options = DAG.getTarget().Options;
9669   const SDNodeFlags Flags = N->getFlags();
9670
9671   // fold vector ops
9672   if (VT.isVector()) {
9673     // This just handles C1 * C2 for vectors. Other vector folds are below.
9674     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9675       return FoldedVOp;
9676   }
9677
9678   // fold (fmul c1, c2) -> c1*c2
9679   if (N0CFP && N1CFP)
9680     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9681
9682   // canonicalize constant to RHS
9683   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9684      !isConstantFPBuildVectorOrConstantFP(N1))
9685     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9686
9687   // fold (fmul A, 1.0) -> A
9688   if (N1CFP && N1CFP->isExactlyValue(1.0))
9689     return N0;
9690
9691   if (SDValue NewSel = foldBinOpIntoSelect(N))
9692     return NewSel;
9693
9694   if (Options.UnsafeFPMath) {
9695     // fold (fmul A, 0) -> 0
9696     if (N1CFP && N1CFP->isZero())
9697       return N1;
9698
9699     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9700     if (N0.getOpcode() == ISD::FMUL) {
9701       // Fold scalars or any vector constants (not just splats).
9702       // This fold is done in general by InstCombine, but extra fmul insts
9703       // may have been generated during lowering.
9704       SDValue N00 = N0.getOperand(0);
9705       SDValue N01 = N0.getOperand(1);
9706       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9707       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9708       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9709
9710       // Check 1: Make sure that the first operand of the inner multiply is NOT
9711       // a constant. Otherwise, we may induce infinite looping.
9712       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9713         // Check 2: Make sure that the second operand of the inner multiply and
9714         // the second operand of the outer multiply are constants.
9715         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9716             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9717           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9718           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9719         }
9720       }
9721     }
9722
9723     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9724     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9725     // during an early run of DAGCombiner can prevent folding with fmuls
9726     // inserted during lowering.
9727     if (N0.getOpcode() == ISD::FADD &&
9728         (N0.getOperand(0) == N0.getOperand(1)) &&
9729         N0.hasOneUse()) {
9730       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9731       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9732       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9733     }
9734   }
9735
9736   // fold (fmul X, 2.0) -> (fadd X, X)
9737   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9738     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9739
9740   // fold (fmul X, -1.0) -> (fneg X)
9741   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9742     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9743       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9744
9745   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9746   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9747     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9748       // Both can be negated for free, check to see if at least one is cheaper
9749       // negated.
9750       if (LHSNeg == 2 || RHSNeg == 2)
9751         return DAG.getNode(ISD::FMUL, DL, VT,
9752                            GetNegatedExpression(N0, DAG, LegalOperations),
9753                            GetNegatedExpression(N1, DAG, LegalOperations),
9754                            Flags);
9755     }
9756   }
9757
9758   // FMUL -> FMA combines:
9759   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9760     AddToWorklist(Fused.getNode());
9761     return Fused;
9762   }
9763
9764   return SDValue();
9765 }
9766
9767 SDValue DAGCombiner::visitFMA(SDNode *N) {
9768   SDValue N0 = N->getOperand(0);
9769   SDValue N1 = N->getOperand(1);
9770   SDValue N2 = N->getOperand(2);
9771   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9772   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9773   EVT VT = N->getValueType(0);
9774   SDLoc DL(N);
9775   const TargetOptions &Options = DAG.getTarget().Options;
9776
9777   // Constant fold FMA.
9778   if (isa<ConstantFPSDNode>(N0) &&
9779       isa<ConstantFPSDNode>(N1) &&
9780       isa<ConstantFPSDNode>(N2)) {
9781     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9782   }
9783
9784   if (Options.UnsafeFPMath) {
9785     if (N0CFP && N0CFP->isZero())
9786       return N2;
9787     if (N1CFP && N1CFP->isZero())
9788       return N2;
9789   }
9790   // TODO: The FMA node should have flags that propagate to these nodes.
9791   if (N0CFP && N0CFP->isExactlyValue(1.0))
9792     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9793   if (N1CFP && N1CFP->isExactlyValue(1.0))
9794     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9795
9796   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9797   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9798      !isConstantFPBuildVectorOrConstantFP(N1))
9799     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9800
9801   // TODO: FMA nodes should have flags that propagate to the created nodes.
9802   // For now, create a Flags object for use with all unsafe math transforms.
9803   SDNodeFlags Flags;
9804   Flags.setUnsafeAlgebra(true);
9805
9806   if (Options.UnsafeFPMath) {
9807     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9808     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9809         isConstantFPBuildVectorOrConstantFP(N1) &&
9810         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9811       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9812                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9813                                      Flags), Flags);
9814     }
9815
9816     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9817     if (N0.getOpcode() == ISD::FMUL &&
9818         isConstantFPBuildVectorOrConstantFP(N1) &&
9819         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9820       return DAG.getNode(ISD::FMA, DL, VT,
9821                          N0.getOperand(0),
9822                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9823                                      Flags),
9824                          N2);
9825     }
9826   }
9827
9828   // (fma x, 1, y) -> (fadd x, y)
9829   // (fma x, -1, y) -> (fadd (fneg x), y)
9830   if (N1CFP) {
9831     if (N1CFP->isExactlyValue(1.0))
9832       // TODO: The FMA node should have flags that propagate to this node.
9833       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9834
9835     if (N1CFP->isExactlyValue(-1.0) &&
9836         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9837       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9838       AddToWorklist(RHSNeg.getNode());
9839       // TODO: The FMA node should have flags that propagate to this node.
9840       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9841     }
9842   }
9843
9844   if (Options.UnsafeFPMath) {
9845     // (fma x, c, x) -> (fmul x, (c+1))
9846     if (N1CFP && N0 == N2) {
9847       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9848                          DAG.getNode(ISD::FADD, DL, VT, N1,
9849                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9850                          Flags);
9851     }
9852
9853     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9854     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9855       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9856                          DAG.getNode(ISD::FADD, DL, VT, N1,
9857                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
9858                          Flags);
9859     }
9860   }
9861
9862   return SDValue();
9863 }
9864
9865 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9866 // reciprocal.
9867 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9868 // Notice that this is not always beneficial. One reason is different targets
9869 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9870 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9871 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9872 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9873   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9874   const SDNodeFlags Flags = N->getFlags();
9875   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9876     return SDValue();
9877
9878   // Skip if current node is a reciprocal.
9879   SDValue N0 = N->getOperand(0);
9880   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9881   if (N0CFP && N0CFP->isExactlyValue(1.0))
9882     return SDValue();
9883
9884   // Exit early if the target does not want this transform or if there can't
9885   // possibly be enough uses of the divisor to make the transform worthwhile.
9886   SDValue N1 = N->getOperand(1);
9887   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9888   if (!MinUses || N1->use_size() < MinUses)
9889     return SDValue();
9890
9891   // Find all FDIV users of the same divisor.
9892   // Use a set because duplicates may be present in the user list.
9893   SetVector<SDNode *> Users;
9894   for (auto *U : N1->uses()) {
9895     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9896       // This division is eligible for optimization only if global unsafe math
9897       // is enabled or if this division allows reciprocal formation.
9898       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
9899         Users.insert(U);
9900     }
9901   }
9902
9903   // Now that we have the actual number of divisor uses, make sure it meets
9904   // the minimum threshold specified by the target.
9905   if (Users.size() < MinUses)
9906     return SDValue();
9907
9908   EVT VT = N->getValueType(0);
9909   SDLoc DL(N);
9910   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9911   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9912
9913   // Dividend / Divisor -> Dividend * Reciprocal
9914   for (auto *U : Users) {
9915     SDValue Dividend = U->getOperand(0);
9916     if (Dividend != FPOne) {
9917       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9918                                     Reciprocal, Flags);
9919       CombineTo(U, NewNode);
9920     } else if (U != Reciprocal.getNode()) {
9921       // In the absence of fast-math-flags, this user node is always the
9922       // same node as Reciprocal, but with FMF they may be different nodes.
9923       CombineTo(U, Reciprocal);
9924     }
9925   }
9926   return SDValue(N, 0);  // N was replaced.
9927 }
9928
9929 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9930   SDValue N0 = N->getOperand(0);
9931   SDValue N1 = N->getOperand(1);
9932   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9933   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9934   EVT VT = N->getValueType(0);
9935   SDLoc DL(N);
9936   const TargetOptions &Options = DAG.getTarget().Options;
9937   SDNodeFlags Flags = N->getFlags();
9938
9939   // fold vector ops
9940   if (VT.isVector())
9941     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9942       return FoldedVOp;
9943
9944   // fold (fdiv c1, c2) -> c1/c2
9945   if (N0CFP && N1CFP)
9946     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9947
9948   if (SDValue NewSel = foldBinOpIntoSelect(N))
9949     return NewSel;
9950
9951   if (Options.UnsafeFPMath) {
9952     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9953     if (N1CFP) {
9954       // Compute the reciprocal 1.0 / c2.
9955       const APFloat &N1APF = N1CFP->getValueAPF();
9956       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9957       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9958       // Only do the transform if the reciprocal is a legal fp immediate that
9959       // isn't too nasty (eg NaN, denormal, ...).
9960       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9961           (!LegalOperations ||
9962            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9963            // backend)... we should handle this gracefully after Legalize.
9964            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9965            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9966            TLI.isFPImmLegal(Recip, VT)))
9967         return DAG.getNode(ISD::FMUL, DL, VT, N0,
9968                            DAG.getConstantFP(Recip, DL, VT), Flags);
9969     }
9970
9971     // If this FDIV is part of a reciprocal square root, it may be folded
9972     // into a target-specific square root estimate instruction.
9973     if (N1.getOpcode() == ISD::FSQRT) {
9974       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9975         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9976       }
9977     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9978                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9979       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9980                                           Flags)) {
9981         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9982         AddToWorklist(RV.getNode());
9983         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9984       }
9985     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9986                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9987       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9988                                           Flags)) {
9989         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9990         AddToWorklist(RV.getNode());
9991         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9992       }
9993     } else if (N1.getOpcode() == ISD::FMUL) {
9994       // Look through an FMUL. Even though this won't remove the FDIV directly,
9995       // it's still worthwhile to get rid of the FSQRT if possible.
9996       SDValue SqrtOp;
9997       SDValue OtherOp;
9998       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9999         SqrtOp = N1.getOperand(0);
10000         OtherOp = N1.getOperand(1);
10001       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10002         SqrtOp = N1.getOperand(1);
10003         OtherOp = N1.getOperand(0);
10004       }
10005       if (SqrtOp.getNode()) {
10006         // We found a FSQRT, so try to make this fold:
10007         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10008         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10009           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10010           AddToWorklist(RV.getNode());
10011           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10012         }
10013       }
10014     }
10015
10016     // Fold into a reciprocal estimate and multiply instead of a real divide.
10017     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10018       AddToWorklist(RV.getNode());
10019       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10020     }
10021   }
10022
10023   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10024   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10025     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10026       // Both can be negated for free, check to see if at least one is cheaper
10027       // negated.
10028       if (LHSNeg == 2 || RHSNeg == 2)
10029         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10030                            GetNegatedExpression(N0, DAG, LegalOperations),
10031                            GetNegatedExpression(N1, DAG, LegalOperations),
10032                            Flags);
10033     }
10034   }
10035
10036   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10037     return CombineRepeatedDivisors;
10038
10039   return SDValue();
10040 }
10041
10042 SDValue DAGCombiner::visitFREM(SDNode *N) {
10043   SDValue N0 = N->getOperand(0);
10044   SDValue N1 = N->getOperand(1);
10045   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10046   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10047   EVT VT = N->getValueType(0);
10048
10049   // fold (frem c1, c2) -> fmod(c1,c2)
10050   if (N0CFP && N1CFP)
10051     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10052
10053   if (SDValue NewSel = foldBinOpIntoSelect(N))
10054     return NewSel;
10055
10056   return SDValue();
10057 }
10058
10059 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10060   if (!DAG.getTarget().Options.UnsafeFPMath)
10061     return SDValue();
10062
10063   SDValue N0 = N->getOperand(0);
10064   if (TLI.isFsqrtCheap(N0, DAG))
10065     return SDValue();
10066
10067   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10068   // For now, create a Flags object for use with all unsafe math transforms.
10069   SDNodeFlags Flags;
10070   Flags.setUnsafeAlgebra(true);
10071   return buildSqrtEstimate(N0, Flags);
10072 }
10073
10074 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10075 /// copysign(x, fp_round(y)) -> copysign(x, y)
10076 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10077   SDValue N1 = N->getOperand(1);
10078   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10079        N1.getOpcode() == ISD::FP_ROUND)) {
10080     // Do not optimize out type conversion of f128 type yet.
10081     // For some targets like x86_64, configuration is changed to keep one f128
10082     // value in one SSE register, but instruction selection cannot handle
10083     // FCOPYSIGN on SSE registers yet.
10084     EVT N1VT = N1->getValueType(0);
10085     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10086     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10087   }
10088   return false;
10089 }
10090
10091 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10092   SDValue N0 = N->getOperand(0);
10093   SDValue N1 = N->getOperand(1);
10094   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10095   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10096   EVT VT = N->getValueType(0);
10097
10098   if (N0CFP && N1CFP) // Constant fold
10099     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10100
10101   if (N1CFP) {
10102     const APFloat &V = N1CFP->getValueAPF();
10103     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10104     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10105     if (!V.isNegative()) {
10106       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10107         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10108     } else {
10109       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10110         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10111                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10112     }
10113   }
10114
10115   // copysign(fabs(x), y) -> copysign(x, y)
10116   // copysign(fneg(x), y) -> copysign(x, y)
10117   // copysign(copysign(x,z), y) -> copysign(x, y)
10118   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10119       N0.getOpcode() == ISD::FCOPYSIGN)
10120     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10121
10122   // copysign(x, abs(y)) -> abs(x)
10123   if (N1.getOpcode() == ISD::FABS)
10124     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10125
10126   // copysign(x, copysign(y,z)) -> copysign(x, z)
10127   if (N1.getOpcode() == ISD::FCOPYSIGN)
10128     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10129
10130   // copysign(x, fp_extend(y)) -> copysign(x, y)
10131   // copysign(x, fp_round(y)) -> copysign(x, y)
10132   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10133     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10134
10135   return SDValue();
10136 }
10137
10138 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10139   SDValue N0 = N->getOperand(0);
10140   EVT VT = N->getValueType(0);
10141   EVT OpVT = N0.getValueType();
10142
10143   // fold (sint_to_fp c1) -> c1fp
10144   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10145       // ...but only if the target supports immediate floating-point values
10146       (!LegalOperations ||
10147        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10148     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10149
10150   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10151   // but UINT_TO_FP is legal on this target, try to convert.
10152   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10153       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10154     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10155     if (DAG.SignBitIsZero(N0))
10156       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10157   }
10158
10159   // The next optimizations are desirable only if SELECT_CC can be lowered.
10160   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10161     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10162     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10163         !VT.isVector() &&
10164         (!LegalOperations ||
10165          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10166       SDLoc DL(N);
10167       SDValue Ops[] =
10168         { N0.getOperand(0), N0.getOperand(1),
10169           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10170           N0.getOperand(2) };
10171       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10172     }
10173
10174     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10175     //      (select_cc x, y, 1.0, 0.0,, cc)
10176     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10177         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10178         (!LegalOperations ||
10179          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10180       SDLoc DL(N);
10181       SDValue Ops[] =
10182         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10183           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10184           N0.getOperand(0).getOperand(2) };
10185       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10186     }
10187   }
10188
10189   return SDValue();
10190 }
10191
10192 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10193   SDValue N0 = N->getOperand(0);
10194   EVT VT = N->getValueType(0);
10195   EVT OpVT = N0.getValueType();
10196
10197   // fold (uint_to_fp c1) -> c1fp
10198   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10199       // ...but only if the target supports immediate floating-point values
10200       (!LegalOperations ||
10201        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10202     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10203
10204   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10205   // but SINT_TO_FP is legal on this target, try to convert.
10206   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10207       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10208     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10209     if (DAG.SignBitIsZero(N0))
10210       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10211   }
10212
10213   // The next optimizations are desirable only if SELECT_CC can be lowered.
10214   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10215     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10216
10217     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10218         (!LegalOperations ||
10219          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10220       SDLoc DL(N);
10221       SDValue Ops[] =
10222         { N0.getOperand(0), N0.getOperand(1),
10223           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10224           N0.getOperand(2) };
10225       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10226     }
10227   }
10228
10229   return SDValue();
10230 }
10231
10232 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10233 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10234   SDValue N0 = N->getOperand(0);
10235   EVT VT = N->getValueType(0);
10236
10237   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10238     return SDValue();
10239
10240   SDValue Src = N0.getOperand(0);
10241   EVT SrcVT = Src.getValueType();
10242   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10243   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10244
10245   // We can safely assume the conversion won't overflow the output range,
10246   // because (for example) (uint8_t)18293.f is undefined behavior.
10247
10248   // Since we can assume the conversion won't overflow, our decision as to
10249   // whether the input will fit in the float should depend on the minimum
10250   // of the input range and output range.
10251
10252   // This means this is also safe for a signed input and unsigned output, since
10253   // a negative input would lead to undefined behavior.
10254   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10255   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10256   unsigned ActualSize = std::min(InputSize, OutputSize);
10257   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10258
10259   // We can only fold away the float conversion if the input range can be
10260   // represented exactly in the float range.
10261   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10262     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10263       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10264                                                        : ISD::ZERO_EXTEND;
10265       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10266     }
10267     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10268       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10269     return DAG.getBitcast(VT, Src);
10270   }
10271   return SDValue();
10272 }
10273
10274 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10275   SDValue N0 = N->getOperand(0);
10276   EVT VT = N->getValueType(0);
10277
10278   // fold (fp_to_sint c1fp) -> c1
10279   if (isConstantFPBuildVectorOrConstantFP(N0))
10280     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10281
10282   return FoldIntToFPToInt(N, DAG);
10283 }
10284
10285 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10286   SDValue N0 = N->getOperand(0);
10287   EVT VT = N->getValueType(0);
10288
10289   // fold (fp_to_uint c1fp) -> c1
10290   if (isConstantFPBuildVectorOrConstantFP(N0))
10291     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10292
10293   return FoldIntToFPToInt(N, DAG);
10294 }
10295
10296 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10297   SDValue N0 = N->getOperand(0);
10298   SDValue N1 = N->getOperand(1);
10299   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10300   EVT VT = N->getValueType(0);
10301
10302   // fold (fp_round c1fp) -> c1fp
10303   if (N0CFP)
10304     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10305
10306   // fold (fp_round (fp_extend x)) -> x
10307   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10308     return N0.getOperand(0);
10309
10310   // fold (fp_round (fp_round x)) -> (fp_round x)
10311   if (N0.getOpcode() == ISD::FP_ROUND) {
10312     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10313     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10314
10315     // Skip this folding if it results in an fp_round from f80 to f16.
10316     //
10317     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10318     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10319     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10320     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10321     // x86.
10322     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10323       return SDValue();
10324
10325     // If the first fp_round isn't a value preserving truncation, it might
10326     // introduce a tie in the second fp_round, that wouldn't occur in the
10327     // single-step fp_round we want to fold to.
10328     // In other words, double rounding isn't the same as rounding.
10329     // Also, this is a value preserving truncation iff both fp_round's are.
10330     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10331       SDLoc DL(N);
10332       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10333                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10334     }
10335   }
10336
10337   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10338   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10339     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10340                               N0.getOperand(0), N1);
10341     AddToWorklist(Tmp.getNode());
10342     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10343                        Tmp, N0.getOperand(1));
10344   }
10345
10346   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10347     return NewVSel;
10348
10349   return SDValue();
10350 }
10351
10352 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10353   SDValue N0 = N->getOperand(0);
10354   EVT VT = N->getValueType(0);
10355   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10356   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10357
10358   // fold (fp_round_inreg c1fp) -> c1fp
10359   if (N0CFP && isTypeLegal(EVT)) {
10360     SDLoc DL(N);
10361     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10362     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10363   }
10364
10365   return SDValue();
10366 }
10367
10368 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10369   SDValue N0 = N->getOperand(0);
10370   EVT VT = N->getValueType(0);
10371
10372   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10373   if (N->hasOneUse() &&
10374       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10375     return SDValue();
10376
10377   // fold (fp_extend c1fp) -> c1fp
10378   if (isConstantFPBuildVectorOrConstantFP(N0))
10379     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10380
10381   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10382   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10383       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10384     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10385
10386   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10387   // value of X.
10388   if (N0.getOpcode() == ISD::FP_ROUND
10389       && N0.getConstantOperandVal(1) == 1) {
10390     SDValue In = N0.getOperand(0);
10391     if (In.getValueType() == VT) return In;
10392     if (VT.bitsLT(In.getValueType()))
10393       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10394                          In, N0.getOperand(1));
10395     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10396   }
10397
10398   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10399   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10400        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10401     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10402     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10403                                      LN0->getChain(),
10404                                      LN0->getBasePtr(), N0.getValueType(),
10405                                      LN0->getMemOperand());
10406     CombineTo(N, ExtLoad);
10407     CombineTo(N0.getNode(),
10408               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10409                           N0.getValueType(), ExtLoad,
10410                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10411               ExtLoad.getValue(1));
10412     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10413   }
10414
10415   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10416     return NewVSel;
10417
10418   return SDValue();
10419 }
10420
10421 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10422   SDValue N0 = N->getOperand(0);
10423   EVT VT = N->getValueType(0);
10424
10425   // fold (fceil c1) -> fceil(c1)
10426   if (isConstantFPBuildVectorOrConstantFP(N0))
10427     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10428
10429   return SDValue();
10430 }
10431
10432 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10433   SDValue N0 = N->getOperand(0);
10434   EVT VT = N->getValueType(0);
10435
10436   // fold (ftrunc c1) -> ftrunc(c1)
10437   if (isConstantFPBuildVectorOrConstantFP(N0))
10438     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10439
10440   return SDValue();
10441 }
10442
10443 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10444   SDValue N0 = N->getOperand(0);
10445   EVT VT = N->getValueType(0);
10446
10447   // fold (ffloor c1) -> ffloor(c1)
10448   if (isConstantFPBuildVectorOrConstantFP(N0))
10449     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10450
10451   return SDValue();
10452 }
10453
10454 // FIXME: FNEG and FABS have a lot in common; refactor.
10455 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10456   SDValue N0 = N->getOperand(0);
10457   EVT VT = N->getValueType(0);
10458
10459   // Constant fold FNEG.
10460   if (isConstantFPBuildVectorOrConstantFP(N0))
10461     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10462
10463   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10464                          &DAG.getTarget().Options))
10465     return GetNegatedExpression(N0, DAG, LegalOperations);
10466
10467   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10468   // constant pool values.
10469   if (!TLI.isFNegFree(VT) &&
10470       N0.getOpcode() == ISD::BITCAST &&
10471       N0.getNode()->hasOneUse()) {
10472     SDValue Int = N0.getOperand(0);
10473     EVT IntVT = Int.getValueType();
10474     if (IntVT.isInteger() && !IntVT.isVector()) {
10475       APInt SignMask;
10476       if (N0.getValueType().isVector()) {
10477         // For a vector, get a mask such as 0x80... per scalar element
10478         // and splat it.
10479         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10480         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10481       } else {
10482         // For a scalar, just generate 0x80...
10483         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10484       }
10485       SDLoc DL0(N0);
10486       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10487                         DAG.getConstant(SignMask, DL0, IntVT));
10488       AddToWorklist(Int.getNode());
10489       return DAG.getBitcast(VT, Int);
10490     }
10491   }
10492
10493   // (fneg (fmul c, x)) -> (fmul -c, x)
10494   if (N0.getOpcode() == ISD::FMUL &&
10495       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10496     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10497     if (CFP1) {
10498       APFloat CVal = CFP1->getValueAPF();
10499       CVal.changeSign();
10500       if (Level >= AfterLegalizeDAG &&
10501           (TLI.isFPImmLegal(CVal, VT) ||
10502            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10503         return DAG.getNode(
10504             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10505             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10506             N0->getFlags());
10507     }
10508   }
10509
10510   return SDValue();
10511 }
10512
10513 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10514   SDValue N0 = N->getOperand(0);
10515   SDValue N1 = N->getOperand(1);
10516   EVT VT = N->getValueType(0);
10517   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10518   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10519
10520   if (N0CFP && N1CFP) {
10521     const APFloat &C0 = N0CFP->getValueAPF();
10522     const APFloat &C1 = N1CFP->getValueAPF();
10523     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10524   }
10525
10526   // Canonicalize to constant on RHS.
10527   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10528      !isConstantFPBuildVectorOrConstantFP(N1))
10529     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10530
10531   return SDValue();
10532 }
10533
10534 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10535   SDValue N0 = N->getOperand(0);
10536   SDValue N1 = N->getOperand(1);
10537   EVT VT = N->getValueType(0);
10538   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10539   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10540
10541   if (N0CFP && N1CFP) {
10542     const APFloat &C0 = N0CFP->getValueAPF();
10543     const APFloat &C1 = N1CFP->getValueAPF();
10544     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10545   }
10546
10547   // Canonicalize to constant on RHS.
10548   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10549      !isConstantFPBuildVectorOrConstantFP(N1))
10550     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10551
10552   return SDValue();
10553 }
10554
10555 SDValue DAGCombiner::visitFABS(SDNode *N) {
10556   SDValue N0 = N->getOperand(0);
10557   EVT VT = N->getValueType(0);
10558
10559   // fold (fabs c1) -> fabs(c1)
10560   if (isConstantFPBuildVectorOrConstantFP(N0))
10561     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10562
10563   // fold (fabs (fabs x)) -> (fabs x)
10564   if (N0.getOpcode() == ISD::FABS)
10565     return N->getOperand(0);
10566
10567   // fold (fabs (fneg x)) -> (fabs x)
10568   // fold (fabs (fcopysign x, y)) -> (fabs x)
10569   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10570     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10571
10572   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10573   // constant pool values.
10574   if (!TLI.isFAbsFree(VT) &&
10575       N0.getOpcode() == ISD::BITCAST &&
10576       N0.getNode()->hasOneUse()) {
10577     SDValue Int = N0.getOperand(0);
10578     EVT IntVT = Int.getValueType();
10579     if (IntVT.isInteger() && !IntVT.isVector()) {
10580       APInt SignMask;
10581       if (N0.getValueType().isVector()) {
10582         // For a vector, get a mask such as 0x7f... per scalar element
10583         // and splat it.
10584         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10585         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10586       } else {
10587         // For a scalar, just generate 0x7f...
10588         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10589       }
10590       SDLoc DL(N0);
10591       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10592                         DAG.getConstant(SignMask, DL, IntVT));
10593       AddToWorklist(Int.getNode());
10594       return DAG.getBitcast(N->getValueType(0), Int);
10595     }
10596   }
10597
10598   return SDValue();
10599 }
10600
10601 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10602   SDValue Chain = N->getOperand(0);
10603   SDValue N1 = N->getOperand(1);
10604   SDValue N2 = N->getOperand(2);
10605
10606   // If N is a constant we could fold this into a fallthrough or unconditional
10607   // branch. However that doesn't happen very often in normal code, because
10608   // Instcombine/SimplifyCFG should have handled the available opportunities.
10609   // If we did this folding here, it would be necessary to update the
10610   // MachineBasicBlock CFG, which is awkward.
10611
10612   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10613   // on the target.
10614   if (N1.getOpcode() == ISD::SETCC &&
10615       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10616                                    N1.getOperand(0).getValueType())) {
10617     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10618                        Chain, N1.getOperand(2),
10619                        N1.getOperand(0), N1.getOperand(1), N2);
10620   }
10621
10622   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10623       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10624        (N1.getOperand(0).hasOneUse() &&
10625         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10626     SDNode *Trunc = nullptr;
10627     if (N1.getOpcode() == ISD::TRUNCATE) {
10628       // Look pass the truncate.
10629       Trunc = N1.getNode();
10630       N1 = N1.getOperand(0);
10631     }
10632
10633     // Match this pattern so that we can generate simpler code:
10634     //
10635     //   %a = ...
10636     //   %b = and i32 %a, 2
10637     //   %c = srl i32 %b, 1
10638     //   brcond i32 %c ...
10639     //
10640     // into
10641     //
10642     //   %a = ...
10643     //   %b = and i32 %a, 2
10644     //   %c = setcc eq %b, 0
10645     //   brcond %c ...
10646     //
10647     // This applies only when the AND constant value has one bit set and the
10648     // SRL constant is equal to the log2 of the AND constant. The back-end is
10649     // smart enough to convert the result into a TEST/JMP sequence.
10650     SDValue Op0 = N1.getOperand(0);
10651     SDValue Op1 = N1.getOperand(1);
10652
10653     if (Op0.getOpcode() == ISD::AND &&
10654         Op1.getOpcode() == ISD::Constant) {
10655       SDValue AndOp1 = Op0.getOperand(1);
10656
10657       if (AndOp1.getOpcode() == ISD::Constant) {
10658         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10659
10660         if (AndConst.isPowerOf2() &&
10661             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10662           SDLoc DL(N);
10663           SDValue SetCC =
10664             DAG.getSetCC(DL,
10665                          getSetCCResultType(Op0.getValueType()),
10666                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10667                          ISD::SETNE);
10668
10669           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10670                                           MVT::Other, Chain, SetCC, N2);
10671           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10672           // will convert it back to (X & C1) >> C2.
10673           CombineTo(N, NewBRCond, false);
10674           // Truncate is dead.
10675           if (Trunc)
10676             deleteAndRecombine(Trunc);
10677           // Replace the uses of SRL with SETCC
10678           WorklistRemover DeadNodes(*this);
10679           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10680           deleteAndRecombine(N1.getNode());
10681           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10682         }
10683       }
10684     }
10685
10686     if (Trunc)
10687       // Restore N1 if the above transformation doesn't match.
10688       N1 = N->getOperand(1);
10689   }
10690
10691   // Transform br(xor(x, y)) -> br(x != y)
10692   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10693   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10694     SDNode *TheXor = N1.getNode();
10695     SDValue Op0 = TheXor->getOperand(0);
10696     SDValue Op1 = TheXor->getOperand(1);
10697     if (Op0.getOpcode() == Op1.getOpcode()) {
10698       // Avoid missing important xor optimizations.
10699       if (SDValue Tmp = visitXOR(TheXor)) {
10700         if (Tmp.getNode() != TheXor) {
10701           DEBUG(dbgs() << "\nReplacing.8 ";
10702                 TheXor->dump(&DAG);
10703                 dbgs() << "\nWith: ";
10704                 Tmp.getNode()->dump(&DAG);
10705                 dbgs() << '\n');
10706           WorklistRemover DeadNodes(*this);
10707           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10708           deleteAndRecombine(TheXor);
10709           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10710                              MVT::Other, Chain, Tmp, N2);
10711         }
10712
10713         // visitXOR has changed XOR's operands or replaced the XOR completely,
10714         // bail out.
10715         return SDValue(N, 0);
10716       }
10717     }
10718
10719     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10720       bool Equal = false;
10721       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10722           Op0.getOpcode() == ISD::XOR) {
10723         TheXor = Op0.getNode();
10724         Equal = true;
10725       }
10726
10727       EVT SetCCVT = N1.getValueType();
10728       if (LegalTypes)
10729         SetCCVT = getSetCCResultType(SetCCVT);
10730       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10731                                    SetCCVT,
10732                                    Op0, Op1,
10733                                    Equal ? ISD::SETEQ : ISD::SETNE);
10734       // Replace the uses of XOR with SETCC
10735       WorklistRemover DeadNodes(*this);
10736       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10737       deleteAndRecombine(N1.getNode());
10738       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10739                          MVT::Other, Chain, SetCC, N2);
10740     }
10741   }
10742
10743   return SDValue();
10744 }
10745
10746 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10747 //
10748 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10749   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10750   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10751
10752   // If N is a constant we could fold this into a fallthrough or unconditional
10753   // branch. However that doesn't happen very often in normal code, because
10754   // Instcombine/SimplifyCFG should have handled the available opportunities.
10755   // If we did this folding here, it would be necessary to update the
10756   // MachineBasicBlock CFG, which is awkward.
10757
10758   // Use SimplifySetCC to simplify SETCC's.
10759   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10760                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10761                                false);
10762   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10763
10764   // fold to a simpler setcc
10765   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10766     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10767                        N->getOperand(0), Simp.getOperand(2),
10768                        Simp.getOperand(0), Simp.getOperand(1),
10769                        N->getOperand(4));
10770
10771   return SDValue();
10772 }
10773
10774 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10775 /// and that N may be folded in the load / store addressing mode.
10776 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10777                                     SelectionDAG &DAG,
10778                                     const TargetLowering &TLI) {
10779   EVT VT;
10780   unsigned AS;
10781
10782   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10783     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10784       return false;
10785     VT = LD->getMemoryVT();
10786     AS = LD->getAddressSpace();
10787   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10788     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10789       return false;
10790     VT = ST->getMemoryVT();
10791     AS = ST->getAddressSpace();
10792   } else
10793     return false;
10794
10795   TargetLowering::AddrMode AM;
10796   if (N->getOpcode() == ISD::ADD) {
10797     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10798     if (Offset)
10799       // [reg +/- imm]
10800       AM.BaseOffs = Offset->getSExtValue();
10801     else
10802       // [reg +/- reg]
10803       AM.Scale = 1;
10804   } else if (N->getOpcode() == ISD::SUB) {
10805     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10806     if (Offset)
10807       // [reg +/- imm]
10808       AM.BaseOffs = -Offset->getSExtValue();
10809     else
10810       // [reg +/- reg]
10811       AM.Scale = 1;
10812   } else
10813     return false;
10814
10815   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10816                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10817 }
10818
10819 /// Try turning a load/store into a pre-indexed load/store when the base
10820 /// pointer is an add or subtract and it has other uses besides the load/store.
10821 /// After the transformation, the new indexed load/store has effectively folded
10822 /// the add/subtract in and all of its other uses are redirected to the
10823 /// new load/store.
10824 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10825   if (Level < AfterLegalizeDAG)
10826     return false;
10827
10828   bool isLoad = true;
10829   SDValue Ptr;
10830   EVT VT;
10831   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10832     if (LD->isIndexed())
10833       return false;
10834     VT = LD->getMemoryVT();
10835     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10836         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10837       return false;
10838     Ptr = LD->getBasePtr();
10839   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10840     if (ST->isIndexed())
10841       return false;
10842     VT = ST->getMemoryVT();
10843     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10844         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10845       return false;
10846     Ptr = ST->getBasePtr();
10847     isLoad = false;
10848   } else {
10849     return false;
10850   }
10851
10852   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10853   // out.  There is no reason to make this a preinc/predec.
10854   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10855       Ptr.getNode()->hasOneUse())
10856     return false;
10857
10858   // Ask the target to do addressing mode selection.
10859   SDValue BasePtr;
10860   SDValue Offset;
10861   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10862   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10863     return false;
10864
10865   // Backends without true r+i pre-indexed forms may need to pass a
10866   // constant base with a variable offset so that constant coercion
10867   // will work with the patterns in canonical form.
10868   bool Swapped = false;
10869   if (isa<ConstantSDNode>(BasePtr)) {
10870     std::swap(BasePtr, Offset);
10871     Swapped = true;
10872   }
10873
10874   // Don't create a indexed load / store with zero offset.
10875   if (isNullConstant(Offset))
10876     return false;
10877
10878   // Try turning it into a pre-indexed load / store except when:
10879   // 1) The new base ptr is a frame index.
10880   // 2) If N is a store and the new base ptr is either the same as or is a
10881   //    predecessor of the value being stored.
10882   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10883   //    that would create a cycle.
10884   // 4) All uses are load / store ops that use it as old base ptr.
10885
10886   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10887   // (plus the implicit offset) to a register to preinc anyway.
10888   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10889     return false;
10890
10891   // Check #2.
10892   if (!isLoad) {
10893     SDValue Val = cast<StoreSDNode>(N)->getValue();
10894     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10895       return false;
10896   }
10897
10898   // Caches for hasPredecessorHelper.
10899   SmallPtrSet<const SDNode *, 32> Visited;
10900   SmallVector<const SDNode *, 16> Worklist;
10901   Worklist.push_back(N);
10902
10903   // If the offset is a constant, there may be other adds of constants that
10904   // can be folded with this one. We should do this to avoid having to keep
10905   // a copy of the original base pointer.
10906   SmallVector<SDNode *, 16> OtherUses;
10907   if (isa<ConstantSDNode>(Offset))
10908     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10909                               UE = BasePtr.getNode()->use_end();
10910          UI != UE; ++UI) {
10911       SDUse &Use = UI.getUse();
10912       // Skip the use that is Ptr and uses of other results from BasePtr's
10913       // node (important for nodes that return multiple results).
10914       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10915         continue;
10916
10917       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10918         continue;
10919
10920       if (Use.getUser()->getOpcode() != ISD::ADD &&
10921           Use.getUser()->getOpcode() != ISD::SUB) {
10922         OtherUses.clear();
10923         break;
10924       }
10925
10926       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10927       if (!isa<ConstantSDNode>(Op1)) {
10928         OtherUses.clear();
10929         break;
10930       }
10931
10932       // FIXME: In some cases, we can be smarter about this.
10933       if (Op1.getValueType() != Offset.getValueType()) {
10934         OtherUses.clear();
10935         break;
10936       }
10937
10938       OtherUses.push_back(Use.getUser());
10939     }
10940
10941   if (Swapped)
10942     std::swap(BasePtr, Offset);
10943
10944   // Now check for #3 and #4.
10945   bool RealUse = false;
10946
10947   for (SDNode *Use : Ptr.getNode()->uses()) {
10948     if (Use == N)
10949       continue;
10950     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10951       return false;
10952
10953     // If Ptr may be folded in addressing mode of other use, then it's
10954     // not profitable to do this transformation.
10955     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10956       RealUse = true;
10957   }
10958
10959   if (!RealUse)
10960     return false;
10961
10962   SDValue Result;
10963   if (isLoad)
10964     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10965                                 BasePtr, Offset, AM);
10966   else
10967     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10968                                  BasePtr, Offset, AM);
10969   ++PreIndexedNodes;
10970   ++NodesCombined;
10971   DEBUG(dbgs() << "\nReplacing.4 ";
10972         N->dump(&DAG);
10973         dbgs() << "\nWith: ";
10974         Result.getNode()->dump(&DAG);
10975         dbgs() << '\n');
10976   WorklistRemover DeadNodes(*this);
10977   if (isLoad) {
10978     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10979     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10980   } else {
10981     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10982   }
10983
10984   // Finally, since the node is now dead, remove it from the graph.
10985   deleteAndRecombine(N);
10986
10987   if (Swapped)
10988     std::swap(BasePtr, Offset);
10989
10990   // Replace other uses of BasePtr that can be updated to use Ptr
10991   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10992     unsigned OffsetIdx = 1;
10993     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10994       OffsetIdx = 0;
10995     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10996            BasePtr.getNode() && "Expected BasePtr operand");
10997
10998     // We need to replace ptr0 in the following expression:
10999     //   x0 * offset0 + y0 * ptr0 = t0
11000     // knowing that
11001     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11002     //
11003     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11004     // indexed load/store and the expresion that needs to be re-written.
11005     //
11006     // Therefore, we have:
11007     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11008
11009     ConstantSDNode *CN =
11010       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11011     int X0, X1, Y0, Y1;
11012     const APInt &Offset0 = CN->getAPIntValue();
11013     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11014
11015     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11016     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11017     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11018     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11019
11020     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11021
11022     APInt CNV = Offset0;
11023     if (X0 < 0) CNV = -CNV;
11024     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11025     else CNV = CNV - Offset1;
11026
11027     SDLoc DL(OtherUses[i]);
11028
11029     // We can now generate the new expression.
11030     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11031     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11032
11033     SDValue NewUse = DAG.getNode(Opcode,
11034                                  DL,
11035                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11036     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11037     deleteAndRecombine(OtherUses[i]);
11038   }
11039
11040   // Replace the uses of Ptr with uses of the updated base value.
11041   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11042   deleteAndRecombine(Ptr.getNode());
11043
11044   return true;
11045 }
11046
11047 /// Try to combine a load/store with a add/sub of the base pointer node into a
11048 /// post-indexed load/store. The transformation folded the add/subtract into the
11049 /// new indexed load/store effectively and all of its uses are redirected to the
11050 /// new load/store.
11051 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11052   if (Level < AfterLegalizeDAG)
11053     return false;
11054
11055   bool isLoad = true;
11056   SDValue Ptr;
11057   EVT VT;
11058   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11059     if (LD->isIndexed())
11060       return false;
11061     VT = LD->getMemoryVT();
11062     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11063         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11064       return false;
11065     Ptr = LD->getBasePtr();
11066   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11067     if (ST->isIndexed())
11068       return false;
11069     VT = ST->getMemoryVT();
11070     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11071         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11072       return false;
11073     Ptr = ST->getBasePtr();
11074     isLoad = false;
11075   } else {
11076     return false;
11077   }
11078
11079   if (Ptr.getNode()->hasOneUse())
11080     return false;
11081
11082   for (SDNode *Op : Ptr.getNode()->uses()) {
11083     if (Op == N ||
11084         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11085       continue;
11086
11087     SDValue BasePtr;
11088     SDValue Offset;
11089     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11090     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11091       // Don't create a indexed load / store with zero offset.
11092       if (isNullConstant(Offset))
11093         continue;
11094
11095       // Try turning it into a post-indexed load / store except when
11096       // 1) All uses are load / store ops that use it as base ptr (and
11097       //    it may be folded as addressing mmode).
11098       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11099       //    nor a successor of N. Otherwise, if Op is folded that would
11100       //    create a cycle.
11101
11102       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11103         continue;
11104
11105       // Check for #1.
11106       bool TryNext = false;
11107       for (SDNode *Use : BasePtr.getNode()->uses()) {
11108         if (Use == Ptr.getNode())
11109           continue;
11110
11111         // If all the uses are load / store addresses, then don't do the
11112         // transformation.
11113         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11114           bool RealUse = false;
11115           for (SDNode *UseUse : Use->uses()) {
11116             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11117               RealUse = true;
11118           }
11119
11120           if (!RealUse) {
11121             TryNext = true;
11122             break;
11123           }
11124         }
11125       }
11126
11127       if (TryNext)
11128         continue;
11129
11130       // Check for #2
11131       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11132         SDValue Result = isLoad
11133           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11134                                BasePtr, Offset, AM)
11135           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11136                                 BasePtr, Offset, AM);
11137         ++PostIndexedNodes;
11138         ++NodesCombined;
11139         DEBUG(dbgs() << "\nReplacing.5 ";
11140               N->dump(&DAG);
11141               dbgs() << "\nWith: ";
11142               Result.getNode()->dump(&DAG);
11143               dbgs() << '\n');
11144         WorklistRemover DeadNodes(*this);
11145         if (isLoad) {
11146           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11147           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11148         } else {
11149           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11150         }
11151
11152         // Finally, since the node is now dead, remove it from the graph.
11153         deleteAndRecombine(N);
11154
11155         // Replace the uses of Use with uses of the updated base value.
11156         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11157                                       Result.getValue(isLoad ? 1 : 0));
11158         deleteAndRecombine(Op);
11159         return true;
11160       }
11161     }
11162   }
11163
11164   return false;
11165 }
11166
11167 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11168 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11169   ISD::MemIndexedMode AM = LD->getAddressingMode();
11170   assert(AM != ISD::UNINDEXED);
11171   SDValue BP = LD->getOperand(1);
11172   SDValue Inc = LD->getOperand(2);
11173
11174   // Some backends use TargetConstants for load offsets, but don't expect
11175   // TargetConstants in general ADD nodes. We can convert these constants into
11176   // regular Constants (if the constant is not opaque).
11177   assert((Inc.getOpcode() != ISD::TargetConstant ||
11178           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11179          "Cannot split out indexing using opaque target constants");
11180   if (Inc.getOpcode() == ISD::TargetConstant) {
11181     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11182     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11183                           ConstInc->getValueType(0));
11184   }
11185
11186   unsigned Opc =
11187       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11188   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11189 }
11190
11191 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11192   LoadSDNode *LD  = cast<LoadSDNode>(N);
11193   SDValue Chain = LD->getChain();
11194   SDValue Ptr   = LD->getBasePtr();
11195
11196   // If load is not volatile and there are no uses of the loaded value (and
11197   // the updated indexed value in case of indexed loads), change uses of the
11198   // chain value into uses of the chain input (i.e. delete the dead load).
11199   if (!LD->isVolatile()) {
11200     if (N->getValueType(1) == MVT::Other) {
11201       // Unindexed loads.
11202       if (!N->hasAnyUseOfValue(0)) {
11203         // It's not safe to use the two value CombineTo variant here. e.g.
11204         // v1, chain2 = load chain1, loc
11205         // v2, chain3 = load chain2, loc
11206         // v3         = add v2, c
11207         // Now we replace use of chain2 with chain1.  This makes the second load
11208         // isomorphic to the one we are deleting, and thus makes this load live.
11209         DEBUG(dbgs() << "\nReplacing.6 ";
11210               N->dump(&DAG);
11211               dbgs() << "\nWith chain: ";
11212               Chain.getNode()->dump(&DAG);
11213               dbgs() << "\n");
11214         WorklistRemover DeadNodes(*this);
11215         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11216         AddUsersToWorklist(Chain.getNode());
11217         if (N->use_empty())
11218           deleteAndRecombine(N);
11219
11220         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11221       }
11222     } else {
11223       // Indexed loads.
11224       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11225
11226       // If this load has an opaque TargetConstant offset, then we cannot split
11227       // the indexing into an add/sub directly (that TargetConstant may not be
11228       // valid for a different type of node, and we cannot convert an opaque
11229       // target constant into a regular constant).
11230       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11231                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11232
11233       if (!N->hasAnyUseOfValue(0) &&
11234           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11235         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11236         SDValue Index;
11237         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11238           Index = SplitIndexingFromLoad(LD);
11239           // Try to fold the base pointer arithmetic into subsequent loads and
11240           // stores.
11241           AddUsersToWorklist(N);
11242         } else
11243           Index = DAG.getUNDEF(N->getValueType(1));
11244         DEBUG(dbgs() << "\nReplacing.7 ";
11245               N->dump(&DAG);
11246               dbgs() << "\nWith: ";
11247               Undef.getNode()->dump(&DAG);
11248               dbgs() << " and 2 other values\n");
11249         WorklistRemover DeadNodes(*this);
11250         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11251         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11252         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11253         deleteAndRecombine(N);
11254         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11255       }
11256     }
11257   }
11258
11259   // If this load is directly stored, replace the load value with the stored
11260   // value.
11261   // TODO: Handle store large -> read small portion.
11262   // TODO: Handle TRUNCSTORE/LOADEXT
11263   if (OptLevel != CodeGenOpt::None &&
11264       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11265     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11266       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11267       if (PrevST->getBasePtr() == Ptr &&
11268           PrevST->getValue().getValueType() == N->getValueType(0))
11269         return CombineTo(N, PrevST->getOperand(1), Chain);
11270     }
11271   }
11272
11273   // Try to infer better alignment information than the load already has.
11274   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11275     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11276       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11277         SDValue NewLoad = DAG.getExtLoad(
11278             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11279             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11280             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11281         if (NewLoad.getNode() != N)
11282           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11283       }
11284     }
11285   }
11286
11287   if (LD->isUnindexed()) {
11288     // Walk up chain skipping non-aliasing memory nodes.
11289     SDValue BetterChain = FindBetterChain(N, Chain);
11290
11291     // If there is a better chain.
11292     if (Chain != BetterChain) {
11293       SDValue ReplLoad;
11294
11295       // Replace the chain to void dependency.
11296       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11297         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11298                                BetterChain, Ptr, LD->getMemOperand());
11299       } else {
11300         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11301                                   LD->getValueType(0),
11302                                   BetterChain, Ptr, LD->getMemoryVT(),
11303                                   LD->getMemOperand());
11304       }
11305
11306       // Create token factor to keep old chain connected.
11307       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11308                                   MVT::Other, Chain, ReplLoad.getValue(1));
11309
11310       // Make sure the new and old chains are cleaned up.
11311       AddToWorklist(Token.getNode());
11312
11313       // Replace uses with load result and token factor. Don't add users
11314       // to work list.
11315       return CombineTo(N, ReplLoad.getValue(0), Token, false);
11316     }
11317   }
11318
11319   // Try transforming N to an indexed load.
11320   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11321     return SDValue(N, 0);
11322
11323   // Try to slice up N to more direct loads if the slices are mapped to
11324   // different register banks or pairing can take place.
11325   if (SliceUpLoad(N))
11326     return SDValue(N, 0);
11327
11328   return SDValue();
11329 }
11330
11331 namespace {
11332 /// \brief Helper structure used to slice a load in smaller loads.
11333 /// Basically a slice is obtained from the following sequence:
11334 /// Origin = load Ty1, Base
11335 /// Shift = srl Ty1 Origin, CstTy Amount
11336 /// Inst = trunc Shift to Ty2
11337 ///
11338 /// Then, it will be rewriten into:
11339 /// Slice = load SliceTy, Base + SliceOffset
11340 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11341 ///
11342 /// SliceTy is deduced from the number of bits that are actually used to
11343 /// build Inst.
11344 struct LoadedSlice {
11345   /// \brief Helper structure used to compute the cost of a slice.
11346   struct Cost {
11347     /// Are we optimizing for code size.
11348     bool ForCodeSize;
11349     /// Various cost.
11350     unsigned Loads;
11351     unsigned Truncates;
11352     unsigned CrossRegisterBanksCopies;
11353     unsigned ZExts;
11354     unsigned Shift;
11355
11356     Cost(bool ForCodeSize = false)
11357         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11358           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11359
11360     /// \brief Get the cost of one isolated slice.
11361     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11362         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11363           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11364       EVT TruncType = LS.Inst->getValueType(0);
11365       EVT LoadedType = LS.getLoadedType();
11366       if (TruncType != LoadedType &&
11367           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11368         ZExts = 1;
11369     }
11370
11371     /// \brief Account for slicing gain in the current cost.
11372     /// Slicing provide a few gains like removing a shift or a
11373     /// truncate. This method allows to grow the cost of the original
11374     /// load with the gain from this slice.
11375     void addSliceGain(const LoadedSlice &LS) {
11376       // Each slice saves a truncate.
11377       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11378       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11379                               LS.Inst->getValueType(0)))
11380         ++Truncates;
11381       // If there is a shift amount, this slice gets rid of it.
11382       if (LS.Shift)
11383         ++Shift;
11384       // If this slice can merge a cross register bank copy, account for it.
11385       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11386         ++CrossRegisterBanksCopies;
11387     }
11388
11389     Cost &operator+=(const Cost &RHS) {
11390       Loads += RHS.Loads;
11391       Truncates += RHS.Truncates;
11392       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11393       ZExts += RHS.ZExts;
11394       Shift += RHS.Shift;
11395       return *this;
11396     }
11397
11398     bool operator==(const Cost &RHS) const {
11399       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11400              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11401              ZExts == RHS.ZExts && Shift == RHS.Shift;
11402     }
11403
11404     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11405
11406     bool operator<(const Cost &RHS) const {
11407       // Assume cross register banks copies are as expensive as loads.
11408       // FIXME: Do we want some more target hooks?
11409       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11410       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11411       // Unless we are optimizing for code size, consider the
11412       // expensive operation first.
11413       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11414         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11415       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11416              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11417     }
11418
11419     bool operator>(const Cost &RHS) const { return RHS < *this; }
11420
11421     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11422
11423     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11424   };
11425   // The last instruction that represent the slice. This should be a
11426   // truncate instruction.
11427   SDNode *Inst;
11428   // The original load instruction.
11429   LoadSDNode *Origin;
11430   // The right shift amount in bits from the original load.
11431   unsigned Shift;
11432   // The DAG from which Origin came from.
11433   // This is used to get some contextual information about legal types, etc.
11434   SelectionDAG *DAG;
11435
11436   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11437               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11438       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11439
11440   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11441   /// \return Result is \p BitWidth and has used bits set to 1 and
11442   ///         not used bits set to 0.
11443   APInt getUsedBits() const {
11444     // Reproduce the trunc(lshr) sequence:
11445     // - Start from the truncated value.
11446     // - Zero extend to the desired bit width.
11447     // - Shift left.
11448     assert(Origin && "No original load to compare against.");
11449     unsigned BitWidth = Origin->getValueSizeInBits(0);
11450     assert(Inst && "This slice is not bound to an instruction");
11451     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11452            "Extracted slice is bigger than the whole type!");
11453     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11454     UsedBits.setAllBits();
11455     UsedBits = UsedBits.zext(BitWidth);
11456     UsedBits <<= Shift;
11457     return UsedBits;
11458   }
11459
11460   /// \brief Get the size of the slice to be loaded in bytes.
11461   unsigned getLoadedSize() const {
11462     unsigned SliceSize = getUsedBits().countPopulation();
11463     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11464     return SliceSize / 8;
11465   }
11466
11467   /// \brief Get the type that will be loaded for this slice.
11468   /// Note: This may not be the final type for the slice.
11469   EVT getLoadedType() const {
11470     assert(DAG && "Missing context");
11471     LLVMContext &Ctxt = *DAG->getContext();
11472     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11473   }
11474
11475   /// \brief Get the alignment of the load used for this slice.
11476   unsigned getAlignment() const {
11477     unsigned Alignment = Origin->getAlignment();
11478     unsigned Offset = getOffsetFromBase();
11479     if (Offset != 0)
11480       Alignment = MinAlign(Alignment, Alignment + Offset);
11481     return Alignment;
11482   }
11483
11484   /// \brief Check if this slice can be rewritten with legal operations.
11485   bool isLegal() const {
11486     // An invalid slice is not legal.
11487     if (!Origin || !Inst || !DAG)
11488       return false;
11489
11490     // Offsets are for indexed load only, we do not handle that.
11491     if (!Origin->getOffset().isUndef())
11492       return false;
11493
11494     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11495
11496     // Check that the type is legal.
11497     EVT SliceType = getLoadedType();
11498     if (!TLI.isTypeLegal(SliceType))
11499       return false;
11500
11501     // Check that the load is legal for this type.
11502     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11503       return false;
11504
11505     // Check that the offset can be computed.
11506     // 1. Check its type.
11507     EVT PtrType = Origin->getBasePtr().getValueType();
11508     if (PtrType == MVT::Untyped || PtrType.isExtended())
11509       return false;
11510
11511     // 2. Check that it fits in the immediate.
11512     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11513       return false;
11514
11515     // 3. Check that the computation is legal.
11516     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11517       return false;
11518
11519     // Check that the zext is legal if it needs one.
11520     EVT TruncateType = Inst->getValueType(0);
11521     if (TruncateType != SliceType &&
11522         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11523       return false;
11524
11525     return true;
11526   }
11527
11528   /// \brief Get the offset in bytes of this slice in the original chunk of
11529   /// bits.
11530   /// \pre DAG != nullptr.
11531   uint64_t getOffsetFromBase() const {
11532     assert(DAG && "Missing context.");
11533     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11534     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11535     uint64_t Offset = Shift / 8;
11536     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11537     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11538            "The size of the original loaded type is not a multiple of a"
11539            " byte.");
11540     // If Offset is bigger than TySizeInBytes, it means we are loading all
11541     // zeros. This should have been optimized before in the process.
11542     assert(TySizeInBytes > Offset &&
11543            "Invalid shift amount for given loaded size");
11544     if (IsBigEndian)
11545       Offset = TySizeInBytes - Offset - getLoadedSize();
11546     return Offset;
11547   }
11548
11549   /// \brief Generate the sequence of instructions to load the slice
11550   /// represented by this object and redirect the uses of this slice to
11551   /// this new sequence of instructions.
11552   /// \pre this->Inst && this->Origin are valid Instructions and this
11553   /// object passed the legal check: LoadedSlice::isLegal returned true.
11554   /// \return The last instruction of the sequence used to load the slice.
11555   SDValue loadSlice() const {
11556     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11557     const SDValue &OldBaseAddr = Origin->getBasePtr();
11558     SDValue BaseAddr = OldBaseAddr;
11559     // Get the offset in that chunk of bytes w.r.t. the endianness.
11560     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11561     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11562     if (Offset) {
11563       // BaseAddr = BaseAddr + Offset.
11564       EVT ArithType = BaseAddr.getValueType();
11565       SDLoc DL(Origin);
11566       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11567                               DAG->getConstant(Offset, DL, ArithType));
11568     }
11569
11570     // Create the type of the loaded slice according to its size.
11571     EVT SliceType = getLoadedType();
11572
11573     // Create the load for the slice.
11574     SDValue LastInst =
11575         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11576                      Origin->getPointerInfo().getWithOffset(Offset),
11577                      getAlignment(), Origin->getMemOperand()->getFlags());
11578     // If the final type is not the same as the loaded type, this means that
11579     // we have to pad with zero. Create a zero extend for that.
11580     EVT FinalType = Inst->getValueType(0);
11581     if (SliceType != FinalType)
11582       LastInst =
11583           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11584     return LastInst;
11585   }
11586
11587   /// \brief Check if this slice can be merged with an expensive cross register
11588   /// bank copy. E.g.,
11589   /// i = load i32
11590   /// f = bitcast i32 i to float
11591   bool canMergeExpensiveCrossRegisterBankCopy() const {
11592     if (!Inst || !Inst->hasOneUse())
11593       return false;
11594     SDNode *Use = *Inst->use_begin();
11595     if (Use->getOpcode() != ISD::BITCAST)
11596       return false;
11597     assert(DAG && "Missing context");
11598     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11599     EVT ResVT = Use->getValueType(0);
11600     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11601     const TargetRegisterClass *ArgRC =
11602         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11603     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11604       return false;
11605
11606     // At this point, we know that we perform a cross-register-bank copy.
11607     // Check if it is expensive.
11608     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11609     // Assume bitcasts are cheap, unless both register classes do not
11610     // explicitly share a common sub class.
11611     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11612       return false;
11613
11614     // Check if it will be merged with the load.
11615     // 1. Check the alignment constraint.
11616     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11617         ResVT.getTypeForEVT(*DAG->getContext()));
11618
11619     if (RequiredAlignment > getAlignment())
11620       return false;
11621
11622     // 2. Check that the load is a legal operation for that type.
11623     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11624       return false;
11625
11626     // 3. Check that we do not have a zext in the way.
11627     if (Inst->getValueType(0) != getLoadedType())
11628       return false;
11629
11630     return true;
11631   }
11632 };
11633 }
11634
11635 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11636 /// \p UsedBits looks like 0..0 1..1 0..0.
11637 static bool areUsedBitsDense(const APInt &UsedBits) {
11638   // If all the bits are one, this is dense!
11639   if (UsedBits.isAllOnesValue())
11640     return true;
11641
11642   // Get rid of the unused bits on the right.
11643   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11644   // Get rid of the unused bits on the left.
11645   if (NarrowedUsedBits.countLeadingZeros())
11646     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11647   // Check that the chunk of bits is completely used.
11648   return NarrowedUsedBits.isAllOnesValue();
11649 }
11650
11651 /// \brief Check whether or not \p First and \p Second are next to each other
11652 /// in memory. This means that there is no hole between the bits loaded
11653 /// by \p First and the bits loaded by \p Second.
11654 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11655                                      const LoadedSlice &Second) {
11656   assert(First.Origin == Second.Origin && First.Origin &&
11657          "Unable to match different memory origins.");
11658   APInt UsedBits = First.getUsedBits();
11659   assert((UsedBits & Second.getUsedBits()) == 0 &&
11660          "Slices are not supposed to overlap.");
11661   UsedBits |= Second.getUsedBits();
11662   return areUsedBitsDense(UsedBits);
11663 }
11664
11665 /// \brief Adjust the \p GlobalLSCost according to the target
11666 /// paring capabilities and the layout of the slices.
11667 /// \pre \p GlobalLSCost should account for at least as many loads as
11668 /// there is in the slices in \p LoadedSlices.
11669 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11670                                  LoadedSlice::Cost &GlobalLSCost) {
11671   unsigned NumberOfSlices = LoadedSlices.size();
11672   // If there is less than 2 elements, no pairing is possible.
11673   if (NumberOfSlices < 2)
11674     return;
11675
11676   // Sort the slices so that elements that are likely to be next to each
11677   // other in memory are next to each other in the list.
11678   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11679             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11680     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11681     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11682   });
11683   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11684   // First (resp. Second) is the first (resp. Second) potentially candidate
11685   // to be placed in a paired load.
11686   const LoadedSlice *First = nullptr;
11687   const LoadedSlice *Second = nullptr;
11688   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11689                 // Set the beginning of the pair.
11690                                                            First = Second) {
11691
11692     Second = &LoadedSlices[CurrSlice];
11693
11694     // If First is NULL, it means we start a new pair.
11695     // Get to the next slice.
11696     if (!First)
11697       continue;
11698
11699     EVT LoadedType = First->getLoadedType();
11700
11701     // If the types of the slices are different, we cannot pair them.
11702     if (LoadedType != Second->getLoadedType())
11703       continue;
11704
11705     // Check if the target supplies paired loads for this type.
11706     unsigned RequiredAlignment = 0;
11707     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11708       // move to the next pair, this type is hopeless.
11709       Second = nullptr;
11710       continue;
11711     }
11712     // Check if we meet the alignment requirement.
11713     if (RequiredAlignment > First->getAlignment())
11714       continue;
11715
11716     // Check that both loads are next to each other in memory.
11717     if (!areSlicesNextToEachOther(*First, *Second))
11718       continue;
11719
11720     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11721     --GlobalLSCost.Loads;
11722     // Move to the next pair.
11723     Second = nullptr;
11724   }
11725 }
11726
11727 /// \brief Check the profitability of all involved LoadedSlice.
11728 /// Currently, it is considered profitable if there is exactly two
11729 /// involved slices (1) which are (2) next to each other in memory, and
11730 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11731 ///
11732 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11733 /// the elements themselves.
11734 ///
11735 /// FIXME: When the cost model will be mature enough, we can relax
11736 /// constraints (1) and (2).
11737 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11738                                 const APInt &UsedBits, bool ForCodeSize) {
11739   unsigned NumberOfSlices = LoadedSlices.size();
11740   if (StressLoadSlicing)
11741     return NumberOfSlices > 1;
11742
11743   // Check (1).
11744   if (NumberOfSlices != 2)
11745     return false;
11746
11747   // Check (2).
11748   if (!areUsedBitsDense(UsedBits))
11749     return false;
11750
11751   // Check (3).
11752   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11753   // The original code has one big load.
11754   OrigCost.Loads = 1;
11755   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11756     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11757     // Accumulate the cost of all the slices.
11758     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11759     GlobalSlicingCost += SliceCost;
11760
11761     // Account as cost in the original configuration the gain obtained
11762     // with the current slices.
11763     OrigCost.addSliceGain(LS);
11764   }
11765
11766   // If the target supports paired load, adjust the cost accordingly.
11767   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11768   return OrigCost > GlobalSlicingCost;
11769 }
11770
11771 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11772 /// operations, split it in the various pieces being extracted.
11773 ///
11774 /// This sort of thing is introduced by SROA.
11775 /// This slicing takes care not to insert overlapping loads.
11776 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11777 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11778   if (Level < AfterLegalizeDAG)
11779     return false;
11780
11781   LoadSDNode *LD = cast<LoadSDNode>(N);
11782   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11783       !LD->getValueType(0).isInteger())
11784     return false;
11785
11786   // Keep track of already used bits to detect overlapping values.
11787   // In that case, we will just abort the transformation.
11788   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11789
11790   SmallVector<LoadedSlice, 4> LoadedSlices;
11791
11792   // Check if this load is used as several smaller chunks of bits.
11793   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11794   // of computation for each trunc.
11795   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11796        UI != UIEnd; ++UI) {
11797     // Skip the uses of the chain.
11798     if (UI.getUse().getResNo() != 0)
11799       continue;
11800
11801     SDNode *User = *UI;
11802     unsigned Shift = 0;
11803
11804     // Check if this is a trunc(lshr).
11805     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11806         isa<ConstantSDNode>(User->getOperand(1))) {
11807       Shift = User->getConstantOperandVal(1);
11808       User = *User->use_begin();
11809     }
11810
11811     // At this point, User is a Truncate, iff we encountered, trunc or
11812     // trunc(lshr).
11813     if (User->getOpcode() != ISD::TRUNCATE)
11814       return false;
11815
11816     // The width of the type must be a power of 2 and greater than 8-bits.
11817     // Otherwise the load cannot be represented in LLVM IR.
11818     // Moreover, if we shifted with a non-8-bits multiple, the slice
11819     // will be across several bytes. We do not support that.
11820     unsigned Width = User->getValueSizeInBits(0);
11821     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11822       return 0;
11823
11824     // Build the slice for this chain of computations.
11825     LoadedSlice LS(User, LD, Shift, &DAG);
11826     APInt CurrentUsedBits = LS.getUsedBits();
11827
11828     // Check if this slice overlaps with another.
11829     if ((CurrentUsedBits & UsedBits) != 0)
11830       return false;
11831     // Update the bits used globally.
11832     UsedBits |= CurrentUsedBits;
11833
11834     // Check if the new slice would be legal.
11835     if (!LS.isLegal())
11836       return false;
11837
11838     // Record the slice.
11839     LoadedSlices.push_back(LS);
11840   }
11841
11842   // Abort slicing if it does not seem to be profitable.
11843   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11844     return false;
11845
11846   ++SlicedLoads;
11847
11848   // Rewrite each chain to use an independent load.
11849   // By construction, each chain can be represented by a unique load.
11850
11851   // Prepare the argument for the new token factor for all the slices.
11852   SmallVector<SDValue, 8> ArgChains;
11853   for (SmallVectorImpl<LoadedSlice>::const_iterator
11854            LSIt = LoadedSlices.begin(),
11855            LSItEnd = LoadedSlices.end();
11856        LSIt != LSItEnd; ++LSIt) {
11857     SDValue SliceInst = LSIt->loadSlice();
11858     CombineTo(LSIt->Inst, SliceInst, true);
11859     if (SliceInst.getOpcode() != ISD::LOAD)
11860       SliceInst = SliceInst.getOperand(0);
11861     assert(SliceInst->getOpcode() == ISD::LOAD &&
11862            "It takes more than a zext to get to the loaded slice!!");
11863     ArgChains.push_back(SliceInst.getValue(1));
11864   }
11865
11866   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11867                               ArgChains);
11868   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11869   AddToWorklist(Chain.getNode());
11870   return true;
11871 }
11872
11873 /// Check to see if V is (and load (ptr), imm), where the load is having
11874 /// specific bytes cleared out.  If so, return the byte size being masked out
11875 /// and the shift amount.
11876 static std::pair<unsigned, unsigned>
11877 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11878   std::pair<unsigned, unsigned> Result(0, 0);
11879
11880   // Check for the structure we're looking for.
11881   if (V->getOpcode() != ISD::AND ||
11882       !isa<ConstantSDNode>(V->getOperand(1)) ||
11883       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11884     return Result;
11885
11886   // Check the chain and pointer.
11887   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11888   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11889
11890   // The store should be chained directly to the load or be an operand of a
11891   // tokenfactor.
11892   if (LD == Chain.getNode())
11893     ; // ok.
11894   else if (Chain->getOpcode() != ISD::TokenFactor)
11895     return Result; // Fail.
11896   else {
11897     bool isOk = false;
11898     for (const SDValue &ChainOp : Chain->op_values())
11899       if (ChainOp.getNode() == LD) {
11900         isOk = true;
11901         break;
11902       }
11903     if (!isOk) return Result;
11904   }
11905
11906   // This only handles simple types.
11907   if (V.getValueType() != MVT::i16 &&
11908       V.getValueType() != MVT::i32 &&
11909       V.getValueType() != MVT::i64)
11910     return Result;
11911
11912   // Check the constant mask.  Invert it so that the bits being masked out are
11913   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
11914   // follow the sign bit for uniformity.
11915   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11916   unsigned NotMaskLZ = countLeadingZeros(NotMask);
11917   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
11918   unsigned NotMaskTZ = countTrailingZeros(NotMask);
11919   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
11920   if (NotMaskLZ == 64) return Result;  // All zero mask.
11921
11922   // See if we have a continuous run of bits.  If so, we have 0*1+0*
11923   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11924     return Result;
11925
11926   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11927   if (V.getValueType() != MVT::i64 && NotMaskLZ)
11928     NotMaskLZ -= 64-V.getValueSizeInBits();
11929
11930   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11931   switch (MaskedBytes) {
11932   case 1:
11933   case 2:
11934   case 4: break;
11935   default: return Result; // All one mask, or 5-byte mask.
11936   }
11937
11938   // Verify that the first bit starts at a multiple of mask so that the access
11939   // is aligned the same as the access width.
11940   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11941
11942   Result.first = MaskedBytes;
11943   Result.second = NotMaskTZ/8;
11944   return Result;
11945 }
11946
11947
11948 /// Check to see if IVal is something that provides a value as specified by
11949 /// MaskInfo. If so, replace the specified store with a narrower store of
11950 /// truncated IVal.
11951 static SDNode *
11952 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11953                                 SDValue IVal, StoreSDNode *St,
11954                                 DAGCombiner *DC) {
11955   unsigned NumBytes = MaskInfo.first;
11956   unsigned ByteShift = MaskInfo.second;
11957   SelectionDAG &DAG = DC->getDAG();
11958
11959   // Check to see if IVal is all zeros in the part being masked in by the 'or'
11960   // that uses this.  If not, this is not a replacement.
11961   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11962                                   ByteShift*8, (ByteShift+NumBytes)*8);
11963   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11964
11965   // Check that it is legal on the target to do this.  It is legal if the new
11966   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11967   // legalization.
11968   MVT VT = MVT::getIntegerVT(NumBytes*8);
11969   if (!DC->isTypeLegal(VT))
11970     return nullptr;
11971
11972   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
11973   // shifted by ByteShift and truncated down to NumBytes.
11974   if (ByteShift) {
11975     SDLoc DL(IVal);
11976     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11977                        DAG.getConstant(ByteShift*8, DL,
11978                                     DC->getShiftAmountTy(IVal.getValueType())));
11979   }
11980
11981   // Figure out the offset for the store and the alignment of the access.
11982   unsigned StOffset;
11983   unsigned NewAlign = St->getAlignment();
11984
11985   if (DAG.getDataLayout().isLittleEndian())
11986     StOffset = ByteShift;
11987   else
11988     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11989
11990   SDValue Ptr = St->getBasePtr();
11991   if (StOffset) {
11992     SDLoc DL(IVal);
11993     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11994                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11995     NewAlign = MinAlign(NewAlign, StOffset);
11996   }
11997
11998   // Truncate down to the new size.
11999   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12000
12001   ++OpsNarrowed;
12002   return DAG
12003       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12004                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12005       .getNode();
12006 }
12007
12008
12009 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12010 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12011 /// narrowing the load and store if it would end up being a win for performance
12012 /// or code size.
12013 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12014   StoreSDNode *ST  = cast<StoreSDNode>(N);
12015   if (ST->isVolatile())
12016     return SDValue();
12017
12018   SDValue Chain = ST->getChain();
12019   SDValue Value = ST->getValue();
12020   SDValue Ptr   = ST->getBasePtr();
12021   EVT VT = Value.getValueType();
12022
12023   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12024     return SDValue();
12025
12026   unsigned Opc = Value.getOpcode();
12027
12028   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12029   // is a byte mask indicating a consecutive number of bytes, check to see if
12030   // Y is known to provide just those bytes.  If so, we try to replace the
12031   // load + replace + store sequence with a single (narrower) store, which makes
12032   // the load dead.
12033   if (Opc == ISD::OR) {
12034     std::pair<unsigned, unsigned> MaskedLoad;
12035     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12036     if (MaskedLoad.first)
12037       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12038                                                   Value.getOperand(1), ST,this))
12039         return SDValue(NewST, 0);
12040
12041     // Or is commutative, so try swapping X and Y.
12042     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12043     if (MaskedLoad.first)
12044       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12045                                                   Value.getOperand(0), ST,this))
12046         return SDValue(NewST, 0);
12047   }
12048
12049   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12050       Value.getOperand(1).getOpcode() != ISD::Constant)
12051     return SDValue();
12052
12053   SDValue N0 = Value.getOperand(0);
12054   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12055       Chain == SDValue(N0.getNode(), 1)) {
12056     LoadSDNode *LD = cast<LoadSDNode>(N0);
12057     if (LD->getBasePtr() != Ptr ||
12058         LD->getPointerInfo().getAddrSpace() !=
12059         ST->getPointerInfo().getAddrSpace())
12060       return SDValue();
12061
12062     // Find the type to narrow it the load / op / store to.
12063     SDValue N1 = Value.getOperand(1);
12064     unsigned BitWidth = N1.getValueSizeInBits();
12065     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12066     if (Opc == ISD::AND)
12067       Imm ^= APInt::getAllOnesValue(BitWidth);
12068     if (Imm == 0 || Imm.isAllOnesValue())
12069       return SDValue();
12070     unsigned ShAmt = Imm.countTrailingZeros();
12071     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12072     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12073     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12074     // The narrowing should be profitable, the load/store operation should be
12075     // legal (or custom) and the store size should be equal to the NewVT width.
12076     while (NewBW < BitWidth &&
12077            (NewVT.getStoreSizeInBits() != NewBW ||
12078             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12079             !TLI.isNarrowingProfitable(VT, NewVT))) {
12080       NewBW = NextPowerOf2(NewBW);
12081       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12082     }
12083     if (NewBW >= BitWidth)
12084       return SDValue();
12085
12086     // If the lsb changed does not start at the type bitwidth boundary,
12087     // start at the previous one.
12088     if (ShAmt % NewBW)
12089       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12090     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12091                                    std::min(BitWidth, ShAmt + NewBW));
12092     if ((Imm & Mask) == Imm) {
12093       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12094       if (Opc == ISD::AND)
12095         NewImm ^= APInt::getAllOnesValue(NewBW);
12096       uint64_t PtrOff = ShAmt / 8;
12097       // For big endian targets, we need to adjust the offset to the pointer to
12098       // load the correct bytes.
12099       if (DAG.getDataLayout().isBigEndian())
12100         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12101
12102       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12103       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12104       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12105         return SDValue();
12106
12107       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12108                                    Ptr.getValueType(), Ptr,
12109                                    DAG.getConstant(PtrOff, SDLoc(LD),
12110                                                    Ptr.getValueType()));
12111       SDValue NewLD =
12112           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12113                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12114                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12115       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12116                                    DAG.getConstant(NewImm, SDLoc(Value),
12117                                                    NewVT));
12118       SDValue NewST =
12119           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12120                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12121
12122       AddToWorklist(NewPtr.getNode());
12123       AddToWorklist(NewLD.getNode());
12124       AddToWorklist(NewVal.getNode());
12125       WorklistRemover DeadNodes(*this);
12126       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12127       ++OpsNarrowed;
12128       return NewST;
12129     }
12130   }
12131
12132   return SDValue();
12133 }
12134
12135 /// For a given floating point load / store pair, if the load value isn't used
12136 /// by any other operations, then consider transforming the pair to integer
12137 /// load / store operations if the target deems the transformation profitable.
12138 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12139   StoreSDNode *ST  = cast<StoreSDNode>(N);
12140   SDValue Chain = ST->getChain();
12141   SDValue Value = ST->getValue();
12142   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12143       Value.hasOneUse() &&
12144       Chain == SDValue(Value.getNode(), 1)) {
12145     LoadSDNode *LD = cast<LoadSDNode>(Value);
12146     EVT VT = LD->getMemoryVT();
12147     if (!VT.isFloatingPoint() ||
12148         VT != ST->getMemoryVT() ||
12149         LD->isNonTemporal() ||
12150         ST->isNonTemporal() ||
12151         LD->getPointerInfo().getAddrSpace() != 0 ||
12152         ST->getPointerInfo().getAddrSpace() != 0)
12153       return SDValue();
12154
12155     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12156     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12157         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12158         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12159         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12160       return SDValue();
12161
12162     unsigned LDAlign = LD->getAlignment();
12163     unsigned STAlign = ST->getAlignment();
12164     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12165     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12166     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12167       return SDValue();
12168
12169     SDValue NewLD =
12170         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12171                     LD->getPointerInfo(), LDAlign);
12172
12173     SDValue NewST =
12174         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12175                      ST->getPointerInfo(), STAlign);
12176
12177     AddToWorklist(NewLD.getNode());
12178     AddToWorklist(NewST.getNode());
12179     WorklistRemover DeadNodes(*this);
12180     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12181     ++LdStFP2Int;
12182     return NewST;
12183   }
12184
12185   return SDValue();
12186 }
12187
12188 // This is a helper function for visitMUL to check the profitability
12189 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12190 // MulNode is the original multiply, AddNode is (add x, c1),
12191 // and ConstNode is c2.
12192 //
12193 // If the (add x, c1) has multiple uses, we could increase
12194 // the number of adds if we make this transformation.
12195 // It would only be worth doing this if we can remove a
12196 // multiply in the process. Check for that here.
12197 // To illustrate:
12198 //     (A + c1) * c3
12199 //     (A + c2) * c3
12200 // We're checking for cases where we have common "c3 * A" expressions.
12201 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12202                                               SDValue &AddNode,
12203                                               SDValue &ConstNode) {
12204   APInt Val;
12205
12206   // If the add only has one use, this would be OK to do.
12207   if (AddNode.getNode()->hasOneUse())
12208     return true;
12209
12210   // Walk all the users of the constant with which we're multiplying.
12211   for (SDNode *Use : ConstNode->uses()) {
12212
12213     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12214       continue;
12215
12216     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12217       SDNode *OtherOp;
12218       SDNode *MulVar = AddNode.getOperand(0).getNode();
12219
12220       // OtherOp is what we're multiplying against the constant.
12221       if (Use->getOperand(0) == ConstNode)
12222         OtherOp = Use->getOperand(1).getNode();
12223       else
12224         OtherOp = Use->getOperand(0).getNode();
12225
12226       // Check to see if multiply is with the same operand of our "add".
12227       //
12228       //     ConstNode  = CONST
12229       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12230       //     ...
12231       //     AddNode  = (A + c1)  <-- MulVar is A.
12232       //         = AddNode * ConstNode   <-- current visiting instruction.
12233       //
12234       // If we make this transformation, we will have a common
12235       // multiply (ConstNode * A) that we can save.
12236       if (OtherOp == MulVar)
12237         return true;
12238
12239       // Now check to see if a future expansion will give us a common
12240       // multiply.
12241       //
12242       //     ConstNode  = CONST
12243       //     AddNode    = (A + c1)
12244       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12245       //     ...
12246       //     OtherOp = (A + c2)
12247       //     Use     = OtherOp * ConstNode <-- visiting Use.
12248       //
12249       // If we make this transformation, we will have a common
12250       // multiply (CONST * A) after we also do the same transformation
12251       // to the "t2" instruction.
12252       if (OtherOp->getOpcode() == ISD::ADD &&
12253           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12254           OtherOp->getOperand(0).getNode() == MulVar)
12255         return true;
12256     }
12257   }
12258
12259   // Didn't find a case where this would be profitable.
12260   return false;
12261 }
12262
12263 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12264                                          unsigned NumStores) {
12265   SmallVector<SDValue, 8> Chains;
12266   SmallPtrSet<const SDNode *, 8> Visited;
12267   SDLoc StoreDL(StoreNodes[0].MemNode);
12268
12269   for (unsigned i = 0; i < NumStores; ++i) {
12270     Visited.insert(StoreNodes[i].MemNode);
12271   }
12272
12273   // don't include nodes that are children
12274   for (unsigned i = 0; i < NumStores; ++i) {
12275     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12276       Chains.push_back(StoreNodes[i].MemNode->getChain());
12277   }
12278
12279   assert(Chains.size() > 0 && "Chain should have generated a chain");
12280   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12281 }
12282
12283 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12284                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12285                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12286   // Make sure we have something to merge.
12287   if (NumStores < 2)
12288     return false;
12289
12290   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12291
12292   // The latest Node in the DAG.
12293   SDLoc DL(StoreNodes[0].MemNode);
12294
12295   SDValue StoredVal;
12296   if (UseVector) {
12297     bool IsVec = MemVT.isVector();
12298     unsigned Elts = NumStores;
12299     if (IsVec) {
12300       // When merging vector stores, get the total number of elements.
12301       Elts *= MemVT.getVectorNumElements();
12302     }
12303     // Get the type for the merged vector store.
12304     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12305     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12306
12307     if (IsConstantSrc) {
12308       SmallVector<SDValue, 8> BuildVector;
12309       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12310         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12311         SDValue Val = St->getValue();
12312         if (MemVT.getScalarType().isInteger())
12313           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12314             Val = DAG.getConstant(
12315                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12316                 SDLoc(CFP), MemVT);
12317         BuildVector.push_back(Val);
12318       }
12319       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12320     } else {
12321       SmallVector<SDValue, 8> Ops;
12322       for (unsigned i = 0; i < NumStores; ++i) {
12323         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12324         SDValue Val = St->getValue();
12325         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12326         if (Val.getValueType() != MemVT)
12327           return false;
12328         Ops.push_back(Val);
12329       }
12330
12331       // Build the extracted vector elements back into a vector.
12332       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12333                               DL, Ty, Ops);    }
12334   } else {
12335     // We should always use a vector store when merging extracted vector
12336     // elements, so this path implies a store of constants.
12337     assert(IsConstantSrc && "Merged vector elements should use vector store");
12338
12339     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12340     APInt StoreInt(SizeInBits, 0);
12341
12342     // Construct a single integer constant which is made of the smaller
12343     // constant inputs.
12344     bool IsLE = DAG.getDataLayout().isLittleEndian();
12345     for (unsigned i = 0; i < NumStores; ++i) {
12346       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12347       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12348
12349       SDValue Val = St->getValue();
12350       StoreInt <<= ElementSizeBytes * 8;
12351       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12352         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12353       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12354         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12355       } else {
12356         llvm_unreachable("Invalid constant element type");
12357       }
12358     }
12359
12360     // Create the new Load and Store operations.
12361     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12362     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12363   }
12364
12365   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12366   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12367   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12368                                   FirstInChain->getBasePtr(),
12369                                   FirstInChain->getPointerInfo(),
12370                                   FirstInChain->getAlignment());
12371
12372   // Replace all merged stores with the new store.
12373   for (unsigned i = 0; i < NumStores; ++i)
12374     CombineTo(StoreNodes[i].MemNode, NewStore);
12375
12376   AddToWorklist(NewChain.getNode());
12377   return true;
12378 }
12379
12380 void DAGCombiner::getStoreMergeCandidates(
12381     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12382   // This holds the base pointer, index, and the offset in bytes from the base
12383   // pointer.
12384   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12385   EVT MemVT = St->getMemoryVT();
12386
12387   // We must have a base and an offset.
12388   if (!BasePtr.Base.getNode())
12389     return;
12390
12391   // Do not handle stores to undef base pointers.
12392   if (BasePtr.Base.isUndef())
12393     return;
12394
12395   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12396   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12397                        isa<ConstantFPSDNode>(St->getValue());
12398   bool IsExtractVecSrc =
12399       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12400        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12401   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12402     if (Other->isVolatile() || Other->isIndexed())
12403       return false;
12404     // We can merge constant floats to equivalent integers
12405     if (Other->getMemoryVT() != MemVT)
12406       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12407             isa<ConstantFPSDNode>(Other->getValue())))
12408         return false;
12409     if (IsLoadSrc)
12410       if (!isa<LoadSDNode>(Other->getValue()))
12411         return false;
12412     if (IsConstantSrc)
12413       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12414             isa<ConstantFPSDNode>(Other->getValue())))
12415         return false;
12416     if (IsExtractVecSrc)
12417       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12418             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12419         return false;
12420     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12421     return (Ptr.equalBaseIndex(BasePtr));
12422   };
12423   // We looking for a root node which is an ancestor to all mergable
12424   // stores. We search up through a load, to our root and then down
12425   // through all children. For instance we will find Store{1,2,3} if
12426   // St is Store1, Store2. or Store3 where the root is not a load
12427   // which always true for nonvolatile ops. TODO: Expand
12428   // the search to find all valid candidates through multiple layers of loads.
12429   //
12430   // Root
12431   // |-------|-------|
12432   // Load    Load    Store3
12433   // |       |
12434   // Store1   Store2
12435   //
12436   // FIXME: We should be able to climb and
12437   // descend TokenFactors to find candidates as well.
12438
12439   SDNode *RootNode = (St->getChain()).getNode();
12440
12441   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12442     RootNode = Ldn->getChain().getNode();
12443     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12444       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12445         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12446           if (I2.getOperandNo() == 0)
12447             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12448               BaseIndexOffset Ptr;
12449               if (CandidateMatch(OtherST, Ptr))
12450                 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12451             }
12452   } else
12453     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12454       if (I.getOperandNo() == 0)
12455         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12456           BaseIndexOffset Ptr;
12457           if (CandidateMatch(OtherST, Ptr))
12458             StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12459         }
12460 }
12461
12462 // We need to check that merging these stores does not cause a loop
12463 // in the DAG. Any store candidate may depend on another candidate
12464 // indirectly through its operand (we already consider dependencies
12465 // through the chain). Check in parallel by searching up from
12466 // non-chain operands of candidates.
12467 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12468     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12469   SmallPtrSet<const SDNode *, 16> Visited;
12470   SmallVector<const SDNode *, 8> Worklist;
12471   // search ops of store candidates
12472   for (unsigned i = 0; i < NumStores; ++i) {
12473     SDNode *n = StoreNodes[i].MemNode;
12474     // Potential loops may happen only through non-chain operands
12475     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12476       Worklist.push_back(n->getOperand(j).getNode());
12477   }
12478   // search through DAG. We can stop early if we find a storenode
12479   for (unsigned i = 0; i < NumStores; ++i) {
12480     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12481       return false;
12482   }
12483   return true;
12484 }
12485
12486 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12487   if (OptLevel == CodeGenOpt::None)
12488     return false;
12489
12490   EVT MemVT = St->getMemoryVT();
12491   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12492
12493   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12494     return false;
12495
12496   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12497       Attribute::NoImplicitFloat);
12498
12499   // This function cannot currently deal with non-byte-sized memory sizes.
12500   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12501     return false;
12502
12503   if (!MemVT.isSimple())
12504     return false;
12505
12506   // Perform an early exit check. Do not bother looking at stored values that
12507   // are not constants, loads, or extracted vector elements.
12508   SDValue StoredVal = St->getValue();
12509   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12510   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12511                        isa<ConstantFPSDNode>(StoredVal);
12512   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12513                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12514
12515   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12516     return false;
12517
12518   // Don't merge vectors into wider vectors if the source data comes from loads.
12519   // TODO: This restriction can be lifted by using logic similar to the
12520   // ExtractVecSrc case.
12521   if (MemVT.isVector() && IsLoadSrc)
12522     return false;
12523
12524   SmallVector<MemOpLink, 8> StoreNodes;
12525   // Find potential store merge candidates by searching through chain sub-DAG
12526   getStoreMergeCandidates(St, StoreNodes);
12527
12528   // Check if there is anything to merge.
12529   if (StoreNodes.size() < 2)
12530     return false;
12531
12532   // Sort the memory operands according to their distance from the
12533   // base pointer.
12534   std::sort(StoreNodes.begin(), StoreNodes.end(),
12535             [](MemOpLink LHS, MemOpLink RHS) {
12536               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12537             });
12538
12539   // Store Merge attempts to merge the lowest stores. This generally
12540   // works out as if successful, as the remaining stores are checked
12541   // after the first collection of stores is merged. However, in the
12542   // case that a non-mergeable store is found first, e.g., {p[-2],
12543   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12544   // mergeable cases. To prevent this, we prune such stores from the
12545   // front of StoreNodes here.
12546
12547   bool RV = false;
12548   while (StoreNodes.size() > 1) {
12549     unsigned StartIdx = 0;
12550     while ((StartIdx + 1 < StoreNodes.size()) &&
12551            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12552                StoreNodes[StartIdx + 1].OffsetFromBase)
12553       ++StartIdx;
12554
12555     // Bail if we don't have enough candidates to merge.
12556     if (StartIdx + 1 >= StoreNodes.size())
12557       return RV;
12558
12559     if (StartIdx)
12560       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12561
12562     // Scan the memory operations on the chain and find the first
12563     // non-consecutive store memory address.
12564     unsigned NumConsecutiveStores = 1;
12565     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12566     // Check that the addresses are consecutive starting from the second
12567     // element in the list of stores.
12568     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12569       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12570       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12571         break;
12572       NumConsecutiveStores = i + 1;
12573     }
12574
12575     if (NumConsecutiveStores < 2) {
12576       StoreNodes.erase(StoreNodes.begin(),
12577                        StoreNodes.begin() + NumConsecutiveStores);
12578       continue;
12579     }
12580
12581     // Check that we can merge these candidates without causing a cycle
12582     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12583                                                   NumConsecutiveStores)) {
12584       StoreNodes.erase(StoreNodes.begin(),
12585                        StoreNodes.begin() + NumConsecutiveStores);
12586       continue;
12587     }
12588
12589     // The node with the lowest store address.
12590     LLVMContext &Context = *DAG.getContext();
12591     const DataLayout &DL = DAG.getDataLayout();
12592
12593     // Store the constants into memory as one consecutive store.
12594     if (IsConstantSrc) {
12595       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12596       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12597       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12598       unsigned LastLegalType = 0;
12599       unsigned LastLegalVectorType = 0;
12600       bool NonZero = false;
12601       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12602         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12603         SDValue StoredVal = ST->getValue();
12604
12605         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12606           NonZero |= !C->isNullValue();
12607         } else if (ConstantFPSDNode *C =
12608                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12609           NonZero |= !C->getConstantFPValue()->isNullValue();
12610         } else {
12611           // Non-constant.
12612           break;
12613         }
12614
12615         // Find a legal type for the constant store.
12616         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12617         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12618         bool IsFast = false;
12619         if (TLI.isTypeLegal(StoreTy) &&
12620             TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12621             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12622                                    FirstStoreAlign, &IsFast) &&
12623             IsFast) {
12624           LastLegalType = i + 1;
12625           // Or check whether a truncstore is legal.
12626         } else if (!LegalTypes &&
12627                    TLI.getTypeAction(Context, StoreTy) ==
12628                    TargetLowering::TypePromoteInteger) {
12629           EVT LegalizedStoredValueTy =
12630               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12631           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12632               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) &&
12633               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12634                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12635               IsFast) {
12636             LastLegalType = i + 1;
12637           }
12638         }
12639
12640         // We only use vectors if the constant is known to be zero or the target
12641         // allows it and the function is not marked with the noimplicitfloat
12642         // attribute.
12643         if ((!NonZero ||
12644              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12645             !NoVectors) {
12646           // Find a legal type for the vector store.
12647           EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12648           if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) &&
12649               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12650                                      FirstStoreAlign, &IsFast) &&
12651               IsFast)
12652             LastLegalVectorType = i + 1;
12653         }
12654       }
12655
12656       // Check if we found a legal integer type that creates a meaningful merge.
12657       if (LastLegalType < 2 && LastLegalVectorType < 2) {
12658         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12659         continue;
12660       }
12661
12662       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12663       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12664
12665       bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12666                                                     true, UseVector);
12667       if (!Merged) {
12668         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12669         continue;
12670       }
12671       // Remove merged stores for next iteration.
12672       RV = true;
12673       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12674       continue;
12675     }
12676
12677     // When extracting multiple vector elements, try to store them
12678     // in one vector store rather than a sequence of scalar stores.
12679     if (IsExtractVecSrc) {
12680       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12681       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12682       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12683       unsigned NumStoresToMerge = 1;
12684       bool IsVec = MemVT.isVector();
12685       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12686         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12687         unsigned StoreValOpcode = St->getValue().getOpcode();
12688         // This restriction could be loosened.
12689         // Bail out if any stored values are not elements extracted from a
12690         // vector. It should be possible to handle mixed sources, but load
12691         // sources need more careful handling (see the block of code below that
12692         // handles consecutive loads).
12693         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12694             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12695           return RV;
12696
12697         // Find a legal type for the vector store.
12698         unsigned Elts = i + 1;
12699         if (IsVec) {
12700           // When merging vector stores, get the total number of elements.
12701           Elts *= MemVT.getVectorNumElements();
12702         }
12703         EVT Ty =
12704             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12705         bool IsFast;
12706         if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) &&
12707             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12708                                    FirstStoreAlign, &IsFast) &&
12709             IsFast)
12710           NumStoresToMerge = i + 1;
12711       }
12712
12713       bool Merged = MergeStoresOfConstantsOrVecElts(
12714           StoreNodes, MemVT, NumStoresToMerge, false, true);
12715       if (!Merged) {
12716         StoreNodes.erase(StoreNodes.begin(),
12717                          StoreNodes.begin() + NumStoresToMerge);
12718         continue;
12719       }
12720       // Remove merged stores for next iteration.
12721       StoreNodes.erase(StoreNodes.begin(),
12722                        StoreNodes.begin() + NumStoresToMerge);
12723       RV = true;
12724       continue;
12725     }
12726
12727     // Below we handle the case of multiple consecutive stores that
12728     // come from multiple consecutive loads. We merge them into a single
12729     // wide load and a single wide store.
12730
12731     // Look for load nodes which are used by the stored values.
12732     SmallVector<MemOpLink, 8> LoadNodes;
12733
12734     // Find acceptable loads. Loads need to have the same chain (token factor),
12735     // must not be zext, volatile, indexed, and they must be consecutive.
12736     BaseIndexOffset LdBasePtr;
12737     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12738       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12739       LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12740       if (!Ld)
12741         break;
12742
12743       // Loads must only have one use.
12744       if (!Ld->hasNUsesOfValue(1, 0))
12745         break;
12746
12747       // The memory operands must not be volatile.
12748       if (Ld->isVolatile() || Ld->isIndexed())
12749         break;
12750
12751       // We do not accept ext loads.
12752       if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12753         break;
12754
12755       // The stored memory type must be the same.
12756       if (Ld->getMemoryVT() != MemVT)
12757         break;
12758
12759       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12760       // If this is not the first ptr that we check.
12761       if (LdBasePtr.Base.getNode()) {
12762         // The base ptr must be the same.
12763         if (!LdPtr.equalBaseIndex(LdBasePtr))
12764           break;
12765       } else {
12766         // Check that all other base pointers are the same as this one.
12767         LdBasePtr = LdPtr;
12768       }
12769
12770       // We found a potential memory operand to merge.
12771       LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12772     }
12773
12774     if (LoadNodes.size() < 2) {
12775       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12776       continue;
12777     }
12778
12779     // If we have load/store pair instructions and we only have two values,
12780     // don't bother.
12781     unsigned RequiredAlignment;
12782     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12783         St->getAlignment() >= RequiredAlignment) {
12784       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
12785       continue;
12786     }
12787     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12788     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12789     unsigned FirstStoreAlign = FirstInChain->getAlignment();
12790     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12791     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12792     unsigned FirstLoadAlign = FirstLoad->getAlignment();
12793
12794     // Scan the memory operations on the chain and find the first
12795     // non-consecutive load memory address. These variables hold the index in
12796     // the store node array.
12797     unsigned LastConsecutiveLoad = 0;
12798     // This variable refers to the size and not index in the array.
12799     unsigned LastLegalVectorType = 0;
12800     unsigned LastLegalIntegerType = 0;
12801     StartAddress = LoadNodes[0].OffsetFromBase;
12802     SDValue FirstChain = FirstLoad->getChain();
12803     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12804       // All loads must share the same chain.
12805       if (LoadNodes[i].MemNode->getChain() != FirstChain)
12806         break;
12807
12808       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12809       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12810         break;
12811       LastConsecutiveLoad = i;
12812       // Find a legal type for the vector store.
12813       EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1);
12814       bool IsFastSt, IsFastLd;
12815       if (TLI.isTypeLegal(StoreTy) &&
12816           TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12817           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12818                                  FirstStoreAlign, &IsFastSt) &&
12819           IsFastSt &&
12820           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12821                                  FirstLoadAlign, &IsFastLd) &&
12822           IsFastLd) {
12823         LastLegalVectorType = i + 1;
12824       }
12825
12826       // Find a legal type for the integer store.
12827       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12828       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12829       if (TLI.isTypeLegal(StoreTy) &&
12830           TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12831           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12832                                  FirstStoreAlign, &IsFastSt) &&
12833           IsFastSt &&
12834           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12835                                  FirstLoadAlign, &IsFastLd) &&
12836           IsFastLd)
12837         LastLegalIntegerType = i + 1;
12838       // Or check whether a truncstore and extload is legal.
12839       else if (TLI.getTypeAction(Context, StoreTy) ==
12840                TargetLowering::TypePromoteInteger) {
12841         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
12842         if (!LegalTypes &&
12843             TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12844             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) &&
12845             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
12846                                StoreTy) &&
12847             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
12848                                StoreTy) &&
12849             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12850             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12851                                    FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12852             IsFastSt &&
12853             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12854                                    FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12855             IsFastLd)
12856           LastLegalIntegerType = i + 1;
12857       }
12858     }
12859
12860     // Only use vector types if the vector type is larger than the integer type.
12861     // If they are the same, use integers.
12862     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12863     unsigned LastLegalType =
12864         std::max(LastLegalVectorType, LastLegalIntegerType);
12865
12866     // We add +1 here because the LastXXX variables refer to location while
12867     // the NumElem refers to array/index size.
12868     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12869     NumElem = std::min(LastLegalType, NumElem);
12870
12871     if (NumElem < 2) {
12872       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12873       continue;
12874     }
12875
12876     // Find if it is better to use vectors or integers to load and store
12877     // to memory.
12878     EVT JointMemOpVT;
12879     if (UseVectorTy) {
12880       JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12881     } else {
12882       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12883       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12884     }
12885
12886     SDLoc LoadDL(LoadNodes[0].MemNode);
12887     SDLoc StoreDL(StoreNodes[0].MemNode);
12888
12889     // The merged loads are required to have the same incoming chain, so
12890     // using the first's chain is acceptable.
12891     SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12892                                   FirstLoad->getBasePtr(),
12893                                   FirstLoad->getPointerInfo(), FirstLoadAlign);
12894
12895     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12896
12897     AddToWorklist(NewStoreChain.getNode());
12898
12899     SDValue NewStore = DAG.getStore(
12900         NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12901         FirstInChain->getPointerInfo(), FirstStoreAlign);
12902
12903     // Transfer chain users from old loads to the new load.
12904     for (unsigned i = 0; i < NumElem; ++i) {
12905       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12906       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12907                                     SDValue(NewLoad.getNode(), 1));
12908     }
12909
12910     // Replace the all stores with the new store.
12911     for (unsigned i = 0; i < NumElem; ++i)
12912       CombineTo(StoreNodes[i].MemNode, NewStore);
12913     RV = true;
12914     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12915     continue;
12916   }
12917   return RV;
12918 }
12919
12920 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12921   SDLoc SL(ST);
12922   SDValue ReplStore;
12923
12924   // Replace the chain to avoid dependency.
12925   if (ST->isTruncatingStore()) {
12926     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12927                                   ST->getBasePtr(), ST->getMemoryVT(),
12928                                   ST->getMemOperand());
12929   } else {
12930     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12931                              ST->getMemOperand());
12932   }
12933
12934   // Create token to keep both nodes around.
12935   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12936                               MVT::Other, ST->getChain(), ReplStore);
12937
12938   // Make sure the new and old chains are cleaned up.
12939   AddToWorklist(Token.getNode());
12940
12941   // Don't add users to work list.
12942   return CombineTo(ST, Token, false);
12943 }
12944
12945 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12946   SDValue Value = ST->getValue();
12947   if (Value.getOpcode() == ISD::TargetConstantFP)
12948     return SDValue();
12949
12950   SDLoc DL(ST);
12951
12952   SDValue Chain = ST->getChain();
12953   SDValue Ptr = ST->getBasePtr();
12954
12955   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12956
12957   // NOTE: If the original store is volatile, this transform must not increase
12958   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12959   // processor operation but an i64 (which is not legal) requires two.  So the
12960   // transform should not be done in this case.
12961
12962   SDValue Tmp;
12963   switch (CFP->getSimpleValueType(0).SimpleTy) {
12964   default:
12965     llvm_unreachable("Unknown FP type");
12966   case MVT::f16:    // We don't do this for these yet.
12967   case MVT::f80:
12968   case MVT::f128:
12969   case MVT::ppcf128:
12970     return SDValue();
12971   case MVT::f32:
12972     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12973         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12974       ;
12975       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12976                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12977                             MVT::i32);
12978       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12979     }
12980
12981     return SDValue();
12982   case MVT::f64:
12983     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12984          !ST->isVolatile()) ||
12985         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12986       ;
12987       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12988                             getZExtValue(), SDLoc(CFP), MVT::i64);
12989       return DAG.getStore(Chain, DL, Tmp,
12990                           Ptr, ST->getMemOperand());
12991     }
12992
12993     if (!ST->isVolatile() &&
12994         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12995       // Many FP stores are not made apparent until after legalize, e.g. for
12996       // argument passing.  Since this is so common, custom legalize the
12997       // 64-bit integer store into two 32-bit stores.
12998       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12999       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13000       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13001       if (DAG.getDataLayout().isBigEndian())
13002         std::swap(Lo, Hi);
13003
13004       unsigned Alignment = ST->getAlignment();
13005       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13006       AAMDNodes AAInfo = ST->getAAInfo();
13007
13008       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13009                                  ST->getAlignment(), MMOFlags, AAInfo);
13010       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13011                         DAG.getConstant(4, DL, Ptr.getValueType()));
13012       Alignment = MinAlign(Alignment, 4U);
13013       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13014                                  ST->getPointerInfo().getWithOffset(4),
13015                                  Alignment, MMOFlags, AAInfo);
13016       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13017                          St0, St1);
13018     }
13019
13020     return SDValue();
13021   }
13022 }
13023
13024 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13025   StoreSDNode *ST  = cast<StoreSDNode>(N);
13026   SDValue Chain = ST->getChain();
13027   SDValue Value = ST->getValue();
13028   SDValue Ptr   = ST->getBasePtr();
13029
13030   // If this is a store of a bit convert, store the input value if the
13031   // resultant store does not need a higher alignment than the original.
13032   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13033       ST->isUnindexed()) {
13034     EVT SVT = Value.getOperand(0).getValueType();
13035     if (((!LegalOperations && !ST->isVolatile()) ||
13036          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13037         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13038       unsigned OrigAlign = ST->getAlignment();
13039       bool Fast = false;
13040       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13041                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13042           Fast) {
13043         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13044                             ST->getPointerInfo(), OrigAlign,
13045                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13046       }
13047     }
13048   }
13049
13050   // Turn 'store undef, Ptr' -> nothing.
13051   if (Value.isUndef() && ST->isUnindexed())
13052     return Chain;
13053
13054   // Try to infer better alignment information than the store already has.
13055   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13056     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13057       if (Align > ST->getAlignment()) {
13058         SDValue NewStore =
13059             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13060                               ST->getMemoryVT(), Align,
13061                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13062         if (NewStore.getNode() != N)
13063           return CombineTo(ST, NewStore, true);
13064       }
13065     }
13066   }
13067
13068   // Try transforming a pair floating point load / store ops to integer
13069   // load / store ops.
13070   if (SDValue NewST = TransformFPLoadStorePair(N))
13071     return NewST;
13072
13073   if (ST->isUnindexed()) {
13074     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13075     // adjacent stores.
13076     if (findBetterNeighborChains(ST)) {
13077       // replaceStoreChain uses CombineTo, which handled all of the worklist
13078       // manipulation. Return the original node to not do anything else.
13079       return SDValue(ST, 0);
13080     }
13081     Chain = ST->getChain();
13082   }
13083
13084   // Try transforming N to an indexed store.
13085   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13086     return SDValue(N, 0);
13087
13088   // FIXME: is there such a thing as a truncating indexed store?
13089   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13090       Value.getValueType().isInteger()) {
13091     // See if we can simplify the input to this truncstore with knowledge that
13092     // only the low bits are being used.  For example:
13093     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13094     SDValue Shorter = GetDemandedBits(
13095         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13096                                     ST->getMemoryVT().getScalarSizeInBits()));
13097     AddToWorklist(Value.getNode());
13098     if (Shorter.getNode())
13099       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13100                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13101
13102     // Otherwise, see if we can simplify the operation with
13103     // SimplifyDemandedBits, which only works if the value has a single use.
13104     if (SimplifyDemandedBits(
13105             Value,
13106             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13107                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13108       // Re-visit the store if anything changed and the store hasn't been merged
13109       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13110       // node back to the worklist if necessary, but we also need to re-visit
13111       // the Store node itself.
13112       if (N->getOpcode() != ISD::DELETED_NODE)
13113         AddToWorklist(N);
13114       return SDValue(N, 0);
13115     }
13116   }
13117
13118   // If this is a load followed by a store to the same location, then the store
13119   // is dead/noop.
13120   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13121     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13122         ST->isUnindexed() && !ST->isVolatile() &&
13123         // There can't be any side effects between the load and store, such as
13124         // a call or store.
13125         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13126       // The store is dead, remove it.
13127       return Chain;
13128     }
13129   }
13130
13131   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13132     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13133         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13134         ST->getMemoryVT() == ST1->getMemoryVT()) {
13135       // If this is a store followed by a store with the same value to the same
13136       // location, then the store is dead/noop.
13137       if (ST1->getValue() == Value) {
13138         // The store is dead, remove it.
13139         return Chain;
13140       }
13141
13142       // If this is a store who's preceeding store to the same location
13143       // and no one other node is chained to that store we can effectively
13144       // drop the store. Do not remove stores to undef as they may be used as
13145       // data sinks.
13146       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13147           !ST1->getBasePtr().isUndef()) {
13148         // ST1 is fully overwritten and can be elided. Combine with it's chain
13149         // value.
13150         CombineTo(ST1, ST1->getChain());
13151         return SDValue();
13152       }
13153     }
13154   }
13155
13156   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13157   // truncating store.  We can do this even if this is already a truncstore.
13158   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13159       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13160       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13161                             ST->getMemoryVT())) {
13162     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13163                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13164   }
13165
13166   // Only perform this optimization before the types are legal, because we
13167   // don't want to perform this optimization on every DAGCombine invocation.
13168   if (!LegalTypes) {
13169     for (;;) {
13170       // There can be multiple store sequences on the same chain.
13171       // Keep trying to merge store sequences until we are unable to do so
13172       // or until we merge the last store on the chain.
13173       bool Changed = MergeConsecutiveStores(ST);
13174       if (!Changed) break;
13175       // Return N as merge only uses CombineTo and no worklist clean
13176       // up is necessary.
13177       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13178         return SDValue(N, 0);
13179     }
13180   }
13181
13182   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13183   //
13184   // Make sure to do this only after attempting to merge stores in order to
13185   //  avoid changing the types of some subset of stores due to visit order,
13186   //  preventing their merging.
13187   if (isa<ConstantFPSDNode>(ST->getValue())) {
13188     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13189       return NewSt;
13190   }
13191
13192   if (SDValue NewSt = splitMergedValStore(ST))
13193     return NewSt;
13194
13195   return ReduceLoadOpStoreWidth(N);
13196 }
13197
13198 /// For the instruction sequence of store below, F and I values
13199 /// are bundled together as an i64 value before being stored into memory.
13200 /// Sometimes it is more efficent to generate separate stores for F and I,
13201 /// which can remove the bitwise instructions or sink them to colder places.
13202 ///
13203 ///   (store (or (zext (bitcast F to i32) to i64),
13204 ///              (shl (zext I to i64), 32)), addr)  -->
13205 ///   (store F, addr) and (store I, addr+4)
13206 ///
13207 /// Similarly, splitting for other merged store can also be beneficial, like:
13208 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13209 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13210 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13211 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13212 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13213 ///
13214 /// We allow each target to determine specifically which kind of splitting is
13215 /// supported.
13216 ///
13217 /// The store patterns are commonly seen from the simple code snippet below
13218 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13219 ///   void goo(const std::pair<int, float> &);
13220 ///   hoo() {
13221 ///     ...
13222 ///     goo(std::make_pair(tmp, ftmp));
13223 ///     ...
13224 ///   }
13225 ///
13226 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13227   if (OptLevel == CodeGenOpt::None)
13228     return SDValue();
13229
13230   SDValue Val = ST->getValue();
13231   SDLoc DL(ST);
13232
13233   // Match OR operand.
13234   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13235     return SDValue();
13236
13237   // Match SHL operand and get Lower and Higher parts of Val.
13238   SDValue Op1 = Val.getOperand(0);
13239   SDValue Op2 = Val.getOperand(1);
13240   SDValue Lo, Hi;
13241   if (Op1.getOpcode() != ISD::SHL) {
13242     std::swap(Op1, Op2);
13243     if (Op1.getOpcode() != ISD::SHL)
13244       return SDValue();
13245   }
13246   Lo = Op2;
13247   Hi = Op1.getOperand(0);
13248   if (!Op1.hasOneUse())
13249     return SDValue();
13250
13251   // Match shift amount to HalfValBitSize.
13252   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13253   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13254   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13255     return SDValue();
13256
13257   // Lo and Hi are zero-extended from int with size less equal than 32
13258   // to i64.
13259   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13260       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13261       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13262       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13263       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13264       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13265     return SDValue();
13266
13267   // Use the EVT of low and high parts before bitcast as the input
13268   // of target query.
13269   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13270                   ? Lo.getOperand(0).getValueType()
13271                   : Lo.getValueType();
13272   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13273                    ? Hi.getOperand(0).getValueType()
13274                    : Hi.getValueType();
13275   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13276     return SDValue();
13277
13278   // Start to split store.
13279   unsigned Alignment = ST->getAlignment();
13280   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13281   AAMDNodes AAInfo = ST->getAAInfo();
13282
13283   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13284   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13285   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13286   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13287
13288   SDValue Chain = ST->getChain();
13289   SDValue Ptr = ST->getBasePtr();
13290   // Lower value store.
13291   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13292                              ST->getAlignment(), MMOFlags, AAInfo);
13293   Ptr =
13294       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13295                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13296   // Higher value store.
13297   SDValue St1 =
13298       DAG.getStore(St0, DL, Hi, Ptr,
13299                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13300                    Alignment / 2, MMOFlags, AAInfo);
13301   return St1;
13302 }
13303
13304 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13305   SDValue InVec = N->getOperand(0);
13306   SDValue InVal = N->getOperand(1);
13307   SDValue EltNo = N->getOperand(2);
13308   SDLoc DL(N);
13309
13310   // If the inserted element is an UNDEF, just use the input vector.
13311   if (InVal.isUndef())
13312     return InVec;
13313
13314   EVT VT = InVec.getValueType();
13315
13316   // Check that we know which element is being inserted
13317   if (!isa<ConstantSDNode>(EltNo))
13318     return SDValue();
13319   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13320
13321   // Canonicalize insert_vector_elt dag nodes.
13322   // Example:
13323   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13324   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13325   //
13326   // Do this only if the child insert_vector node has one use; also
13327   // do this only if indices are both constants and Idx1 < Idx0.
13328   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13329       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13330     unsigned OtherElt = InVec.getConstantOperandVal(2);
13331     if (Elt < OtherElt) {
13332       // Swap nodes.
13333       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13334                                   InVec.getOperand(0), InVal, EltNo);
13335       AddToWorklist(NewOp.getNode());
13336       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13337                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13338     }
13339   }
13340
13341   // If we can't generate a legal BUILD_VECTOR, exit
13342   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13343     return SDValue();
13344
13345   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13346   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13347   // vector elements.
13348   SmallVector<SDValue, 8> Ops;
13349   // Do not combine these two vectors if the output vector will not replace
13350   // the input vector.
13351   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13352     Ops.append(InVec.getNode()->op_begin(),
13353                InVec.getNode()->op_end());
13354   } else if (InVec.isUndef()) {
13355     unsigned NElts = VT.getVectorNumElements();
13356     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13357   } else {
13358     return SDValue();
13359   }
13360
13361   // Insert the element
13362   if (Elt < Ops.size()) {
13363     // All the operands of BUILD_VECTOR must have the same type;
13364     // we enforce that here.
13365     EVT OpVT = Ops[0].getValueType();
13366     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13367   }
13368
13369   // Return the new vector
13370   return DAG.getBuildVector(VT, DL, Ops);
13371 }
13372
13373 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13374     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13375   assert(!OriginalLoad->isVolatile());
13376
13377   EVT ResultVT = EVE->getValueType(0);
13378   EVT VecEltVT = InVecVT.getVectorElementType();
13379   unsigned Align = OriginalLoad->getAlignment();
13380   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13381       VecEltVT.getTypeForEVT(*DAG.getContext()));
13382
13383   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13384     return SDValue();
13385
13386   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13387     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13388   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13389     return SDValue();
13390
13391   Align = NewAlign;
13392
13393   SDValue NewPtr = OriginalLoad->getBasePtr();
13394   SDValue Offset;
13395   EVT PtrType = NewPtr.getValueType();
13396   MachinePointerInfo MPI;
13397   SDLoc DL(EVE);
13398   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13399     int Elt = ConstEltNo->getZExtValue();
13400     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13401     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13402     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13403   } else {
13404     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13405     Offset = DAG.getNode(
13406         ISD::MUL, DL, PtrType, Offset,
13407         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13408     MPI = OriginalLoad->getPointerInfo();
13409   }
13410   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13411
13412   // The replacement we need to do here is a little tricky: we need to
13413   // replace an extractelement of a load with a load.
13414   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13415   // Note that this replacement assumes that the extractvalue is the only
13416   // use of the load; that's okay because we don't want to perform this
13417   // transformation in other cases anyway.
13418   SDValue Load;
13419   SDValue Chain;
13420   if (ResultVT.bitsGT(VecEltVT)) {
13421     // If the result type of vextract is wider than the load, then issue an
13422     // extending load instead.
13423     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13424                                                   VecEltVT)
13425                                    ? ISD::ZEXTLOAD
13426                                    : ISD::EXTLOAD;
13427     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13428                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13429                           Align, OriginalLoad->getMemOperand()->getFlags(),
13430                           OriginalLoad->getAAInfo());
13431     Chain = Load.getValue(1);
13432   } else {
13433     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13434                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13435                        OriginalLoad->getAAInfo());
13436     Chain = Load.getValue(1);
13437     if (ResultVT.bitsLT(VecEltVT))
13438       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13439     else
13440       Load = DAG.getBitcast(ResultVT, Load);
13441   }
13442   WorklistRemover DeadNodes(*this);
13443   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13444   SDValue To[] = { Load, Chain };
13445   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13446   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13447   // worklist explicitly as well.
13448   AddToWorklist(Load.getNode());
13449   AddUsersToWorklist(Load.getNode()); // Add users too
13450   // Make sure to revisit this node to clean it up; it will usually be dead.
13451   AddToWorklist(EVE);
13452   ++OpsNarrowed;
13453   return SDValue(EVE, 0);
13454 }
13455
13456 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13457   // (vextract (scalar_to_vector val, 0) -> val
13458   SDValue InVec = N->getOperand(0);
13459   EVT VT = InVec.getValueType();
13460   EVT NVT = N->getValueType(0);
13461
13462   if (InVec.isUndef())
13463     return DAG.getUNDEF(NVT);
13464
13465   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13466     // Check if the result type doesn't match the inserted element type. A
13467     // SCALAR_TO_VECTOR may truncate the inserted element and the
13468     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13469     SDValue InOp = InVec.getOperand(0);
13470     if (InOp.getValueType() != NVT) {
13471       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13472       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13473     }
13474     return InOp;
13475   }
13476
13477   SDValue EltNo = N->getOperand(1);
13478   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13479
13480   // extract_vector_elt (build_vector x, y), 1 -> y
13481   if (ConstEltNo &&
13482       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13483       TLI.isTypeLegal(VT) &&
13484       (InVec.hasOneUse() ||
13485        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13486     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13487     EVT InEltVT = Elt.getValueType();
13488
13489     // Sometimes build_vector's scalar input types do not match result type.
13490     if (NVT == InEltVT)
13491       return Elt;
13492
13493     // TODO: It may be useful to truncate if free if the build_vector implicitly
13494     // converts.
13495   }
13496
13497   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13498   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13499       ConstEltNo->isNullValue() && VT.isInteger()) {
13500     SDValue BCSrc = InVec.getOperand(0);
13501     if (BCSrc.getValueType().isScalarInteger())
13502       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13503   }
13504
13505   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13506   //
13507   // This only really matters if the index is non-constant since other combines
13508   // on the constant elements already work.
13509   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13510       EltNo == InVec.getOperand(2)) {
13511     SDValue Elt = InVec.getOperand(1);
13512     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13513   }
13514
13515   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13516   // We only perform this optimization before the op legalization phase because
13517   // we may introduce new vector instructions which are not backed by TD
13518   // patterns. For example on AVX, extracting elements from a wide vector
13519   // without using extract_subvector. However, if we can find an underlying
13520   // scalar value, then we can always use that.
13521   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13522     int NumElem = VT.getVectorNumElements();
13523     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13524     // Find the new index to extract from.
13525     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13526
13527     // Extracting an undef index is undef.
13528     if (OrigElt == -1)
13529       return DAG.getUNDEF(NVT);
13530
13531     // Select the right vector half to extract from.
13532     SDValue SVInVec;
13533     if (OrigElt < NumElem) {
13534       SVInVec = InVec->getOperand(0);
13535     } else {
13536       SVInVec = InVec->getOperand(1);
13537       OrigElt -= NumElem;
13538     }
13539
13540     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13541       SDValue InOp = SVInVec.getOperand(OrigElt);
13542       if (InOp.getValueType() != NVT) {
13543         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13544         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13545       }
13546
13547       return InOp;
13548     }
13549
13550     // FIXME: We should handle recursing on other vector shuffles and
13551     // scalar_to_vector here as well.
13552
13553     if (!LegalOperations) {
13554       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13555       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13556                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13557     }
13558   }
13559
13560   bool BCNumEltsChanged = false;
13561   EVT ExtVT = VT.getVectorElementType();
13562   EVT LVT = ExtVT;
13563
13564   // If the result of load has to be truncated, then it's not necessarily
13565   // profitable.
13566   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13567     return SDValue();
13568
13569   if (InVec.getOpcode() == ISD::BITCAST) {
13570     // Don't duplicate a load with other uses.
13571     if (!InVec.hasOneUse())
13572       return SDValue();
13573
13574     EVT BCVT = InVec.getOperand(0).getValueType();
13575     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13576       return SDValue();
13577     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13578       BCNumEltsChanged = true;
13579     InVec = InVec.getOperand(0);
13580     ExtVT = BCVT.getVectorElementType();
13581   }
13582
13583   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13584   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13585       ISD::isNormalLoad(InVec.getNode()) &&
13586       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13587     SDValue Index = N->getOperand(1);
13588     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13589       if (!OrigLoad->isVolatile()) {
13590         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13591                                                              OrigLoad);
13592       }
13593     }
13594   }
13595
13596   // Perform only after legalization to ensure build_vector / vector_shuffle
13597   // optimizations have already been done.
13598   if (!LegalOperations) return SDValue();
13599
13600   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13601   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13602   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13603
13604   if (ConstEltNo) {
13605     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13606
13607     LoadSDNode *LN0 = nullptr;
13608     const ShuffleVectorSDNode *SVN = nullptr;
13609     if (ISD::isNormalLoad(InVec.getNode())) {
13610       LN0 = cast<LoadSDNode>(InVec);
13611     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13612                InVec.getOperand(0).getValueType() == ExtVT &&
13613                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13614       // Don't duplicate a load with other uses.
13615       if (!InVec.hasOneUse())
13616         return SDValue();
13617
13618       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13619     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13620       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13621       // =>
13622       // (load $addr+1*size)
13623
13624       // Don't duplicate a load with other uses.
13625       if (!InVec.hasOneUse())
13626         return SDValue();
13627
13628       // If the bit convert changed the number of elements, it is unsafe
13629       // to examine the mask.
13630       if (BCNumEltsChanged)
13631         return SDValue();
13632
13633       // Select the input vector, guarding against out of range extract vector.
13634       unsigned NumElems = VT.getVectorNumElements();
13635       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13636       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13637
13638       if (InVec.getOpcode() == ISD::BITCAST) {
13639         // Don't duplicate a load with other uses.
13640         if (!InVec.hasOneUse())
13641           return SDValue();
13642
13643         InVec = InVec.getOperand(0);
13644       }
13645       if (ISD::isNormalLoad(InVec.getNode())) {
13646         LN0 = cast<LoadSDNode>(InVec);
13647         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13648         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13649       }
13650     }
13651
13652     // Make sure we found a non-volatile load and the extractelement is
13653     // the only use.
13654     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13655       return SDValue();
13656
13657     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13658     if (Elt == -1)
13659       return DAG.getUNDEF(LVT);
13660
13661     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13662   }
13663
13664   return SDValue();
13665 }
13666
13667 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13668 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13669   // We perform this optimization post type-legalization because
13670   // the type-legalizer often scalarizes integer-promoted vectors.
13671   // Performing this optimization before may create bit-casts which
13672   // will be type-legalized to complex code sequences.
13673   // We perform this optimization only before the operation legalizer because we
13674   // may introduce illegal operations.
13675   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13676     return SDValue();
13677
13678   unsigned NumInScalars = N->getNumOperands();
13679   SDLoc DL(N);
13680   EVT VT = N->getValueType(0);
13681
13682   // Check to see if this is a BUILD_VECTOR of a bunch of values
13683   // which come from any_extend or zero_extend nodes. If so, we can create
13684   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13685   // optimizations. We do not handle sign-extend because we can't fill the sign
13686   // using shuffles.
13687   EVT SourceType = MVT::Other;
13688   bool AllAnyExt = true;
13689
13690   for (unsigned i = 0; i != NumInScalars; ++i) {
13691     SDValue In = N->getOperand(i);
13692     // Ignore undef inputs.
13693     if (In.isUndef()) continue;
13694
13695     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13696     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13697
13698     // Abort if the element is not an extension.
13699     if (!ZeroExt && !AnyExt) {
13700       SourceType = MVT::Other;
13701       break;
13702     }
13703
13704     // The input is a ZeroExt or AnyExt. Check the original type.
13705     EVT InTy = In.getOperand(0).getValueType();
13706
13707     // Check that all of the widened source types are the same.
13708     if (SourceType == MVT::Other)
13709       // First time.
13710       SourceType = InTy;
13711     else if (InTy != SourceType) {
13712       // Multiple income types. Abort.
13713       SourceType = MVT::Other;
13714       break;
13715     }
13716
13717     // Check if all of the extends are ANY_EXTENDs.
13718     AllAnyExt &= AnyExt;
13719   }
13720
13721   // In order to have valid types, all of the inputs must be extended from the
13722   // same source type and all of the inputs must be any or zero extend.
13723   // Scalar sizes must be a power of two.
13724   EVT OutScalarTy = VT.getScalarType();
13725   bool ValidTypes = SourceType != MVT::Other &&
13726                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13727                  isPowerOf2_32(SourceType.getSizeInBits());
13728
13729   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13730   // turn into a single shuffle instruction.
13731   if (!ValidTypes)
13732     return SDValue();
13733
13734   bool isLE = DAG.getDataLayout().isLittleEndian();
13735   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13736   assert(ElemRatio > 1 && "Invalid element size ratio");
13737   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13738                                DAG.getConstant(0, DL, SourceType);
13739
13740   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13741   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13742
13743   // Populate the new build_vector
13744   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13745     SDValue Cast = N->getOperand(i);
13746     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13747             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13748             Cast.isUndef()) && "Invalid cast opcode");
13749     SDValue In;
13750     if (Cast.isUndef())
13751       In = DAG.getUNDEF(SourceType);
13752     else
13753       In = Cast->getOperand(0);
13754     unsigned Index = isLE ? (i * ElemRatio) :
13755                             (i * ElemRatio + (ElemRatio - 1));
13756
13757     assert(Index < Ops.size() && "Invalid index");
13758     Ops[Index] = In;
13759   }
13760
13761   // The type of the new BUILD_VECTOR node.
13762   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13763   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13764          "Invalid vector size");
13765   // Check if the new vector type is legal.
13766   if (!isTypeLegal(VecVT)) return SDValue();
13767
13768   // Make the new BUILD_VECTOR.
13769   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13770
13771   // The new BUILD_VECTOR node has the potential to be further optimized.
13772   AddToWorklist(BV.getNode());
13773   // Bitcast to the desired type.
13774   return DAG.getBitcast(VT, BV);
13775 }
13776
13777 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13778   EVT VT = N->getValueType(0);
13779
13780   unsigned NumInScalars = N->getNumOperands();
13781   SDLoc DL(N);
13782
13783   EVT SrcVT = MVT::Other;
13784   unsigned Opcode = ISD::DELETED_NODE;
13785   unsigned NumDefs = 0;
13786
13787   for (unsigned i = 0; i != NumInScalars; ++i) {
13788     SDValue In = N->getOperand(i);
13789     unsigned Opc = In.getOpcode();
13790
13791     if (Opc == ISD::UNDEF)
13792       continue;
13793
13794     // If all scalar values are floats and converted from integers.
13795     if (Opcode == ISD::DELETED_NODE &&
13796         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13797       Opcode = Opc;
13798     }
13799
13800     if (Opc != Opcode)
13801       return SDValue();
13802
13803     EVT InVT = In.getOperand(0).getValueType();
13804
13805     // If all scalar values are typed differently, bail out. It's chosen to
13806     // simplify BUILD_VECTOR of integer types.
13807     if (SrcVT == MVT::Other)
13808       SrcVT = InVT;
13809     if (SrcVT != InVT)
13810       return SDValue();
13811     NumDefs++;
13812   }
13813
13814   // If the vector has just one element defined, it's not worth to fold it into
13815   // a vectorized one.
13816   if (NumDefs < 2)
13817     return SDValue();
13818
13819   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13820          && "Should only handle conversion from integer to float.");
13821   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13822
13823   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13824
13825   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13826     return SDValue();
13827
13828   // Just because the floating-point vector type is legal does not necessarily
13829   // mean that the corresponding integer vector type is.
13830   if (!isTypeLegal(NVT))
13831     return SDValue();
13832
13833   SmallVector<SDValue, 8> Opnds;
13834   for (unsigned i = 0; i != NumInScalars; ++i) {
13835     SDValue In = N->getOperand(i);
13836
13837     if (In.isUndef())
13838       Opnds.push_back(DAG.getUNDEF(SrcVT));
13839     else
13840       Opnds.push_back(In.getOperand(0));
13841   }
13842   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13843   AddToWorklist(BV.getNode());
13844
13845   return DAG.getNode(Opcode, DL, VT, BV);
13846 }
13847
13848 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13849                                            ArrayRef<int> VectorMask,
13850                                            SDValue VecIn1, SDValue VecIn2,
13851                                            unsigned LeftIdx) {
13852   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13853   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13854
13855   EVT VT = N->getValueType(0);
13856   EVT InVT1 = VecIn1.getValueType();
13857   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13858
13859   unsigned Vec2Offset = InVT1.getVectorNumElements();
13860   unsigned NumElems = VT.getVectorNumElements();
13861   unsigned ShuffleNumElems = NumElems;
13862
13863   // We can't generate a shuffle node with mismatched input and output types.
13864   // Try to make the types match the type of the output.
13865   if (InVT1 != VT || InVT2 != VT) {
13866     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13867       // If the output vector length is a multiple of both input lengths,
13868       // we can concatenate them and pad the rest with undefs.
13869       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13870       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13871       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13872       ConcatOps[0] = VecIn1;
13873       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13874       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13875       VecIn2 = SDValue();
13876     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13877       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13878         return SDValue();
13879
13880       if (!VecIn2.getNode()) {
13881         // If we only have one input vector, and it's twice the size of the
13882         // output, split it in two.
13883         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13884                              DAG.getConstant(NumElems, DL, IdxTy));
13885         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13886         // Since we now have shorter input vectors, adjust the offset of the
13887         // second vector's start.
13888         Vec2Offset = NumElems;
13889       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13890         // VecIn1 is wider than the output, and we have another, possibly
13891         // smaller input. Pad the smaller input with undefs, shuffle at the
13892         // input vector width, and extract the output.
13893         // The shuffle type is different than VT, so check legality again.
13894         if (LegalOperations &&
13895             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13896           return SDValue();
13897
13898         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13899         // lower it back into a BUILD_VECTOR. So if the inserted type is
13900         // illegal, don't even try.
13901         if (InVT1 != InVT2) {
13902           if (!TLI.isTypeLegal(InVT2))
13903             return SDValue();
13904           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13905                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13906         }
13907         ShuffleNumElems = NumElems * 2;
13908       } else {
13909         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13910         // than VecIn1. We can't handle this for now - this case will disappear
13911         // when we start sorting the vectors by type.
13912         return SDValue();
13913       }
13914     } else {
13915       // TODO: Support cases where the length mismatch isn't exactly by a
13916       // factor of 2.
13917       // TODO: Move this check upwards, so that if we have bad type
13918       // mismatches, we don't create any DAG nodes.
13919       return SDValue();
13920     }
13921   }
13922
13923   // Initialize mask to undef.
13924   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13925
13926   // Only need to run up to the number of elements actually used, not the
13927   // total number of elements in the shuffle - if we are shuffling a wider
13928   // vector, the high lanes should be set to undef.
13929   for (unsigned i = 0; i != NumElems; ++i) {
13930     if (VectorMask[i] <= 0)
13931       continue;
13932
13933     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13934     if (VectorMask[i] == (int)LeftIdx) {
13935       Mask[i] = ExtIndex;
13936     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13937       Mask[i] = Vec2Offset + ExtIndex;
13938     }
13939   }
13940
13941   // The type the input vectors may have changed above.
13942   InVT1 = VecIn1.getValueType();
13943
13944   // If we already have a VecIn2, it should have the same type as VecIn1.
13945   // If we don't, get an undef/zero vector of the appropriate type.
13946   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13947   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13948
13949   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13950   if (ShuffleNumElems > NumElems)
13951     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13952
13953   return Shuffle;
13954 }
13955
13956 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13957 // operations. If the types of the vectors we're extracting from allow it,
13958 // turn this into a vector_shuffle node.
13959 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13960   SDLoc DL(N);
13961   EVT VT = N->getValueType(0);
13962
13963   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13964   if (!isTypeLegal(VT))
13965     return SDValue();
13966
13967   // May only combine to shuffle after legalize if shuffle is legal.
13968   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13969     return SDValue();
13970
13971   bool UsesZeroVector = false;
13972   unsigned NumElems = N->getNumOperands();
13973
13974   // Record, for each element of the newly built vector, which input vector
13975   // that element comes from. -1 stands for undef, 0 for the zero vector,
13976   // and positive values for the input vectors.
13977   // VectorMask maps each element to its vector number, and VecIn maps vector
13978   // numbers to their initial SDValues.
13979
13980   SmallVector<int, 8> VectorMask(NumElems, -1);
13981   SmallVector<SDValue, 8> VecIn;
13982   VecIn.push_back(SDValue());
13983
13984   for (unsigned i = 0; i != NumElems; ++i) {
13985     SDValue Op = N->getOperand(i);
13986
13987     if (Op.isUndef())
13988       continue;
13989
13990     // See if we can use a blend with a zero vector.
13991     // TODO: Should we generalize this to a blend with an arbitrary constant
13992     // vector?
13993     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13994       UsesZeroVector = true;
13995       VectorMask[i] = 0;
13996       continue;
13997     }
13998
13999     // Not an undef or zero. If the input is something other than an
14000     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14001     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14002         !isa<ConstantSDNode>(Op.getOperand(1)))
14003       return SDValue();
14004
14005     SDValue ExtractedFromVec = Op.getOperand(0);
14006
14007     // All inputs must have the same element type as the output.
14008     if (VT.getVectorElementType() !=
14009         ExtractedFromVec.getValueType().getVectorElementType())
14010       return SDValue();
14011
14012     // Have we seen this input vector before?
14013     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14014     // a map back from SDValues to numbers isn't worth it.
14015     unsigned Idx = std::distance(
14016         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14017     if (Idx == VecIn.size())
14018       VecIn.push_back(ExtractedFromVec);
14019
14020     VectorMask[i] = Idx;
14021   }
14022
14023   // If we didn't find at least one input vector, bail out.
14024   if (VecIn.size() < 2)
14025     return SDValue();
14026
14027   // TODO: We want to sort the vectors by descending length, so that adjacent
14028   // pairs have similar length, and the longer vector is always first in the
14029   // pair.
14030
14031   // TODO: Should this fire if some of the input vectors has illegal type (like
14032   // it does now), or should we let legalization run its course first?
14033
14034   // Shuffle phase:
14035   // Take pairs of vectors, and shuffle them so that the result has elements
14036   // from these vectors in the correct places.
14037   // For example, given:
14038   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14039   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14040   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14041   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14042   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14043   // We will generate:
14044   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14045   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14046   SmallVector<SDValue, 4> Shuffles;
14047   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14048     unsigned LeftIdx = 2 * In + 1;
14049     SDValue VecLeft = VecIn[LeftIdx];
14050     SDValue VecRight =
14051         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14052
14053     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14054                                                 VecRight, LeftIdx))
14055       Shuffles.push_back(Shuffle);
14056     else
14057       return SDValue();
14058   }
14059
14060   // If we need the zero vector as an "ingredient" in the blend tree, add it
14061   // to the list of shuffles.
14062   if (UsesZeroVector)
14063     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14064                                       : DAG.getConstantFP(0.0, DL, VT));
14065
14066   // If we only have one shuffle, we're done.
14067   if (Shuffles.size() == 1)
14068     return Shuffles[0];
14069
14070   // Update the vector mask to point to the post-shuffle vectors.
14071   for (int &Vec : VectorMask)
14072     if (Vec == 0)
14073       Vec = Shuffles.size() - 1;
14074     else
14075       Vec = (Vec - 1) / 2;
14076
14077   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14078   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14079   // generate:
14080   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14081   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14082   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14083   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14084   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14085   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14086   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14087
14088   // Make sure the initial size of the shuffle list is even.
14089   if (Shuffles.size() % 2)
14090     Shuffles.push_back(DAG.getUNDEF(VT));
14091
14092   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14093     if (CurSize % 2) {
14094       Shuffles[CurSize] = DAG.getUNDEF(VT);
14095       CurSize++;
14096     }
14097     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14098       int Left = 2 * In;
14099       int Right = 2 * In + 1;
14100       SmallVector<int, 8> Mask(NumElems, -1);
14101       for (unsigned i = 0; i != NumElems; ++i) {
14102         if (VectorMask[i] == Left) {
14103           Mask[i] = i;
14104           VectorMask[i] = In;
14105         } else if (VectorMask[i] == Right) {
14106           Mask[i] = i + NumElems;
14107           VectorMask[i] = In;
14108         }
14109       }
14110
14111       Shuffles[In] =
14112           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14113     }
14114   }
14115
14116   return Shuffles[0];
14117 }
14118
14119 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14120   EVT VT = N->getValueType(0);
14121
14122   // A vector built entirely of undefs is undef.
14123   if (ISD::allOperandsUndef(N))
14124     return DAG.getUNDEF(VT);
14125
14126   // Check if we can express BUILD VECTOR via subvector extract.
14127   if (!LegalTypes && (N->getNumOperands() > 1)) {
14128     SDValue Op0 = N->getOperand(0);
14129     auto checkElem = [&](SDValue Op) -> uint64_t {
14130       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14131           (Op0.getOperand(0) == Op.getOperand(0)))
14132         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14133           return CNode->getZExtValue();
14134       return -1;
14135     };
14136
14137     int Offset = checkElem(Op0);
14138     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14139       if (Offset + i != checkElem(N->getOperand(i))) {
14140         Offset = -1;
14141         break;
14142       }
14143     }
14144
14145     if ((Offset == 0) &&
14146         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14147       return Op0.getOperand(0);
14148     if ((Offset != -1) &&
14149         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14150          0)) // IDX must be multiple of output size.
14151       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14152                          Op0.getOperand(0), Op0.getOperand(1));
14153   }
14154
14155   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14156     return V;
14157
14158   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14159     return V;
14160
14161   if (SDValue V = reduceBuildVecToShuffle(N))
14162     return V;
14163
14164   return SDValue();
14165 }
14166
14167 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14169   EVT OpVT = N->getOperand(0).getValueType();
14170
14171   // If the operands are legal vectors, leave them alone.
14172   if (TLI.isTypeLegal(OpVT))
14173     return SDValue();
14174
14175   SDLoc DL(N);
14176   EVT VT = N->getValueType(0);
14177   SmallVector<SDValue, 8> Ops;
14178
14179   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14180   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14181
14182   // Keep track of what we encounter.
14183   bool AnyInteger = false;
14184   bool AnyFP = false;
14185   for (const SDValue &Op : N->ops()) {
14186     if (ISD::BITCAST == Op.getOpcode() &&
14187         !Op.getOperand(0).getValueType().isVector())
14188       Ops.push_back(Op.getOperand(0));
14189     else if (ISD::UNDEF == Op.getOpcode())
14190       Ops.push_back(ScalarUndef);
14191     else
14192       return SDValue();
14193
14194     // Note whether we encounter an integer or floating point scalar.
14195     // If it's neither, bail out, it could be something weird like x86mmx.
14196     EVT LastOpVT = Ops.back().getValueType();
14197     if (LastOpVT.isFloatingPoint())
14198       AnyFP = true;
14199     else if (LastOpVT.isInteger())
14200       AnyInteger = true;
14201     else
14202       return SDValue();
14203   }
14204
14205   // If any of the operands is a floating point scalar bitcast to a vector,
14206   // use floating point types throughout, and bitcast everything.
14207   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14208   if (AnyFP) {
14209     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14210     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14211     if (AnyInteger) {
14212       for (SDValue &Op : Ops) {
14213         if (Op.getValueType() == SVT)
14214           continue;
14215         if (Op.isUndef())
14216           Op = ScalarUndef;
14217         else
14218           Op = DAG.getBitcast(SVT, Op);
14219       }
14220     }
14221   }
14222
14223   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14224                                VT.getSizeInBits() / SVT.getSizeInBits());
14225   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14226 }
14227
14228 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14229 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14230 // most two distinct vectors the same size as the result, attempt to turn this
14231 // into a legal shuffle.
14232 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14233   EVT VT = N->getValueType(0);
14234   EVT OpVT = N->getOperand(0).getValueType();
14235   int NumElts = VT.getVectorNumElements();
14236   int NumOpElts = OpVT.getVectorNumElements();
14237
14238   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14239   SmallVector<int, 8> Mask;
14240
14241   for (SDValue Op : N->ops()) {
14242     // Peek through any bitcast.
14243     while (Op.getOpcode() == ISD::BITCAST)
14244       Op = Op.getOperand(0);
14245
14246     // UNDEF nodes convert to UNDEF shuffle mask values.
14247     if (Op.isUndef()) {
14248       Mask.append((unsigned)NumOpElts, -1);
14249       continue;
14250     }
14251
14252     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14253       return SDValue();
14254
14255     // What vector are we extracting the subvector from and at what index?
14256     SDValue ExtVec = Op.getOperand(0);
14257
14258     // We want the EVT of the original extraction to correctly scale the
14259     // extraction index.
14260     EVT ExtVT = ExtVec.getValueType();
14261
14262     // Peek through any bitcast.
14263     while (ExtVec.getOpcode() == ISD::BITCAST)
14264       ExtVec = ExtVec.getOperand(0);
14265
14266     // UNDEF nodes convert to UNDEF shuffle mask values.
14267     if (ExtVec.isUndef()) {
14268       Mask.append((unsigned)NumOpElts, -1);
14269       continue;
14270     }
14271
14272     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14273       return SDValue();
14274     int ExtIdx = Op.getConstantOperandVal(1);
14275
14276     // Ensure that we are extracting a subvector from a vector the same
14277     // size as the result.
14278     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14279       return SDValue();
14280
14281     // Scale the subvector index to account for any bitcast.
14282     int NumExtElts = ExtVT.getVectorNumElements();
14283     if (0 == (NumExtElts % NumElts))
14284       ExtIdx /= (NumExtElts / NumElts);
14285     else if (0 == (NumElts % NumExtElts))
14286       ExtIdx *= (NumElts / NumExtElts);
14287     else
14288       return SDValue();
14289
14290     // At most we can reference 2 inputs in the final shuffle.
14291     if (SV0.isUndef() || SV0 == ExtVec) {
14292       SV0 = ExtVec;
14293       for (int i = 0; i != NumOpElts; ++i)
14294         Mask.push_back(i + ExtIdx);
14295     } else if (SV1.isUndef() || SV1 == ExtVec) {
14296       SV1 = ExtVec;
14297       for (int i = 0; i != NumOpElts; ++i)
14298         Mask.push_back(i + ExtIdx + NumElts);
14299     } else {
14300       return SDValue();
14301     }
14302   }
14303
14304   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14305     return SDValue();
14306
14307   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14308                               DAG.getBitcast(VT, SV1), Mask);
14309 }
14310
14311 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14312   // If we only have one input vector, we don't need to do any concatenation.
14313   if (N->getNumOperands() == 1)
14314     return N->getOperand(0);
14315
14316   // Check if all of the operands are undefs.
14317   EVT VT = N->getValueType(0);
14318   if (ISD::allOperandsUndef(N))
14319     return DAG.getUNDEF(VT);
14320
14321   // Optimize concat_vectors where all but the first of the vectors are undef.
14322   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14323         return Op.isUndef();
14324       })) {
14325     SDValue In = N->getOperand(0);
14326     assert(In.getValueType().isVector() && "Must concat vectors");
14327
14328     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14329     if (In->getOpcode() == ISD::BITCAST &&
14330         !In->getOperand(0)->getValueType(0).isVector()) {
14331       SDValue Scalar = In->getOperand(0);
14332
14333       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14334       // look through the trunc so we can still do the transform:
14335       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14336       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14337           !TLI.isTypeLegal(Scalar.getValueType()) &&
14338           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14339         Scalar = Scalar->getOperand(0);
14340
14341       EVT SclTy = Scalar->getValueType(0);
14342
14343       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14344         return SDValue();
14345
14346       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14347       if (VNTNumElms < 2)
14348         return SDValue();
14349
14350       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14351       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14352         return SDValue();
14353
14354       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14355       return DAG.getBitcast(VT, Res);
14356     }
14357   }
14358
14359   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14360   // We have already tested above for an UNDEF only concatenation.
14361   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14362   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14363   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14364     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14365   };
14366   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14367     SmallVector<SDValue, 8> Opnds;
14368     EVT SVT = VT.getScalarType();
14369
14370     EVT MinVT = SVT;
14371     if (!SVT.isFloatingPoint()) {
14372       // If BUILD_VECTOR are from built from integer, they may have different
14373       // operand types. Get the smallest type and truncate all operands to it.
14374       bool FoundMinVT = false;
14375       for (const SDValue &Op : N->ops())
14376         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14377           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14378           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14379           FoundMinVT = true;
14380         }
14381       assert(FoundMinVT && "Concat vector type mismatch");
14382     }
14383
14384     for (const SDValue &Op : N->ops()) {
14385       EVT OpVT = Op.getValueType();
14386       unsigned NumElts = OpVT.getVectorNumElements();
14387
14388       if (ISD::UNDEF == Op.getOpcode())
14389         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14390
14391       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14392         if (SVT.isFloatingPoint()) {
14393           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14394           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14395         } else {
14396           for (unsigned i = 0; i != NumElts; ++i)
14397             Opnds.push_back(
14398                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14399         }
14400       }
14401     }
14402
14403     assert(VT.getVectorNumElements() == Opnds.size() &&
14404            "Concat vector type mismatch");
14405     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14406   }
14407
14408   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14409   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14410     return V;
14411
14412   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14413   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14414     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14415       return V;
14416
14417   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14418   // nodes often generate nop CONCAT_VECTOR nodes.
14419   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14420   // place the incoming vectors at the exact same location.
14421   SDValue SingleSource = SDValue();
14422   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14423
14424   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14425     SDValue Op = N->getOperand(i);
14426
14427     if (Op.isUndef())
14428       continue;
14429
14430     // Check if this is the identity extract:
14431     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14432       return SDValue();
14433
14434     // Find the single incoming vector for the extract_subvector.
14435     if (SingleSource.getNode()) {
14436       if (Op.getOperand(0) != SingleSource)
14437         return SDValue();
14438     } else {
14439       SingleSource = Op.getOperand(0);
14440
14441       // Check the source type is the same as the type of the result.
14442       // If not, this concat may extend the vector, so we can not
14443       // optimize it away.
14444       if (SingleSource.getValueType() != N->getValueType(0))
14445         return SDValue();
14446     }
14447
14448     unsigned IdentityIndex = i * PartNumElem;
14449     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14450     // The extract index must be constant.
14451     if (!CS)
14452       return SDValue();
14453
14454     // Check that we are reading from the identity index.
14455     if (CS->getZExtValue() != IdentityIndex)
14456       return SDValue();
14457   }
14458
14459   if (SingleSource.getNode())
14460     return SingleSource;
14461
14462   return SDValue();
14463 }
14464
14465 /// If we are extracting a subvector produced by a wide binary operator with at
14466 /// at least one operand that was the result of a vector concatenation, then try
14467 /// to use the narrow vector operands directly to avoid the concatenation and
14468 /// extraction.
14469 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14470   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14471   // some of these bailouts with other transforms.
14472
14473   // The extract index must be a constant, so we can map it to a concat operand.
14474   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14475   if (!ExtractIndex)
14476     return SDValue();
14477
14478   // Only handle the case where we are doubling and then halving. A larger ratio
14479   // may require more than two narrow binops to replace the wide binop.
14480   EVT VT = Extract->getValueType(0);
14481   unsigned NumElems = VT.getVectorNumElements();
14482   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14483          "Extract index is not a multiple of the vector length.");
14484   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14485     return SDValue();
14486
14487   // We are looking for an optionally bitcasted wide vector binary operator
14488   // feeding an extract subvector.
14489   SDValue BinOp = Extract->getOperand(0);
14490   if (BinOp.getOpcode() == ISD::BITCAST)
14491     BinOp = BinOp.getOperand(0);
14492
14493   // TODO: The motivating case for this transform is an x86 AVX1 target. That
14494   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14495   // flavors, but no other 256-bit integer support. This could be extended to
14496   // handle any binop, but that may require fixing/adding other folds to avoid
14497   // codegen regressions.
14498   unsigned BOpcode = BinOp.getOpcode();
14499   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14500     return SDValue();
14501
14502   // The binop must be a vector type, so we can chop it in half.
14503   EVT WideBVT = BinOp.getValueType();
14504   if (!WideBVT.isVector())
14505     return SDValue();
14506
14507   // Bail out if the target does not support a narrower version of the binop.
14508   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14509                                    WideBVT.getVectorNumElements() / 2);
14510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14511   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14512     return SDValue();
14513
14514   // Peek through bitcasts of the binary operator operands if needed.
14515   SDValue LHS = BinOp.getOperand(0);
14516   if (LHS.getOpcode() == ISD::BITCAST)
14517     LHS = LHS.getOperand(0);
14518
14519   SDValue RHS = BinOp.getOperand(1);
14520   if (RHS.getOpcode() == ISD::BITCAST)
14521     RHS = RHS.getOperand(0);
14522
14523   // We need at least one concatenation operation of a binop operand to make
14524   // this transform worthwhile. The concat must double the input vector sizes.
14525   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14526   bool ConcatL =
14527       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14528   bool ConcatR =
14529       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14530   if (!ConcatL && !ConcatR)
14531     return SDValue();
14532
14533   // If one of the binop operands was not the result of a concat, we must
14534   // extract a half-sized operand for our new narrow binop. We can't just reuse
14535   // the original extract index operand because we may have bitcasted.
14536   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14537   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14538   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14539   SDLoc DL(Extract);
14540
14541   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14542   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14543   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14544   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14545                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14546                                     BinOp.getOperand(0),
14547                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14548
14549   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14550                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14551                                     BinOp.getOperand(1),
14552                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14553
14554   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14555   return DAG.getBitcast(VT, NarrowBinOp);
14556 }
14557
14558 /// If we are extracting a subvector from a wide vector load, convert to a
14559 /// narrow load to eliminate the extraction:
14560 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14561 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14562   // TODO: Add support for big-endian. The offset calculation must be adjusted.
14563   if (DAG.getDataLayout().isBigEndian())
14564     return SDValue();
14565
14566   // TODO: The one-use check is overly conservative. Check the cost of the
14567   // extract instead or remove that condition entirely.
14568   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14569   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14570   if (!Ld || !Ld->hasOneUse() || Ld->isVolatile() || !ExtIdx)
14571     return SDValue();
14572
14573   // The narrow load will be offset from the base address of the old load if
14574   // we are extracting from something besides index 0 (little-endian).
14575   EVT VT = Extract->getValueType(0);
14576   SDLoc DL(Extract);
14577   SDValue BaseAddr = Ld->getOperand(1);
14578   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14579
14580   // TODO: Use "BaseIndexOffset" to make this more effective.
14581   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
14582   MachineFunction &MF = DAG.getMachineFunction();
14583   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
14584                                                    VT.getStoreSize());
14585   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
14586
14587   // The new load must have the same position as the old load in terms of memory
14588   // dependency. Create a TokenFactor for Ld and NewLd and update uses of Ld's
14589   // output chain to use that TokenFactor.
14590   // TODO: This code is based on a similar sequence in x86 lowering. It should
14591   // be moved to a helper function, so it can be shared and reused.
14592   if (Ld->hasAnyUseOfValue(1)) {
14593     SDValue OldChain = SDValue(Ld, 1);
14594     SDValue NewChain = SDValue(NewLd.getNode(), 1);
14595     SDValue TokenFactor = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14596                                       OldChain, NewChain);
14597     DAG.ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
14598     DAG.UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
14599   }
14600
14601   return NewLd;
14602 }
14603
14604 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14605   EVT NVT = N->getValueType(0);
14606   SDValue V = N->getOperand(0);
14607
14608   // Extract from UNDEF is UNDEF.
14609   if (V.isUndef())
14610     return DAG.getUNDEF(NVT);
14611
14612   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
14613     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
14614       return NarrowLoad;
14615
14616   // Combine:
14617   //    (extract_subvec (concat V1, V2, ...), i)
14618   // Into:
14619   //    Vi if possible
14620   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14621   // type.
14622   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14623       isa<ConstantSDNode>(N->getOperand(1)) &&
14624       V->getOperand(0).getValueType() == NVT) {
14625     unsigned Idx = N->getConstantOperandVal(1);
14626     unsigned NumElems = NVT.getVectorNumElements();
14627     assert((Idx % NumElems) == 0 &&
14628            "IDX in concat is not a multiple of the result vector length.");
14629     return V->getOperand(Idx / NumElems);
14630   }
14631
14632   // Skip bitcasting
14633   if (V->getOpcode() == ISD::BITCAST)
14634     V = V.getOperand(0);
14635
14636   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14637     // Handle only simple case where vector being inserted and vector
14638     // being extracted are of same size.
14639     EVT SmallVT = V->getOperand(1).getValueType();
14640     if (!NVT.bitsEq(SmallVT))
14641       return SDValue();
14642
14643     // Only handle cases where both indexes are constants.
14644     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14645     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14646
14647     if (InsIdx && ExtIdx) {
14648       // Combine:
14649       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14650       // Into:
14651       //    indices are equal or bit offsets are equal => V1
14652       //    otherwise => (extract_subvec V1, ExtIdx)
14653       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14654           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14655         return DAG.getBitcast(NVT, V->getOperand(1));
14656       return DAG.getNode(
14657           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14658           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14659           N->getOperand(1));
14660     }
14661   }
14662
14663   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
14664     return NarrowBOp;
14665
14666   return SDValue();
14667 }
14668
14669 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14670                                                  SDValue V, SelectionDAG &DAG) {
14671   SDLoc DL(V);
14672   EVT VT = V.getValueType();
14673
14674   switch (V.getOpcode()) {
14675   default:
14676     return V;
14677
14678   case ISD::CONCAT_VECTORS: {
14679     EVT OpVT = V->getOperand(0).getValueType();
14680     int OpSize = OpVT.getVectorNumElements();
14681     SmallBitVector OpUsedElements(OpSize, false);
14682     bool FoundSimplification = false;
14683     SmallVector<SDValue, 4> NewOps;
14684     NewOps.reserve(V->getNumOperands());
14685     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14686       SDValue Op = V->getOperand(i);
14687       bool OpUsed = false;
14688       for (int j = 0; j < OpSize; ++j)
14689         if (UsedElements[i * OpSize + j]) {
14690           OpUsedElements[j] = true;
14691           OpUsed = true;
14692         }
14693       NewOps.push_back(
14694           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14695                  : DAG.getUNDEF(OpVT));
14696       FoundSimplification |= Op == NewOps.back();
14697       OpUsedElements.reset();
14698     }
14699     if (FoundSimplification)
14700       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14701     return V;
14702   }
14703
14704   case ISD::INSERT_SUBVECTOR: {
14705     SDValue BaseV = V->getOperand(0);
14706     SDValue SubV = V->getOperand(1);
14707     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14708     if (!IdxN)
14709       return V;
14710
14711     int SubSize = SubV.getValueType().getVectorNumElements();
14712     int Idx = IdxN->getZExtValue();
14713     bool SubVectorUsed = false;
14714     SmallBitVector SubUsedElements(SubSize, false);
14715     for (int i = 0; i < SubSize; ++i)
14716       if (UsedElements[i + Idx]) {
14717         SubVectorUsed = true;
14718         SubUsedElements[i] = true;
14719         UsedElements[i + Idx] = false;
14720       }
14721
14722     // Now recurse on both the base and sub vectors.
14723     SDValue SimplifiedSubV =
14724         SubVectorUsed
14725             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14726             : DAG.getUNDEF(SubV.getValueType());
14727     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14728     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14729       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14730                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14731     return V;
14732   }
14733   }
14734 }
14735
14736 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14737                                        SDValue N1, SelectionDAG &DAG) {
14738   EVT VT = SVN->getValueType(0);
14739   int NumElts = VT.getVectorNumElements();
14740   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14741   for (int M : SVN->getMask())
14742     if (M >= 0 && M < NumElts)
14743       N0UsedElements[M] = true;
14744     else if (M >= NumElts)
14745       N1UsedElements[M - NumElts] = true;
14746
14747   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14748   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14749   if (S0 == N0 && S1 == N1)
14750     return SDValue();
14751
14752   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14753 }
14754
14755 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14756 // or turn a shuffle of a single concat into simpler shuffle then concat.
14757 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14758   EVT VT = N->getValueType(0);
14759   unsigned NumElts = VT.getVectorNumElements();
14760
14761   SDValue N0 = N->getOperand(0);
14762   SDValue N1 = N->getOperand(1);
14763   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14764
14765   SmallVector<SDValue, 4> Ops;
14766   EVT ConcatVT = N0.getOperand(0).getValueType();
14767   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14768   unsigned NumConcats = NumElts / NumElemsPerConcat;
14769
14770   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14771   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14772   // half vector elements.
14773   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14774       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14775                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14776     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14777                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14778     N1 = DAG.getUNDEF(ConcatVT);
14779     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14780   }
14781
14782   // Look at every vector that's inserted. We're looking for exact
14783   // subvector-sized copies from a concatenated vector
14784   for (unsigned I = 0; I != NumConcats; ++I) {
14785     // Make sure we're dealing with a copy.
14786     unsigned Begin = I * NumElemsPerConcat;
14787     bool AllUndef = true, NoUndef = true;
14788     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14789       if (SVN->getMaskElt(J) >= 0)
14790         AllUndef = false;
14791       else
14792         NoUndef = false;
14793     }
14794
14795     if (NoUndef) {
14796       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14797         return SDValue();
14798
14799       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14800         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14801           return SDValue();
14802
14803       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14804       if (FirstElt < N0.getNumOperands())
14805         Ops.push_back(N0.getOperand(FirstElt));
14806       else
14807         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14808
14809     } else if (AllUndef) {
14810       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14811     } else { // Mixed with general masks and undefs, can't do optimization.
14812       return SDValue();
14813     }
14814   }
14815
14816   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14817 }
14818
14819 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14820 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14821 //
14822 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14823 // a simplification in some sense, but it isn't appropriate in general: some
14824 // BUILD_VECTORs are substantially cheaper than others. The general case
14825 // of a BUILD_VECTOR requires inserting each element individually (or
14826 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14827 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14828 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14829 // are undef lowers to a small number of element insertions.
14830 //
14831 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14832 // We don't fold shuffles where one side is a non-zero constant, and we don't
14833 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14834 // non-constant operands. This seems to work out reasonably well in practice.
14835 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14836                                        SelectionDAG &DAG,
14837                                        const TargetLowering &TLI) {
14838   EVT VT = SVN->getValueType(0);
14839   unsigned NumElts = VT.getVectorNumElements();
14840   SDValue N0 = SVN->getOperand(0);
14841   SDValue N1 = SVN->getOperand(1);
14842
14843   if (!N0->hasOneUse() || !N1->hasOneUse())
14844     return SDValue();
14845   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14846   // discussed above.
14847   if (!N1.isUndef()) {
14848     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14849     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14850     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14851       return SDValue();
14852     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14853       return SDValue();
14854   }
14855
14856   SmallVector<SDValue, 8> Ops;
14857   SmallSet<SDValue, 16> DuplicateOps;
14858   for (int M : SVN->getMask()) {
14859     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14860     if (M >= 0) {
14861       int Idx = M < (int)NumElts ? M : M - NumElts;
14862       SDValue &S = (M < (int)NumElts ? N0 : N1);
14863       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14864         Op = S.getOperand(Idx);
14865       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14866         if (Idx == 0)
14867           Op = S.getOperand(0);
14868       } else {
14869         // Operand can't be combined - bail out.
14870         return SDValue();
14871       }
14872     }
14873
14874     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14875     // fine, but it's likely to generate low-quality code if the target can't
14876     // reconstruct an appropriate shuffle.
14877     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14878       if (!DuplicateOps.insert(Op).second)
14879         return SDValue();
14880
14881     Ops.push_back(Op);
14882   }
14883   // BUILD_VECTOR requires all inputs to be of the same type, find the
14884   // maximum type and extend them all.
14885   EVT SVT = VT.getScalarType();
14886   if (SVT.isInteger())
14887     for (SDValue &Op : Ops)
14888       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14889   if (SVT != VT.getScalarType())
14890     for (SDValue &Op : Ops)
14891       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14892                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14893                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14894   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14895 }
14896
14897 // Match shuffles that can be converted to any_vector_extend_in_reg.
14898 // This is often generated during legalization.
14899 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14900 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14901 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14902                                             SelectionDAG &DAG,
14903                                             const TargetLowering &TLI,
14904                                             bool LegalOperations) {
14905   EVT VT = SVN->getValueType(0);
14906   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14907
14908   // TODO Add support for big-endian when we have a test case.
14909   if (!VT.isInteger() || IsBigEndian)
14910     return SDValue();
14911
14912   unsigned NumElts = VT.getVectorNumElements();
14913   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14914   ArrayRef<int> Mask = SVN->getMask();
14915   SDValue N0 = SVN->getOperand(0);
14916
14917   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14918   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14919     for (unsigned i = 0; i != NumElts; ++i) {
14920       if (Mask[i] < 0)
14921         continue;
14922       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14923         continue;
14924       return false;
14925     }
14926     return true;
14927   };
14928
14929   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14930   // power-of-2 extensions as they are the most likely.
14931   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14932     if (!isAnyExtend(Scale))
14933       continue;
14934
14935     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14936     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14937     if (!LegalOperations ||
14938         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14939       return DAG.getBitcast(VT,
14940                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14941   }
14942
14943   return SDValue();
14944 }
14945
14946 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14947 // each source element of a large type into the lowest elements of a smaller
14948 // destination type. This is often generated during legalization.
14949 // If the source node itself was a '*_extend_vector_inreg' node then we should
14950 // then be able to remove it.
14951 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
14952                                         SelectionDAG &DAG) {
14953   EVT VT = SVN->getValueType(0);
14954   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14955
14956   // TODO Add support for big-endian when we have a test case.
14957   if (!VT.isInteger() || IsBigEndian)
14958     return SDValue();
14959
14960   SDValue N0 = SVN->getOperand(0);
14961   while (N0.getOpcode() == ISD::BITCAST)
14962     N0 = N0.getOperand(0);
14963
14964   unsigned Opcode = N0.getOpcode();
14965   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14966       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14967       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14968     return SDValue();
14969
14970   SDValue N00 = N0.getOperand(0);
14971   ArrayRef<int> Mask = SVN->getMask();
14972   unsigned NumElts = VT.getVectorNumElements();
14973   unsigned EltSizeInBits = VT.getScalarSizeInBits();
14974   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14975
14976   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14977   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14978   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14979   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14980     for (unsigned i = 0; i != NumElts; ++i) {
14981       if (Mask[i] < 0)
14982         continue;
14983       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14984         continue;
14985       return false;
14986     }
14987     return true;
14988   };
14989
14990   // At the moment we just handle the case where we've truncated back to the
14991   // same size as before the extension.
14992   // TODO: handle more extension/truncation cases as cases arise.
14993   if (EltSizeInBits != ExtSrcSizeInBits)
14994     return SDValue();
14995
14996   // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14997   // power-of-2 truncations as they are the most likely.
14998   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14999     if (isTruncate(Scale))
15000       return DAG.getBitcast(VT, N00);
15001
15002   return SDValue();
15003 }
15004
15005 // Combine shuffles of splat-shuffles of the form:
15006 // shuffle (shuffle V, undef, splat-mask), undef, M
15007 // If splat-mask contains undef elements, we need to be careful about
15008 // introducing undef's in the folded mask which are not the result of composing
15009 // the masks of the shuffles.
15010 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15011                                      ShuffleVectorSDNode *Splat,
15012                                      SelectionDAG &DAG) {
15013   ArrayRef<int> SplatMask = Splat->getMask();
15014   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15015
15016   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15017   // every undef mask element in the splat-shuffle has a corresponding undef
15018   // element in the user-shuffle's mask or if the composition of mask elements
15019   // would result in undef.
15020   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15021   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15022   //   In this case it is not legal to simplify to the splat-shuffle because we
15023   //   may be exposing the users of the shuffle an undef element at index 1
15024   //   which was not there before the combine.
15025   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15026   //   In this case the composition of masks yields SplatMask, so it's ok to
15027   //   simplify to the splat-shuffle.
15028   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15029   //   In this case the composed mask includes all undef elements of SplatMask
15030   //   and in addition sets element zero to undef. It is safe to simplify to
15031   //   the splat-shuffle.
15032   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15033                                        ArrayRef<int> SplatMask) {
15034     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15035       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15036           SplatMask[UserMask[i]] != -1)
15037         return false;
15038     return true;
15039   };
15040   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15041     return SDValue(Splat, 0);
15042
15043   // Create a new shuffle with a mask that is composed of the two shuffles'
15044   // masks.
15045   SmallVector<int, 32> NewMask;
15046   for (int Idx : UserMask)
15047     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15048
15049   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15050                               Splat->getOperand(0), Splat->getOperand(1),
15051                               NewMask);
15052 }
15053
15054 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15055   EVT VT = N->getValueType(0);
15056   unsigned NumElts = VT.getVectorNumElements();
15057
15058   SDValue N0 = N->getOperand(0);
15059   SDValue N1 = N->getOperand(1);
15060
15061   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15062
15063   // Canonicalize shuffle undef, undef -> undef
15064   if (N0.isUndef() && N1.isUndef())
15065     return DAG.getUNDEF(VT);
15066
15067   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15068
15069   // Canonicalize shuffle v, v -> v, undef
15070   if (N0 == N1) {
15071     SmallVector<int, 8> NewMask;
15072     for (unsigned i = 0; i != NumElts; ++i) {
15073       int Idx = SVN->getMaskElt(i);
15074       if (Idx >= (int)NumElts) Idx -= NumElts;
15075       NewMask.push_back(Idx);
15076     }
15077     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15078   }
15079
15080   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15081   if (N0.isUndef())
15082     return DAG.getCommutedVectorShuffle(*SVN);
15083
15084   // Remove references to rhs if it is undef
15085   if (N1.isUndef()) {
15086     bool Changed = false;
15087     SmallVector<int, 8> NewMask;
15088     for (unsigned i = 0; i != NumElts; ++i) {
15089       int Idx = SVN->getMaskElt(i);
15090       if (Idx >= (int)NumElts) {
15091         Idx = -1;
15092         Changed = true;
15093       }
15094       NewMask.push_back(Idx);
15095     }
15096     if (Changed)
15097       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15098   }
15099
15100   // A shuffle of a single vector that is a splat can always be folded.
15101   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15102     if (N1->isUndef() && N0Shuf->isSplat())
15103       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15104
15105   // If it is a splat, check if the argument vector is another splat or a
15106   // build_vector.
15107   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15108     SDNode *V = N0.getNode();
15109
15110     // If this is a bit convert that changes the element type of the vector but
15111     // not the number of vector elements, look through it.  Be careful not to
15112     // look though conversions that change things like v4f32 to v2f64.
15113     if (V->getOpcode() == ISD::BITCAST) {
15114       SDValue ConvInput = V->getOperand(0);
15115       if (ConvInput.getValueType().isVector() &&
15116           ConvInput.getValueType().getVectorNumElements() == NumElts)
15117         V = ConvInput.getNode();
15118     }
15119
15120     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15121       assert(V->getNumOperands() == NumElts &&
15122              "BUILD_VECTOR has wrong number of operands");
15123       SDValue Base;
15124       bool AllSame = true;
15125       for (unsigned i = 0; i != NumElts; ++i) {
15126         if (!V->getOperand(i).isUndef()) {
15127           Base = V->getOperand(i);
15128           break;
15129         }
15130       }
15131       // Splat of <u, u, u, u>, return <u, u, u, u>
15132       if (!Base.getNode())
15133         return N0;
15134       for (unsigned i = 0; i != NumElts; ++i) {
15135         if (V->getOperand(i) != Base) {
15136           AllSame = false;
15137           break;
15138         }
15139       }
15140       // Splat of <x, x, x, x>, return <x, x, x, x>
15141       if (AllSame)
15142         return N0;
15143
15144       // Canonicalize any other splat as a build_vector.
15145       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15146       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15147       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15148
15149       // We may have jumped through bitcasts, so the type of the
15150       // BUILD_VECTOR may not match the type of the shuffle.
15151       if (V->getValueType(0) != VT)
15152         NewBV = DAG.getBitcast(VT, NewBV);
15153       return NewBV;
15154     }
15155   }
15156
15157   // There are various patterns used to build up a vector from smaller vectors,
15158   // subvectors, or elements. Scan chains of these and replace unused insertions
15159   // or components with undef.
15160   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15161     return S;
15162
15163   // Match shuffles that can be converted to any_vector_extend_in_reg.
15164   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15165     return V;
15166
15167   // Combine "truncate_vector_in_reg" style shuffles.
15168   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15169     return V;
15170
15171   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15172       Level < AfterLegalizeVectorOps &&
15173       (N1.isUndef() ||
15174       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15175        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15176     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15177       return V;
15178   }
15179
15180   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15181   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15182   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15183     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15184       return Res;
15185
15186   // If this shuffle only has a single input that is a bitcasted shuffle,
15187   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15188   // back to their original types.
15189   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15190       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15191       TLI.isTypeLegal(VT)) {
15192
15193     // Peek through the bitcast only if there is one user.
15194     SDValue BC0 = N0;
15195     while (BC0.getOpcode() == ISD::BITCAST) {
15196       if (!BC0.hasOneUse())
15197         break;
15198       BC0 = BC0.getOperand(0);
15199     }
15200
15201     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15202       if (Scale == 1)
15203         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15204
15205       SmallVector<int, 8> NewMask;
15206       for (int M : Mask)
15207         for (int s = 0; s != Scale; ++s)
15208           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15209       return NewMask;
15210     };
15211
15212     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15213       EVT SVT = VT.getScalarType();
15214       EVT InnerVT = BC0->getValueType(0);
15215       EVT InnerSVT = InnerVT.getScalarType();
15216
15217       // Determine which shuffle works with the smaller scalar type.
15218       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15219       EVT ScaleSVT = ScaleVT.getScalarType();
15220
15221       if (TLI.isTypeLegal(ScaleVT) &&
15222           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15223           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15224
15225         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15226         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15227
15228         // Scale the shuffle masks to the smaller scalar type.
15229         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15230         SmallVector<int, 8> InnerMask =
15231             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15232         SmallVector<int, 8> OuterMask =
15233             ScaleShuffleMask(SVN->getMask(), OuterScale);
15234
15235         // Merge the shuffle masks.
15236         SmallVector<int, 8> NewMask;
15237         for (int M : OuterMask)
15238           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15239
15240         // Test for shuffle mask legality over both commutations.
15241         SDValue SV0 = BC0->getOperand(0);
15242         SDValue SV1 = BC0->getOperand(1);
15243         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15244         if (!LegalMask) {
15245           std::swap(SV0, SV1);
15246           ShuffleVectorSDNode::commuteMask(NewMask);
15247           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15248         }
15249
15250         if (LegalMask) {
15251           SV0 = DAG.getBitcast(ScaleVT, SV0);
15252           SV1 = DAG.getBitcast(ScaleVT, SV1);
15253           return DAG.getBitcast(
15254               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15255         }
15256       }
15257     }
15258   }
15259
15260   // Canonicalize shuffles according to rules:
15261   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15262   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15263   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15264   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15265       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15266       TLI.isTypeLegal(VT)) {
15267     // The incoming shuffle must be of the same type as the result of the
15268     // current shuffle.
15269     assert(N1->getOperand(0).getValueType() == VT &&
15270            "Shuffle types don't match");
15271
15272     SDValue SV0 = N1->getOperand(0);
15273     SDValue SV1 = N1->getOperand(1);
15274     bool HasSameOp0 = N0 == SV0;
15275     bool IsSV1Undef = SV1.isUndef();
15276     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15277       // Commute the operands of this shuffle so that next rule
15278       // will trigger.
15279       return DAG.getCommutedVectorShuffle(*SVN);
15280   }
15281
15282   // Try to fold according to rules:
15283   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15284   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15285   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15286   // Don't try to fold shuffles with illegal type.
15287   // Only fold if this shuffle is the only user of the other shuffle.
15288   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15289       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15290     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15291
15292     // Don't try to fold splats; they're likely to simplify somehow, or they
15293     // might be free.
15294     if (OtherSV->isSplat())
15295       return SDValue();
15296
15297     // The incoming shuffle must be of the same type as the result of the
15298     // current shuffle.
15299     assert(OtherSV->getOperand(0).getValueType() == VT &&
15300            "Shuffle types don't match");
15301
15302     SDValue SV0, SV1;
15303     SmallVector<int, 4> Mask;
15304     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15305     // operand, and SV1 as the second operand.
15306     for (unsigned i = 0; i != NumElts; ++i) {
15307       int Idx = SVN->getMaskElt(i);
15308       if (Idx < 0) {
15309         // Propagate Undef.
15310         Mask.push_back(Idx);
15311         continue;
15312       }
15313
15314       SDValue CurrentVec;
15315       if (Idx < (int)NumElts) {
15316         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15317         // shuffle mask to identify which vector is actually referenced.
15318         Idx = OtherSV->getMaskElt(Idx);
15319         if (Idx < 0) {
15320           // Propagate Undef.
15321           Mask.push_back(Idx);
15322           continue;
15323         }
15324
15325         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15326                                            : OtherSV->getOperand(1);
15327       } else {
15328         // This shuffle index references an element within N1.
15329         CurrentVec = N1;
15330       }
15331
15332       // Simple case where 'CurrentVec' is UNDEF.
15333       if (CurrentVec.isUndef()) {
15334         Mask.push_back(-1);
15335         continue;
15336       }
15337
15338       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15339       // will be the first or second operand of the combined shuffle.
15340       Idx = Idx % NumElts;
15341       if (!SV0.getNode() || SV0 == CurrentVec) {
15342         // Ok. CurrentVec is the left hand side.
15343         // Update the mask accordingly.
15344         SV0 = CurrentVec;
15345         Mask.push_back(Idx);
15346         continue;
15347       }
15348
15349       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15350       if (SV1.getNode() && SV1 != CurrentVec)
15351         return SDValue();
15352
15353       // Ok. CurrentVec is the right hand side.
15354       // Update the mask accordingly.
15355       SV1 = CurrentVec;
15356       Mask.push_back(Idx + NumElts);
15357     }
15358
15359     // Check if all indices in Mask are Undef. In case, propagate Undef.
15360     bool isUndefMask = true;
15361     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15362       isUndefMask &= Mask[i] < 0;
15363
15364     if (isUndefMask)
15365       return DAG.getUNDEF(VT);
15366
15367     if (!SV0.getNode())
15368       SV0 = DAG.getUNDEF(VT);
15369     if (!SV1.getNode())
15370       SV1 = DAG.getUNDEF(VT);
15371
15372     // Avoid introducing shuffles with illegal mask.
15373     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15374       ShuffleVectorSDNode::commuteMask(Mask);
15375
15376       if (!TLI.isShuffleMaskLegal(Mask, VT))
15377         return SDValue();
15378
15379       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15380       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15381       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15382       std::swap(SV0, SV1);
15383     }
15384
15385     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15386     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15387     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15388     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15389   }
15390
15391   return SDValue();
15392 }
15393
15394 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15395   SDValue InVal = N->getOperand(0);
15396   EVT VT = N->getValueType(0);
15397
15398   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15399   // with a VECTOR_SHUFFLE.
15400   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15401     SDValue InVec = InVal->getOperand(0);
15402     SDValue EltNo = InVal->getOperand(1);
15403
15404     // FIXME: We could support implicit truncation if the shuffle can be
15405     // scaled to a smaller vector scalar type.
15406     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15407     if (C0 && VT == InVec.getValueType() &&
15408         VT.getScalarType() == InVal.getValueType()) {
15409       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15410       int Elt = C0->getZExtValue();
15411       NewMask[0] = Elt;
15412
15413       if (TLI.isShuffleMaskLegal(NewMask, VT))
15414         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15415                                     NewMask);
15416     }
15417   }
15418
15419   return SDValue();
15420 }
15421
15422 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15423   EVT VT = N->getValueType(0);
15424   SDValue N0 = N->getOperand(0);
15425   SDValue N1 = N->getOperand(1);
15426   SDValue N2 = N->getOperand(2);
15427
15428   // If inserting an UNDEF, just return the original vector.
15429   if (N1.isUndef())
15430     return N0;
15431
15432   // If this is an insert of an extracted vector into an undef vector, we can
15433   // just use the input to the extract.
15434   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15435       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15436     return N1.getOperand(0);
15437
15438   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15439   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15440   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15441   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15442       N0.getOperand(1).getValueType() == N1.getValueType() &&
15443       N0.getOperand(2) == N2)
15444     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15445                        N1, N2);
15446
15447   if (!isa<ConstantSDNode>(N2))
15448     return SDValue();
15449
15450   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15451
15452   // Canonicalize insert_subvector dag nodes.
15453   // Example:
15454   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15455   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15456   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15457       N1.getValueType() == N0.getOperand(1).getValueType() &&
15458       isa<ConstantSDNode>(N0.getOperand(2))) {
15459     unsigned OtherIdx = N0.getConstantOperandVal(2);
15460     if (InsIdx < OtherIdx) {
15461       // Swap nodes.
15462       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15463                                   N0.getOperand(0), N1, N2);
15464       AddToWorklist(NewOp.getNode());
15465       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15466                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15467     }
15468   }
15469
15470   // If the input vector is a concatenation, and the insert replaces
15471   // one of the pieces, we can optimize into a single concat_vectors.
15472   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15473       N0.getOperand(0).getValueType() == N1.getValueType()) {
15474     unsigned Factor = N1.getValueType().getVectorNumElements();
15475
15476     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15477     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15478
15479     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15480   }
15481
15482   return SDValue();
15483 }
15484
15485 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15486   SDValue N0 = N->getOperand(0);
15487
15488   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15489   if (N0->getOpcode() == ISD::FP16_TO_FP)
15490     return N0->getOperand(0);
15491
15492   return SDValue();
15493 }
15494
15495 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15496   SDValue N0 = N->getOperand(0);
15497
15498   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15499   if (N0->getOpcode() == ISD::AND) {
15500     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15501     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15502       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15503                          N0.getOperand(0));
15504     }
15505   }
15506
15507   return SDValue();
15508 }
15509
15510 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15511 /// with the destination vector and a zero vector.
15512 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15513 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15514 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15515   EVT VT = N->getValueType(0);
15516   SDValue LHS = N->getOperand(0);
15517   SDValue RHS = N->getOperand(1);
15518   SDLoc DL(N);
15519
15520   // Make sure we're not running after operation legalization where it
15521   // may have custom lowered the vector shuffles.
15522   if (LegalOperations)
15523     return SDValue();
15524
15525   if (N->getOpcode() != ISD::AND)
15526     return SDValue();
15527
15528   if (RHS.getOpcode() == ISD::BITCAST)
15529     RHS = RHS.getOperand(0);
15530
15531   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15532     return SDValue();
15533
15534   EVT RVT = RHS.getValueType();
15535   unsigned NumElts = RHS.getNumOperands();
15536
15537   // Attempt to create a valid clear mask, splitting the mask into
15538   // sub elements and checking to see if each is
15539   // all zeros or all ones - suitable for shuffle masking.
15540   auto BuildClearMask = [&](int Split) {
15541     int NumSubElts = NumElts * Split;
15542     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15543
15544     SmallVector<int, 8> Indices;
15545     for (int i = 0; i != NumSubElts; ++i) {
15546       int EltIdx = i / Split;
15547       int SubIdx = i % Split;
15548       SDValue Elt = RHS.getOperand(EltIdx);
15549       if (Elt.isUndef()) {
15550         Indices.push_back(-1);
15551         continue;
15552       }
15553
15554       APInt Bits;
15555       if (isa<ConstantSDNode>(Elt))
15556         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15557       else if (isa<ConstantFPSDNode>(Elt))
15558         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15559       else
15560         return SDValue();
15561
15562       // Extract the sub element from the constant bit mask.
15563       if (DAG.getDataLayout().isBigEndian()) {
15564         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15565       } else {
15566         Bits.lshrInPlace(SubIdx * NumSubBits);
15567       }
15568
15569       if (Split > 1)
15570         Bits = Bits.trunc(NumSubBits);
15571
15572       if (Bits.isAllOnesValue())
15573         Indices.push_back(i);
15574       else if (Bits == 0)
15575         Indices.push_back(i + NumSubElts);
15576       else
15577         return SDValue();
15578     }
15579
15580     // Let's see if the target supports this vector_shuffle.
15581     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15582     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15583     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15584       return SDValue();
15585
15586     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15587     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15588                                                    DAG.getBitcast(ClearVT, LHS),
15589                                                    Zero, Indices));
15590   };
15591
15592   // Determine maximum split level (byte level masking).
15593   int MaxSplit = 1;
15594   if (RVT.getScalarSizeInBits() % 8 == 0)
15595     MaxSplit = RVT.getScalarSizeInBits() / 8;
15596
15597   for (int Split = 1; Split <= MaxSplit; ++Split)
15598     if (RVT.getScalarSizeInBits() % Split == 0)
15599       if (SDValue S = BuildClearMask(Split))
15600         return S;
15601
15602   return SDValue();
15603 }
15604
15605 /// Visit a binary vector operation, like ADD.
15606 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15607   assert(N->getValueType(0).isVector() &&
15608          "SimplifyVBinOp only works on vectors!");
15609
15610   SDValue LHS = N->getOperand(0);
15611   SDValue RHS = N->getOperand(1);
15612   SDValue Ops[] = {LHS, RHS};
15613
15614   // See if we can constant fold the vector operation.
15615   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15616           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15617     return Fold;
15618
15619   // Try to convert a constant mask AND into a shuffle clear mask.
15620   if (SDValue Shuffle = XformToShuffleWithZero(N))
15621     return Shuffle;
15622
15623   // Type legalization might introduce new shuffles in the DAG.
15624   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15625   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15626   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15627       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15628       LHS.getOperand(1).isUndef() &&
15629       RHS.getOperand(1).isUndef()) {
15630     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15631     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15632
15633     if (SVN0->getMask().equals(SVN1->getMask())) {
15634       EVT VT = N->getValueType(0);
15635       SDValue UndefVector = LHS.getOperand(1);
15636       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15637                                      LHS.getOperand(0), RHS.getOperand(0),
15638                                      N->getFlags());
15639       AddUsersToWorklist(N);
15640       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15641                                   SVN0->getMask());
15642     }
15643   }
15644
15645   return SDValue();
15646 }
15647
15648 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15649                                     SDValue N2) {
15650   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15651
15652   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15653                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15654
15655   // If we got a simplified select_cc node back from SimplifySelectCC, then
15656   // break it down into a new SETCC node, and a new SELECT node, and then return
15657   // the SELECT node, since we were called with a SELECT node.
15658   if (SCC.getNode()) {
15659     // Check to see if we got a select_cc back (to turn into setcc/select).
15660     // Otherwise, just return whatever node we got back, like fabs.
15661     if (SCC.getOpcode() == ISD::SELECT_CC) {
15662       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15663                                   N0.getValueType(),
15664                                   SCC.getOperand(0), SCC.getOperand(1),
15665                                   SCC.getOperand(4));
15666       AddToWorklist(SETCC.getNode());
15667       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15668                            SCC.getOperand(2), SCC.getOperand(3));
15669     }
15670
15671     return SCC;
15672   }
15673   return SDValue();
15674 }
15675
15676 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15677 /// being selected between, see if we can simplify the select.  Callers of this
15678 /// should assume that TheSelect is deleted if this returns true.  As such, they
15679 /// should return the appropriate thing (e.g. the node) back to the top-level of
15680 /// the DAG combiner loop to avoid it being looked at.
15681 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15682                                     SDValue RHS) {
15683
15684   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15685   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15686   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15687     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15688       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15689       SDValue Sqrt = RHS;
15690       ISD::CondCode CC;
15691       SDValue CmpLHS;
15692       const ConstantFPSDNode *Zero = nullptr;
15693
15694       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15695         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15696         CmpLHS = TheSelect->getOperand(0);
15697         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15698       } else {
15699         // SELECT or VSELECT
15700         SDValue Cmp = TheSelect->getOperand(0);
15701         if (Cmp.getOpcode() == ISD::SETCC) {
15702           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15703           CmpLHS = Cmp.getOperand(0);
15704           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15705         }
15706       }
15707       if (Zero && Zero->isZero() &&
15708           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15709           CC == ISD::SETULT || CC == ISD::SETLT)) {
15710         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15711         CombineTo(TheSelect, Sqrt);
15712         return true;
15713       }
15714     }
15715   }
15716   // Cannot simplify select with vector condition
15717   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15718
15719   // If this is a select from two identical things, try to pull the operation
15720   // through the select.
15721   if (LHS.getOpcode() != RHS.getOpcode() ||
15722       !LHS.hasOneUse() || !RHS.hasOneUse())
15723     return false;
15724
15725   // If this is a load and the token chain is identical, replace the select
15726   // of two loads with a load through a select of the address to load from.
15727   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15728   // constants have been dropped into the constant pool.
15729   if (LHS.getOpcode() == ISD::LOAD) {
15730     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15731     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15732
15733     // Token chains must be identical.
15734     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15735         // Do not let this transformation reduce the number of volatile loads.
15736         LLD->isVolatile() || RLD->isVolatile() ||
15737         // FIXME: If either is a pre/post inc/dec load,
15738         // we'd need to split out the address adjustment.
15739         LLD->isIndexed() || RLD->isIndexed() ||
15740         // If this is an EXTLOAD, the VT's must match.
15741         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15742         // If this is an EXTLOAD, the kind of extension must match.
15743         (LLD->getExtensionType() != RLD->getExtensionType() &&
15744          // The only exception is if one of the extensions is anyext.
15745          LLD->getExtensionType() != ISD::EXTLOAD &&
15746          RLD->getExtensionType() != ISD::EXTLOAD) ||
15747         // FIXME: this discards src value information.  This is
15748         // over-conservative. It would be beneficial to be able to remember
15749         // both potential memory locations.  Since we are discarding
15750         // src value info, don't do the transformation if the memory
15751         // locations are not in the default address space.
15752         LLD->getPointerInfo().getAddrSpace() != 0 ||
15753         RLD->getPointerInfo().getAddrSpace() != 0 ||
15754         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15755                                       LLD->getBasePtr().getValueType()))
15756       return false;
15757
15758     // Check that the select condition doesn't reach either load.  If so,
15759     // folding this will induce a cycle into the DAG.  If not, this is safe to
15760     // xform, so create a select of the addresses.
15761     SDValue Addr;
15762     if (TheSelect->getOpcode() == ISD::SELECT) {
15763       SDNode *CondNode = TheSelect->getOperand(0).getNode();
15764       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15765           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15766         return false;
15767       // The loads must not depend on one another.
15768       if (LLD->isPredecessorOf(RLD) ||
15769           RLD->isPredecessorOf(LLD))
15770         return false;
15771       Addr = DAG.getSelect(SDLoc(TheSelect),
15772                            LLD->getBasePtr().getValueType(),
15773                            TheSelect->getOperand(0), LLD->getBasePtr(),
15774                            RLD->getBasePtr());
15775     } else {  // Otherwise SELECT_CC
15776       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15777       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15778
15779       if ((LLD->hasAnyUseOfValue(1) &&
15780            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15781           (RLD->hasAnyUseOfValue(1) &&
15782            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15783         return false;
15784
15785       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15786                          LLD->getBasePtr().getValueType(),
15787                          TheSelect->getOperand(0),
15788                          TheSelect->getOperand(1),
15789                          LLD->getBasePtr(), RLD->getBasePtr(),
15790                          TheSelect->getOperand(4));
15791     }
15792
15793     SDValue Load;
15794     // It is safe to replace the two loads if they have different alignments,
15795     // but the new load must be the minimum (most restrictive) alignment of the
15796     // inputs.
15797     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15798     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15799     if (!RLD->isInvariant())
15800       MMOFlags &= ~MachineMemOperand::MOInvariant;
15801     if (!RLD->isDereferenceable())
15802       MMOFlags &= ~MachineMemOperand::MODereferenceable;
15803     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15804       // FIXME: Discards pointer and AA info.
15805       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15806                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15807                          MMOFlags);
15808     } else {
15809       // FIXME: Discards pointer and AA info.
15810       Load = DAG.getExtLoad(
15811           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15812                                                   : LLD->getExtensionType(),
15813           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15814           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15815     }
15816
15817     // Users of the select now use the result of the load.
15818     CombineTo(TheSelect, Load);
15819
15820     // Users of the old loads now use the new load's chain.  We know the
15821     // old-load value is dead now.
15822     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15823     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15824     return true;
15825   }
15826
15827   return false;
15828 }
15829
15830 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15831 /// bitwise 'and'.
15832 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15833                                             SDValue N1, SDValue N2, SDValue N3,
15834                                             ISD::CondCode CC) {
15835   // If this is a select where the false operand is zero and the compare is a
15836   // check of the sign bit, see if we can perform the "gzip trick":
15837   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15838   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15839   EVT XType = N0.getValueType();
15840   EVT AType = N2.getValueType();
15841   if (!isNullConstant(N3) || !XType.bitsGE(AType))
15842     return SDValue();
15843
15844   // If the comparison is testing for a positive value, we have to invert
15845   // the sign bit mask, so only do that transform if the target has a bitwise
15846   // 'and not' instruction (the invert is free).
15847   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15848     // (X > -1) ? A : 0
15849     // (X >  0) ? X : 0 <-- This is canonical signed max.
15850     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15851       return SDValue();
15852   } else if (CC == ISD::SETLT) {
15853     // (X <  0) ? A : 0
15854     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
15855     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15856       return SDValue();
15857   } else {
15858     return SDValue();
15859   }
15860
15861   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15862   // constant.
15863   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15864   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15865   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15866     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15867     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15868     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15869     AddToWorklist(Shift.getNode());
15870
15871     if (XType.bitsGT(AType)) {
15872       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15873       AddToWorklist(Shift.getNode());
15874     }
15875
15876     if (CC == ISD::SETGT)
15877       Shift = DAG.getNOT(DL, Shift, AType);
15878
15879     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15880   }
15881
15882   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15883   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15884   AddToWorklist(Shift.getNode());
15885
15886   if (XType.bitsGT(AType)) {
15887     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15888     AddToWorklist(Shift.getNode());
15889   }
15890
15891   if (CC == ISD::SETGT)
15892     Shift = DAG.getNOT(DL, Shift, AType);
15893
15894   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15895 }
15896
15897 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15898 /// where 'cond' is the comparison specified by CC.
15899 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15900                                       SDValue N2, SDValue N3, ISD::CondCode CC,
15901                                       bool NotExtCompare) {
15902   // (x ? y : y) -> y.
15903   if (N2 == N3) return N2;
15904
15905   EVT VT = N2.getValueType();
15906   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15907   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15908
15909   // Determine if the condition we're dealing with is constant
15910   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15911                               N0, N1, CC, DL, false);
15912   if (SCC.getNode()) AddToWorklist(SCC.getNode());
15913
15914   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15915     // fold select_cc true, x, y -> x
15916     // fold select_cc false, x, y -> y
15917     return !SCCC->isNullValue() ? N2 : N3;
15918   }
15919
15920   // Check to see if we can simplify the select into an fabs node
15921   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15922     // Allow either -0.0 or 0.0
15923     if (CFP->isZero()) {
15924       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15925       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15926           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15927           N2 == N3.getOperand(0))
15928         return DAG.getNode(ISD::FABS, DL, VT, N0);
15929
15930       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15931       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15932           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15933           N2.getOperand(0) == N3)
15934         return DAG.getNode(ISD::FABS, DL, VT, N3);
15935     }
15936   }
15937
15938   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15939   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15940   // in it.  This is a win when the constant is not otherwise available because
15941   // it replaces two constant pool loads with one.  We only do this if the FP
15942   // type is known to be legal, because if it isn't, then we are before legalize
15943   // types an we want the other legalization to happen first (e.g. to avoid
15944   // messing with soft float) and if the ConstantFP is not legal, because if
15945   // it is legal, we may not need to store the FP constant in a constant pool.
15946   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15947     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15948       if (TLI.isTypeLegal(N2.getValueType()) &&
15949           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15950                TargetLowering::Legal &&
15951            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15952            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15953           // If both constants have multiple uses, then we won't need to do an
15954           // extra load, they are likely around in registers for other users.
15955           (TV->hasOneUse() || FV->hasOneUse())) {
15956         Constant *Elts[] = {
15957           const_cast<ConstantFP*>(FV->getConstantFPValue()),
15958           const_cast<ConstantFP*>(TV->getConstantFPValue())
15959         };
15960         Type *FPTy = Elts[0]->getType();
15961         const DataLayout &TD = DAG.getDataLayout();
15962
15963         // Create a ConstantArray of the two constants.
15964         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15965         SDValue CPIdx =
15966             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15967                                 TD.getPrefTypeAlignment(FPTy));
15968         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15969
15970         // Get the offsets to the 0 and 1 element of the array so that we can
15971         // select between them.
15972         SDValue Zero = DAG.getIntPtrConstant(0, DL);
15973         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15974         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15975
15976         SDValue Cond = DAG.getSetCC(DL,
15977                                     getSetCCResultType(N0.getValueType()),
15978                                     N0, N1, CC);
15979         AddToWorklist(Cond.getNode());
15980         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15981                                           Cond, One, Zero);
15982         AddToWorklist(CstOffset.getNode());
15983         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15984                             CstOffset);
15985         AddToWorklist(CPIdx.getNode());
15986         return DAG.getLoad(
15987             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15988             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15989             Alignment);
15990       }
15991     }
15992
15993   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15994     return V;
15995
15996   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15997   // where y is has a single bit set.
15998   // A plaintext description would be, we can turn the SELECT_CC into an AND
15999   // when the condition can be materialized as an all-ones register.  Any
16000   // single bit-test can be materialized as an all-ones register with
16001   // shift-left and shift-right-arith.
16002   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16003       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16004     SDValue AndLHS = N0->getOperand(0);
16005     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16006     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16007       // Shift the tested bit over the sign bit.
16008       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16009       SDValue ShlAmt =
16010         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16011                         getShiftAmountTy(AndLHS.getValueType()));
16012       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16013
16014       // Now arithmetic right shift it all the way over, so the result is either
16015       // all-ones, or zero.
16016       SDValue ShrAmt =
16017         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16018                         getShiftAmountTy(Shl.getValueType()));
16019       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16020
16021       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16022     }
16023   }
16024
16025   // fold select C, 16, 0 -> shl C, 4
16026   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16027       TLI.getBooleanContents(N0.getValueType()) ==
16028           TargetLowering::ZeroOrOneBooleanContent) {
16029
16030     // If the caller doesn't want us to simplify this into a zext of a compare,
16031     // don't do it.
16032     if (NotExtCompare && N2C->isOne())
16033       return SDValue();
16034
16035     // Get a SetCC of the condition
16036     // NOTE: Don't create a SETCC if it's not legal on this target.
16037     if (!LegalOperations ||
16038         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16039       SDValue Temp, SCC;
16040       // cast from setcc result type to select result type
16041       if (LegalTypes) {
16042         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16043                             N0, N1, CC);
16044         if (N2.getValueType().bitsLT(SCC.getValueType()))
16045           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16046                                         N2.getValueType());
16047         else
16048           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16049                              N2.getValueType(), SCC);
16050       } else {
16051         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16052         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16053                            N2.getValueType(), SCC);
16054       }
16055
16056       AddToWorklist(SCC.getNode());
16057       AddToWorklist(Temp.getNode());
16058
16059       if (N2C->isOne())
16060         return Temp;
16061
16062       // shl setcc result by log2 n2c
16063       return DAG.getNode(
16064           ISD::SHL, DL, N2.getValueType(), Temp,
16065           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16066                           getShiftAmountTy(Temp.getValueType())));
16067     }
16068   }
16069
16070   // Check to see if this is an integer abs.
16071   // select_cc setg[te] X,  0,  X, -X ->
16072   // select_cc setgt    X, -1,  X, -X ->
16073   // select_cc setl[te] X,  0, -X,  X ->
16074   // select_cc setlt    X,  1, -X,  X ->
16075   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16076   if (N1C) {
16077     ConstantSDNode *SubC = nullptr;
16078     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16079          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16080         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16081       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16082     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16083               (N1C->isOne() && CC == ISD::SETLT)) &&
16084              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16085       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16086
16087     EVT XType = N0.getValueType();
16088     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16089       SDLoc DL(N0);
16090       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16091                                   N0,
16092                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16093                                          getShiftAmountTy(N0.getValueType())));
16094       SDValue Add = DAG.getNode(ISD::ADD, DL,
16095                                 XType, N0, Shift);
16096       AddToWorklist(Shift.getNode());
16097       AddToWorklist(Add.getNode());
16098       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16099     }
16100   }
16101
16102   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16103   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16104   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16105   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16106   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16107   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16108   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16109   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16110   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16111     SDValue ValueOnZero = N2;
16112     SDValue Count = N3;
16113     // If the condition is NE instead of E, swap the operands.
16114     if (CC == ISD::SETNE)
16115       std::swap(ValueOnZero, Count);
16116     // Check if the value on zero is a constant equal to the bits in the type.
16117     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16118       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16119         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16120         // legal, combine to just cttz.
16121         if ((Count.getOpcode() == ISD::CTTZ ||
16122              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16123             N0 == Count.getOperand(0) &&
16124             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16125           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16126         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16127         // legal, combine to just ctlz.
16128         if ((Count.getOpcode() == ISD::CTLZ ||
16129              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16130             N0 == Count.getOperand(0) &&
16131             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16132           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16133       }
16134     }
16135   }
16136
16137   return SDValue();
16138 }
16139
16140 /// This is a stub for TargetLowering::SimplifySetCC.
16141 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16142                                    ISD::CondCode Cond, const SDLoc &DL,
16143                                    bool foldBooleans) {
16144   TargetLowering::DAGCombinerInfo
16145     DagCombineInfo(DAG, Level, false, this);
16146   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16147 }
16148
16149 /// Given an ISD::SDIV node expressing a divide by constant, return
16150 /// a DAG expression to select that will generate the same value by multiplying
16151 /// by a magic number.
16152 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16153 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16154   // when optimising for minimum size, we don't want to expand a div to a mul
16155   // and a shift.
16156   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16157     return SDValue();
16158
16159   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16160   if (!C)
16161     return SDValue();
16162
16163   // Avoid division by zero.
16164   if (C->isNullValue())
16165     return SDValue();
16166
16167   std::vector<SDNode*> Built;
16168   SDValue S =
16169       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16170
16171   for (SDNode *N : Built)
16172     AddToWorklist(N);
16173   return S;
16174 }
16175
16176 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16177 /// DAG expression that will generate the same value by right shifting.
16178 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16179   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16180   if (!C)
16181     return SDValue();
16182
16183   // Avoid division by zero.
16184   if (C->isNullValue())
16185     return SDValue();
16186
16187   std::vector<SDNode *> Built;
16188   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16189
16190   for (SDNode *N : Built)
16191     AddToWorklist(N);
16192   return S;
16193 }
16194
16195 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16196 /// expression that will generate the same value by multiplying by a magic
16197 /// number.
16198 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16199 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16200   // when optimising for minimum size, we don't want to expand a div to a mul
16201   // and a shift.
16202   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16203     return SDValue();
16204
16205   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16206   if (!C)
16207     return SDValue();
16208
16209   // Avoid division by zero.
16210   if (C->isNullValue())
16211     return SDValue();
16212
16213   std::vector<SDNode*> Built;
16214   SDValue S =
16215       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16216
16217   for (SDNode *N : Built)
16218     AddToWorklist(N);
16219   return S;
16220 }
16221
16222 /// Determines the LogBase2 value for a non-null input value using the
16223 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16224 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16225   EVT VT = V.getValueType();
16226   unsigned EltBits = VT.getScalarSizeInBits();
16227   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16228   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16229   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16230   return LogBase2;
16231 }
16232
16233 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16234 /// For the reciprocal, we need to find the zero of the function:
16235 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16236 ///     =>
16237 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16238 ///     does not require additional intermediate precision]
16239 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16240   if (Level >= AfterLegalizeDAG)
16241     return SDValue();
16242
16243   // TODO: Handle half and/or extended types?
16244   EVT VT = Op.getValueType();
16245   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16246     return SDValue();
16247
16248   // If estimates are explicitly disabled for this function, we're done.
16249   MachineFunction &MF = DAG.getMachineFunction();
16250   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16251   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16252     return SDValue();
16253
16254   // Estimates may be explicitly enabled for this type with a custom number of
16255   // refinement steps.
16256   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16257   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16258     AddToWorklist(Est.getNode());
16259
16260     if (Iterations) {
16261       EVT VT = Op.getValueType();
16262       SDLoc DL(Op);
16263       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16264
16265       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16266       for (int i = 0; i < Iterations; ++i) {
16267         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16268         AddToWorklist(NewEst.getNode());
16269
16270         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16271         AddToWorklist(NewEst.getNode());
16272
16273         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16274         AddToWorklist(NewEst.getNode());
16275
16276         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16277         AddToWorklist(Est.getNode());
16278       }
16279     }
16280     return Est;
16281   }
16282
16283   return SDValue();
16284 }
16285
16286 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16287 /// For the reciprocal sqrt, we need to find the zero of the function:
16288 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16289 ///     =>
16290 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16291 /// As a result, we precompute A/2 prior to the iteration loop.
16292 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16293                                          unsigned Iterations,
16294                                          SDNodeFlags Flags, bool Reciprocal) {
16295   EVT VT = Arg.getValueType();
16296   SDLoc DL(Arg);
16297   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16298
16299   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16300   // this entire sequence requires only one FP constant.
16301   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16302   AddToWorklist(HalfArg.getNode());
16303
16304   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16305   AddToWorklist(HalfArg.getNode());
16306
16307   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16308   for (unsigned i = 0; i < Iterations; ++i) {
16309     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16310     AddToWorklist(NewEst.getNode());
16311
16312     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16313     AddToWorklist(NewEst.getNode());
16314
16315     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16316     AddToWorklist(NewEst.getNode());
16317
16318     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16319     AddToWorklist(Est.getNode());
16320   }
16321
16322   // If non-reciprocal square root is requested, multiply the result by Arg.
16323   if (!Reciprocal) {
16324     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16325     AddToWorklist(Est.getNode());
16326   }
16327
16328   return Est;
16329 }
16330
16331 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16332 /// For the reciprocal sqrt, we need to find the zero of the function:
16333 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16334 ///     =>
16335 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16336 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16337                                          unsigned Iterations,
16338                                          SDNodeFlags Flags, bool Reciprocal) {
16339   EVT VT = Arg.getValueType();
16340   SDLoc DL(Arg);
16341   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16342   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16343
16344   // This routine must enter the loop below to work correctly
16345   // when (Reciprocal == false).
16346   assert(Iterations > 0);
16347
16348   // Newton iterations for reciprocal square root:
16349   // E = (E * -0.5) * ((A * E) * E + -3.0)
16350   for (unsigned i = 0; i < Iterations; ++i) {
16351     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16352     AddToWorklist(AE.getNode());
16353
16354     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16355     AddToWorklist(AEE.getNode());
16356
16357     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16358     AddToWorklist(RHS.getNode());
16359
16360     // When calculating a square root at the last iteration build:
16361     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16362     // (notice a common subexpression)
16363     SDValue LHS;
16364     if (Reciprocal || (i + 1) < Iterations) {
16365       // RSQRT: LHS = (E * -0.5)
16366       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16367     } else {
16368       // SQRT: LHS = (A * E) * -0.5
16369       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16370     }
16371     AddToWorklist(LHS.getNode());
16372
16373     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16374     AddToWorklist(Est.getNode());
16375   }
16376
16377   return Est;
16378 }
16379
16380 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16381 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16382 /// Op can be zero.
16383 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16384                                            bool Reciprocal) {
16385   if (Level >= AfterLegalizeDAG)
16386     return SDValue();
16387
16388   // TODO: Handle half and/or extended types?
16389   EVT VT = Op.getValueType();
16390   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16391     return SDValue();
16392
16393   // If estimates are explicitly disabled for this function, we're done.
16394   MachineFunction &MF = DAG.getMachineFunction();
16395   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16396   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16397     return SDValue();
16398
16399   // Estimates may be explicitly enabled for this type with a custom number of
16400   // refinement steps.
16401   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16402
16403   bool UseOneConstNR = false;
16404   if (SDValue Est =
16405       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16406                           Reciprocal)) {
16407     AddToWorklist(Est.getNode());
16408
16409     if (Iterations) {
16410       Est = UseOneConstNR
16411             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16412             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16413
16414       if (!Reciprocal) {
16415         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16416         // Select out this case and force the answer to 0.0.
16417         EVT VT = Op.getValueType();
16418         SDLoc DL(Op);
16419
16420         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16421         EVT CCVT = getSetCCResultType(VT);
16422         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16423         AddToWorklist(ZeroCmp.getNode());
16424
16425         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16426                           ZeroCmp, FPZero, Est);
16427         AddToWorklist(Est.getNode());
16428       }
16429     }
16430     return Est;
16431   }
16432
16433   return SDValue();
16434 }
16435
16436 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16437   return buildSqrtEstimateImpl(Op, Flags, true);
16438 }
16439
16440 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16441   return buildSqrtEstimateImpl(Op, Flags, false);
16442 }
16443
16444 /// Return true if base is a frame index, which is known not to alias with
16445 /// anything but itself.  Provides base object and offset as results.
16446 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16447                            const GlobalValue *&GV, const void *&CV) {
16448   // Assume it is a primitive operation.
16449   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16450
16451   // If it's an adding a simple constant then integrate the offset.
16452   if (Base.getOpcode() == ISD::ADD) {
16453     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16454       Base = Base.getOperand(0);
16455       Offset += C->getSExtValue();
16456     }
16457   }
16458
16459   // Return the underlying GlobalValue, and update the Offset.  Return false
16460   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16461   // by multiple nodes with different offsets.
16462   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16463     GV = G->getGlobal();
16464     Offset += G->getOffset();
16465     return false;
16466   }
16467
16468   // Return the underlying Constant value, and update the Offset.  Return false
16469   // for ConstantSDNodes since the same constant pool entry may be represented
16470   // by multiple nodes with different offsets.
16471   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16472     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16473                                          : (const void *)C->getConstVal();
16474     Offset += C->getOffset();
16475     return false;
16476   }
16477   // If it's any of the following then it can't alias with anything but itself.
16478   return isa<FrameIndexSDNode>(Base);
16479 }
16480
16481 /// Return true if there is any possibility that the two addresses overlap.
16482 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16483   // If they are the same then they must be aliases.
16484   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16485
16486   // If they are both volatile then they cannot be reordered.
16487   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16488
16489   // If one operation reads from invariant memory, and the other may store, they
16490   // cannot alias. These should really be checking the equivalent of mayWrite,
16491   // but it only matters for memory nodes other than load /store.
16492   if (Op0->isInvariant() && Op1->writeMem())
16493     return false;
16494
16495   if (Op1->isInvariant() && Op0->writeMem())
16496     return false;
16497
16498   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16499   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16500
16501   // Check for BaseIndexOffset matching.
16502   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16503   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16504   if (BasePtr0.equalBaseIndex(BasePtr1))
16505     return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) ||
16506              (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset));
16507
16508   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16509   // modified to use BaseIndexOffset.
16510
16511   // Gather base node and offset information.
16512   SDValue Base0, Base1;
16513   int64_t Offset0, Offset1;
16514   const GlobalValue *GV0, *GV1;
16515   const void *CV0, *CV1;
16516   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16517                                       Base0, Offset0, GV0, CV0);
16518   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16519                                       Base1, Offset1, GV1, CV1);
16520
16521   // If they have the same base address, then check to see if they overlap.
16522   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16523     return !((Offset0 + NumBytes0) <= Offset1 ||
16524              (Offset1 + NumBytes1) <= Offset0);
16525
16526   // It is possible for different frame indices to alias each other, mostly
16527   // when tail call optimization reuses return address slots for arguments.
16528   // To catch this case, look up the actual index of frame indices to compute
16529   // the real alias relationship.
16530   if (IsFrameIndex0 && IsFrameIndex1) {
16531     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16532     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16533     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16534     return !((Offset0 + NumBytes0) <= Offset1 ||
16535              (Offset1 + NumBytes1) <= Offset0);
16536   }
16537
16538   // Otherwise, if we know what the bases are, and they aren't identical, then
16539   // we know they cannot alias.
16540   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16541     return false;
16542
16543   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16544   // compared to the size and offset of the access, we may be able to prove they
16545   // do not alias. This check is conservative for now to catch cases created by
16546   // splitting vector types.
16547   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16548   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16549   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16550   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16551   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16552       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16553     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16554     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16555
16556     // There is no overlap between these relatively aligned accesses of similar
16557     // size. Return no alias.
16558     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16559         (OffAlign1 + NumBytes1) <= OffAlign0)
16560       return false;
16561   }
16562
16563   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16564                    ? CombinerGlobalAA
16565                    : DAG.getSubtarget().useAA();
16566 #ifndef NDEBUG
16567   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16568       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16569     UseAA = false;
16570 #endif
16571
16572   if (UseAA && AA &&
16573       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16574     // Use alias analysis information.
16575     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16576     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16577     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16578     AliasResult AAResult =
16579         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16580                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16581                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16582                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16583     if (AAResult == NoAlias)
16584       return false;
16585   }
16586
16587   // Otherwise we have to assume they alias.
16588   return true;
16589 }
16590
16591 /// Walk up chain skipping non-aliasing memory nodes,
16592 /// looking for aliasing nodes and adding them to the Aliases vector.
16593 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16594                                    SmallVectorImpl<SDValue> &Aliases) {
16595   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16596   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16597
16598   // Get alias information for node.
16599   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16600
16601   // Starting off.
16602   Chains.push_back(OriginalChain);
16603   unsigned Depth = 0;
16604
16605   // Look at each chain and determine if it is an alias.  If so, add it to the
16606   // aliases list.  If not, then continue up the chain looking for the next
16607   // candidate.
16608   while (!Chains.empty()) {
16609     SDValue Chain = Chains.pop_back_val();
16610
16611     // For TokenFactor nodes, look at each operand and only continue up the
16612     // chain until we reach the depth limit.
16613     //
16614     // FIXME: The depth check could be made to return the last non-aliasing
16615     // chain we found before we hit a tokenfactor rather than the original
16616     // chain.
16617     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16618       Aliases.clear();
16619       Aliases.push_back(OriginalChain);
16620       return;
16621     }
16622
16623     // Don't bother if we've been before.
16624     if (!Visited.insert(Chain.getNode()).second)
16625       continue;
16626
16627     switch (Chain.getOpcode()) {
16628     case ISD::EntryToken:
16629       // Entry token is ideal chain operand, but handled in FindBetterChain.
16630       break;
16631
16632     case ISD::LOAD:
16633     case ISD::STORE: {
16634       // Get alias information for Chain.
16635       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16636           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16637
16638       // If chain is alias then stop here.
16639       if (!(IsLoad && IsOpLoad) &&
16640           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16641         Aliases.push_back(Chain);
16642       } else {
16643         // Look further up the chain.
16644         Chains.push_back(Chain.getOperand(0));
16645         ++Depth;
16646       }
16647       break;
16648     }
16649
16650     case ISD::TokenFactor:
16651       // We have to check each of the operands of the token factor for "small"
16652       // token factors, so we queue them up.  Adding the operands to the queue
16653       // (stack) in reverse order maintains the original order and increases the
16654       // likelihood that getNode will find a matching token factor (CSE.)
16655       if (Chain.getNumOperands() > 16) {
16656         Aliases.push_back(Chain);
16657         break;
16658       }
16659       for (unsigned n = Chain.getNumOperands(); n;)
16660         Chains.push_back(Chain.getOperand(--n));
16661       ++Depth;
16662       break;
16663
16664     case ISD::CopyFromReg:
16665       // Forward past CopyFromReg.
16666       Chains.push_back(Chain.getOperand(0));
16667       ++Depth;
16668       break;
16669
16670     default:
16671       // For all other instructions we will just have to take what we can get.
16672       Aliases.push_back(Chain);
16673       break;
16674     }
16675   }
16676 }
16677
16678 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16679 /// (aliasing node.)
16680 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16681   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16682
16683   // Accumulate all the aliases to this node.
16684   GatherAllAliases(N, OldChain, Aliases);
16685
16686   // If no operands then chain to entry token.
16687   if (Aliases.size() == 0)
16688     return DAG.getEntryNode();
16689
16690   // If a single operand then chain to it.  We don't need to revisit it.
16691   if (Aliases.size() == 1)
16692     return Aliases[0];
16693
16694   // Construct a custom tailored token factor.
16695   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16696 }
16697
16698 // This function tries to collect a bunch of potentially interesting
16699 // nodes to improve the chains of, all at once. This might seem
16700 // redundant, as this function gets called when visiting every store
16701 // node, so why not let the work be done on each store as it's visited?
16702 //
16703 // I believe this is mainly important because MergeConsecutiveStores
16704 // is unable to deal with merging stores of different sizes, so unless
16705 // we improve the chains of all the potential candidates up-front
16706 // before running MergeConsecutiveStores, it might only see some of
16707 // the nodes that will eventually be candidates, and then not be able
16708 // to go from a partially-merged state to the desired final
16709 // fully-merged state.
16710 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16711   // This holds the base pointer, index, and the offset in bytes from the base
16712   // pointer.
16713   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16714
16715   // We must have a base and an offset.
16716   if (!BasePtr.Base.getNode())
16717     return false;
16718
16719   // Do not handle stores to undef base pointers.
16720   if (BasePtr.Base.isUndef())
16721     return false;
16722
16723   SmallVector<StoreSDNode *, 8> ChainedStores;
16724   ChainedStores.push_back(St);
16725
16726   // Walk up the chain and look for nodes with offsets from the same
16727   // base pointer. Stop when reaching an instruction with a different kind
16728   // or instruction which has a different base pointer.
16729   StoreSDNode *Index = St;
16730   while (Index) {
16731     // If the chain has more than one use, then we can't reorder the mem ops.
16732     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16733       break;
16734
16735     if (Index->isVolatile() || Index->isIndexed())
16736       break;
16737
16738     // Find the base pointer and offset for this memory node.
16739     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16740
16741     // Check that the base pointer is the same as the original one.
16742     if (!Ptr.equalBaseIndex(BasePtr))
16743       break;
16744
16745     // Walk up the chain to find the next store node, ignoring any
16746     // intermediate loads. Any other kind of node will halt the loop.
16747     SDNode *NextInChain = Index->getChain().getNode();
16748     while (true) {
16749       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16750         // We found a store node. Use it for the next iteration.
16751         if (STn->isVolatile() || STn->isIndexed()) {
16752           Index = nullptr;
16753           break;
16754         }
16755         ChainedStores.push_back(STn);
16756         Index = STn;
16757         break;
16758       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16759         NextInChain = Ldn->getChain().getNode();
16760         continue;
16761       } else {
16762         Index = nullptr;
16763         break;
16764       }
16765     } // end while
16766   }
16767
16768   // At this point, ChainedStores lists all of the Store nodes
16769   // reachable by iterating up through chain nodes matching the above
16770   // conditions.  For each such store identified, try to find an
16771   // earlier chain to attach the store to which won't violate the
16772   // required ordering.
16773   bool MadeChangeToSt = false;
16774   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16775
16776   for (StoreSDNode *ChainedStore : ChainedStores) {
16777     SDValue Chain = ChainedStore->getChain();
16778     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16779
16780     if (Chain != BetterChain) {
16781       if (ChainedStore == St)
16782         MadeChangeToSt = true;
16783       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16784     }
16785   }
16786
16787   // Do all replacements after finding the replacements to make to avoid making
16788   // the chains more complicated by introducing new TokenFactors.
16789   for (auto Replacement : BetterChains)
16790     replaceStoreChain(Replacement.first, Replacement.second);
16791
16792   return MadeChangeToSt;
16793 }
16794
16795 /// This is the entry point for the file.
16796 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
16797                            CodeGenOpt::Level OptLevel) {
16798   /// This is the main entry point to this class.
16799   DAGCombiner(*this, AA, OptLevel).Run(Level);
16800 }