]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge compiler-rt trunk r321017 to contrib/compiler-rt.
[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/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryLocation.h"
34 #include "llvm/CodeGen/DAGCombine.h"
35 #include "llvm/CodeGen/ISDOpcodes.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineValueType.h"
40 #include "llvm/CodeGen/RuntimeLibcalls.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
45 #include "llvm/CodeGen/TargetLowering.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/CodeGen/ValueTypes.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/Constant.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Target/TargetOptions.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <functional>
71 #include <iterator>
72 #include <string>
73 #include <tuple>
74 #include <utility>
75 #include <vector>
76
77 using namespace llvm;
78
79 #define DEBUG_TYPE "dagcombine"
80
81 STATISTIC(NodesCombined   , "Number of dag nodes combined");
82 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
83 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
84 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
85 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
86 STATISTIC(SlicedLoads, "Number of load sliced");
87
88 static cl::opt<bool>
89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
90                  cl::desc("Enable DAG combiner's use of IR alias analysis"));
91
92 static cl::opt<bool>
93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
94         cl::desc("Enable DAG combiner's use of TBAA"));
95
96 #ifndef NDEBUG
97 static cl::opt<std::string>
98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
99                    cl::desc("Only use DAG-combiner alias analysis in this"
100                             " function"));
101 #endif
102
103 /// Hidden option to stress test load slicing, i.e., when this option
104 /// is enabled, load slicing bypasses most of its profitability guards.
105 static cl::opt<bool>
106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
107                   cl::desc("Bypass the profitability model of load slicing"),
108                   cl::init(false));
109
110 static cl::opt<bool>
111   MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
112                     cl::desc("DAG combiner may split indexing from loads"));
113
114 namespace {
115
116   class DAGCombiner {
117     SelectionDAG &DAG;
118     const TargetLowering &TLI;
119     CombineLevel Level;
120     CodeGenOpt::Level OptLevel;
121     bool LegalOperations = false;
122     bool LegalTypes = false;
123     bool ForCodeSize;
124
125     /// \brief Worklist of all of the nodes that need to be simplified.
126     ///
127     /// This must behave as a stack -- new nodes to process are pushed onto the
128     /// back and when processing we pop off of the back.
129     ///
130     /// The worklist will not contain duplicates but may contain null entries
131     /// due to nodes being deleted from the underlying DAG.
132     SmallVector<SDNode *, 64> Worklist;
133
134     /// \brief Mapping from an SDNode to its position on the worklist.
135     ///
136     /// This is used to find and remove nodes from the worklist (by nulling
137     /// them) when they are deleted from the underlying DAG. It relies on
138     /// stable indices of nodes within the worklist.
139     DenseMap<SDNode *, unsigned> WorklistMap;
140
141     /// \brief Set of nodes which have been combined (at least once).
142     ///
143     /// This is used to allow us to reliably add any operands of a DAG node
144     /// which have not yet been combined to the worklist.
145     SmallPtrSet<SDNode *, 32> CombinedNodes;
146
147     // AA - Used for DAG load/store alias analysis.
148     AliasAnalysis *AA;
149
150     /// When an instruction is simplified, add all users of the instruction to
151     /// the work lists because they might get more simplified now.
152     void AddUsersToWorklist(SDNode *N) {
153       for (SDNode *Node : N->uses())
154         AddToWorklist(Node);
155     }
156
157     /// Call the node-specific routine that folds each particular type of node.
158     SDValue visit(SDNode *N);
159
160   public:
161     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
162         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
163           OptLevel(OL), AA(AA) {
164       ForCodeSize = DAG.getMachineFunction().getFunction().optForSize();
165
166       MaximumLegalStoreInBits = 0;
167       for (MVT VT : MVT::all_valuetypes())
168         if (EVT(VT).isSimple() && VT != MVT::Other &&
169             TLI.isTypeLegal(EVT(VT)) &&
170             VT.getSizeInBits() >= MaximumLegalStoreInBits)
171           MaximumLegalStoreInBits = VT.getSizeInBits();
172     }
173
174     /// Add to the worklist making sure its instance is at the back (next to be
175     /// processed.)
176     void AddToWorklist(SDNode *N) {
177       assert(N->getOpcode() != ISD::DELETED_NODE &&
178              "Deleted Node added to Worklist");
179
180       // Skip handle nodes as they can't usefully be combined and confuse the
181       // zero-use deletion strategy.
182       if (N->getOpcode() == ISD::HANDLENODE)
183         return;
184
185       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
186         Worklist.push_back(N);
187     }
188
189     /// Remove all instances of N from the worklist.
190     void removeFromWorklist(SDNode *N) {
191       CombinedNodes.erase(N);
192
193       auto It = WorklistMap.find(N);
194       if (It == WorklistMap.end())
195         return; // Not in the worklist.
196
197       // Null out the entry rather than erasing it to avoid a linear operation.
198       Worklist[It->second] = nullptr;
199       WorklistMap.erase(It);
200     }
201
202     void deleteAndRecombine(SDNode *N);
203     bool recursivelyDeleteUnusedNodes(SDNode *N);
204
205     /// Replaces all uses of the results of one DAG node with new values.
206     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
207                       bool AddTo = true);
208
209     /// Replaces all uses of the results of one DAG node with new values.
210     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
211       return CombineTo(N, &Res, 1, AddTo);
212     }
213
214     /// Replaces all uses of the results of one DAG node with new values.
215     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
216                       bool AddTo = true) {
217       SDValue To[] = { Res0, Res1 };
218       return CombineTo(N, To, 2, AddTo);
219     }
220
221     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
222
223   private:
224     unsigned MaximumLegalStoreInBits;
225
226     /// Check the specified integer node value to see if it can be simplified or
227     /// if things it uses can be simplified by bit propagation.
228     /// If so, return true.
229     bool SimplifyDemandedBits(SDValue Op) {
230       unsigned BitWidth = Op.getScalarValueSizeInBits();
231       APInt Demanded = APInt::getAllOnesValue(BitWidth);
232       return SimplifyDemandedBits(Op, Demanded);
233     }
234
235     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
236
237     bool CombineToPreIndexedLoadStore(SDNode *N);
238     bool CombineToPostIndexedLoadStore(SDNode *N);
239     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
240     bool SliceUpLoad(SDNode *N);
241
242     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
243     ///   load.
244     ///
245     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
246     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
247     /// \param EltNo index of the vector element to load.
248     /// \param OriginalLoad load that EVE came from to be replaced.
249     /// \returns EVE on success SDValue() on failure.
250     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
251         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
252     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
253     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
254     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
255     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
256     SDValue PromoteIntBinOp(SDValue Op);
257     SDValue PromoteIntShiftOp(SDValue Op);
258     SDValue PromoteExtend(SDValue Op);
259     bool PromoteLoad(SDValue Op);
260
261     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
262                          SDValue ExtLoad, const SDLoc &DL,
263                          ISD::NodeType ExtType);
264
265     /// Call the node-specific routine that knows how to fold each
266     /// particular type of node. If that doesn't do anything, try the
267     /// target-specific DAG combines.
268     SDValue combine(SDNode *N);
269
270     // Visitation implementation - Implement dag node combining for different
271     // node types.  The semantics are as follows:
272     // Return Value:
273     //   SDValue.getNode() == 0 - No change was made
274     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
275     //   otherwise              - N should be replaced by the returned Operand.
276     //
277     SDValue visitTokenFactor(SDNode *N);
278     SDValue visitMERGE_VALUES(SDNode *N);
279     SDValue visitADD(SDNode *N);
280     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
281     SDValue visitSUB(SDNode *N);
282     SDValue visitADDC(SDNode *N);
283     SDValue visitUADDO(SDNode *N);
284     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
285     SDValue visitSUBC(SDNode *N);
286     SDValue visitUSUBO(SDNode *N);
287     SDValue visitADDE(SDNode *N);
288     SDValue visitADDCARRY(SDNode *N);
289     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
290     SDValue visitSUBE(SDNode *N);
291     SDValue visitSUBCARRY(SDNode *N);
292     SDValue visitMUL(SDNode *N);
293     SDValue useDivRem(SDNode *N);
294     SDValue visitSDIV(SDNode *N);
295     SDValue visitUDIV(SDNode *N);
296     SDValue visitREM(SDNode *N);
297     SDValue visitMULHU(SDNode *N);
298     SDValue visitMULHS(SDNode *N);
299     SDValue visitSMUL_LOHI(SDNode *N);
300     SDValue visitUMUL_LOHI(SDNode *N);
301     SDValue visitSMULO(SDNode *N);
302     SDValue visitUMULO(SDNode *N);
303     SDValue visitIMINMAX(SDNode *N);
304     SDValue visitAND(SDNode *N);
305     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
306     SDValue visitOR(SDNode *N);
307     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
308     SDValue visitXOR(SDNode *N);
309     SDValue SimplifyVBinOp(SDNode *N);
310     SDValue visitSHL(SDNode *N);
311     SDValue visitSRA(SDNode *N);
312     SDValue visitSRL(SDNode *N);
313     SDValue visitRotate(SDNode *N);
314     SDValue visitABS(SDNode *N);
315     SDValue visitBSWAP(SDNode *N);
316     SDValue visitBITREVERSE(SDNode *N);
317     SDValue visitCTLZ(SDNode *N);
318     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
319     SDValue visitCTTZ(SDNode *N);
320     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
321     SDValue visitCTPOP(SDNode *N);
322     SDValue visitSELECT(SDNode *N);
323     SDValue visitVSELECT(SDNode *N);
324     SDValue visitSELECT_CC(SDNode *N);
325     SDValue visitSETCC(SDNode *N);
326     SDValue visitSETCCE(SDNode *N);
327     SDValue visitSETCCCARRY(SDNode *N);
328     SDValue visitSIGN_EXTEND(SDNode *N);
329     SDValue visitZERO_EXTEND(SDNode *N);
330     SDValue visitANY_EXTEND(SDNode *N);
331     SDValue visitAssertExt(SDNode *N);
332     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
333     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
334     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
335     SDValue visitTRUNCATE(SDNode *N);
336     SDValue visitBITCAST(SDNode *N);
337     SDValue visitBUILD_PAIR(SDNode *N);
338     SDValue visitFADD(SDNode *N);
339     SDValue visitFSUB(SDNode *N);
340     SDValue visitFMUL(SDNode *N);
341     SDValue visitFMA(SDNode *N);
342     SDValue visitFDIV(SDNode *N);
343     SDValue visitFREM(SDNode *N);
344     SDValue visitFSQRT(SDNode *N);
345     SDValue visitFCOPYSIGN(SDNode *N);
346     SDValue visitSINT_TO_FP(SDNode *N);
347     SDValue visitUINT_TO_FP(SDNode *N);
348     SDValue visitFP_TO_SINT(SDNode *N);
349     SDValue visitFP_TO_UINT(SDNode *N);
350     SDValue visitFP_ROUND(SDNode *N);
351     SDValue visitFP_ROUND_INREG(SDNode *N);
352     SDValue visitFP_EXTEND(SDNode *N);
353     SDValue visitFNEG(SDNode *N);
354     SDValue visitFABS(SDNode *N);
355     SDValue visitFCEIL(SDNode *N);
356     SDValue visitFTRUNC(SDNode *N);
357     SDValue visitFFLOOR(SDNode *N);
358     SDValue visitFMINNUM(SDNode *N);
359     SDValue visitFMAXNUM(SDNode *N);
360     SDValue visitBRCOND(SDNode *N);
361     SDValue visitBR_CC(SDNode *N);
362     SDValue visitLOAD(SDNode *N);
363
364     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
365     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
366
367     SDValue visitSTORE(SDNode *N);
368     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
369     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
370     SDValue visitBUILD_VECTOR(SDNode *N);
371     SDValue visitCONCAT_VECTORS(SDNode *N);
372     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
373     SDValue visitVECTOR_SHUFFLE(SDNode *N);
374     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
375     SDValue visitINSERT_SUBVECTOR(SDNode *N);
376     SDValue visitMLOAD(SDNode *N);
377     SDValue visitMSTORE(SDNode *N);
378     SDValue visitMGATHER(SDNode *N);
379     SDValue visitMSCATTER(SDNode *N);
380     SDValue visitFP_TO_FP16(SDNode *N);
381     SDValue visitFP16_TO_FP(SDNode *N);
382
383     SDValue visitFADDForFMACombine(SDNode *N);
384     SDValue visitFSUBForFMACombine(SDNode *N);
385     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
386
387     SDValue XformToShuffleWithZero(SDNode *N);
388     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
389                            SDValue RHS);
390
391     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
392
393     SDValue foldSelectOfConstants(SDNode *N);
394     SDValue foldVSelectOfConstants(SDNode *N);
395     SDValue foldBinOpIntoSelect(SDNode *BO);
396     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
397     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
398     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
399     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
400                              SDValue N2, SDValue N3, ISD::CondCode CC,
401                              bool NotExtCompare = false);
402     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
403                                    SDValue N2, SDValue N3, ISD::CondCode CC);
404     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
405                               const SDLoc &DL);
406     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
407                           const SDLoc &DL, bool foldBooleans = true);
408
409     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
410                            SDValue &CC) const;
411     bool isOneUseSetCC(SDValue N) const;
412
413     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
414                                          unsigned HiOp);
415     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
416     SDValue CombineExtLoad(SDNode *N);
417     SDValue combineRepeatedFPDivisors(SDNode *N);
418     SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
419     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
420     SDValue BuildSDIV(SDNode *N);
421     SDValue BuildSDIVPow2(SDNode *N);
422     SDValue BuildUDIV(SDNode *N);
423     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
424     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
425     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
426     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
427     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
428     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
429                                 SDNodeFlags Flags, bool Reciprocal);
430     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
431                                 SDNodeFlags Flags, bool Reciprocal);
432     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
433                                bool DemandHighBits = true);
434     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
435     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
436                               SDValue InnerPos, SDValue InnerNeg,
437                               unsigned PosOpcode, unsigned NegOpcode,
438                               const SDLoc &DL);
439     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
440     SDValue MatchLoadCombine(SDNode *N);
441     SDValue ReduceLoadWidth(SDNode *N);
442     SDValue ReduceLoadOpStoreWidth(SDNode *N);
443     SDValue splitMergedValStore(StoreSDNode *ST);
444     SDValue TransformFPLoadStorePair(SDNode *N);
445     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
446     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
447     SDValue reduceBuildVecToShuffle(SDNode *N);
448     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
449                                   ArrayRef<int> VectorMask, SDValue VecIn1,
450                                   SDValue VecIn2, unsigned LeftIdx);
451     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
452
453     /// Walk up chain skipping non-aliasing memory nodes,
454     /// looking for aliasing nodes and adding them to the Aliases vector.
455     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
456                           SmallVectorImpl<SDValue> &Aliases);
457
458     /// Return true if there is any possibility that the two addresses overlap.
459     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
460
461     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
462     /// chain (aliasing node.)
463     SDValue FindBetterChain(SDNode *N, SDValue Chain);
464
465     /// Try to replace a store and any possibly adjacent stores on
466     /// consecutive chains with better chains. Return true only if St is
467     /// replaced.
468     ///
469     /// Notice that other chains may still be replaced even if the function
470     /// returns false.
471     bool findBetterNeighborChains(StoreSDNode *St);
472
473     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
474     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
475
476     /// Holds a pointer to an LSBaseSDNode as well as information on where it
477     /// is located in a sequence of memory operations connected by a chain.
478     struct MemOpLink {
479       // Ptr to the mem node.
480       LSBaseSDNode *MemNode;
481
482       // Offset from the base ptr.
483       int64_t OffsetFromBase;
484
485       MemOpLink(LSBaseSDNode *N, int64_t Offset)
486           : MemNode(N), OffsetFromBase(Offset) {}
487     };
488
489     /// This is a helper function for visitMUL to check the profitability
490     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
491     /// MulNode is the original multiply, AddNode is (add x, c1),
492     /// and ConstNode is c2.
493     bool isMulAddWithConstProfitable(SDNode *MulNode,
494                                      SDValue &AddNode,
495                                      SDValue &ConstNode);
496
497     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
498     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
499     /// the type of the loaded value to be extended.
500     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
501                           EVT LoadResultTy, EVT &ExtVT);
502
503     /// Helper function to calculate whether the given Load can have its
504     /// width reduced to ExtVT.
505     bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
506                            EVT &ExtVT, unsigned ShAmt = 0);
507
508     /// Used by BackwardsPropagateMask to find suitable loads.
509     bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
510                            SmallPtrSetImpl<SDNode*> &NodeWithConsts,
511                            ConstantSDNode *Mask, SDNode *&UncombinedNode);
512     /// Attempt to propagate a given AND node back to load leaves so that they
513     /// can be combined into narrow loads.
514     bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
515
516     /// Helper function for MergeConsecutiveStores which merges the
517     /// component store chains.
518     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
519                                 unsigned NumStores);
520
521     /// This is a helper function for MergeConsecutiveStores. When the
522     /// source elements of the consecutive stores are all constants or
523     /// all extracted vector elements, try to merge them into one
524     /// larger store introducing bitcasts if necessary.  \return True
525     /// if a merged store was created.
526     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
527                                          EVT MemVT, unsigned NumStores,
528                                          bool IsConstantSrc, bool UseVector,
529                                          bool UseTrunc);
530
531     /// This is a helper function for MergeConsecutiveStores. Stores
532     /// that potentially may be merged with St are placed in
533     /// StoreNodes.
534     void getStoreMergeCandidates(StoreSDNode *St,
535                                  SmallVectorImpl<MemOpLink> &StoreNodes);
536
537     /// Helper function for MergeConsecutiveStores. Checks if
538     /// candidate stores have indirect dependency through their
539     /// operands. \return True if safe to merge.
540     bool checkMergeStoreCandidatesForDependencies(
541         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
542
543     /// Merge consecutive store operations into a wide store.
544     /// This optimization uses wide integers or vectors when possible.
545     /// \return number of stores that were merged into a merged store (the
546     /// affected nodes are stored as a prefix in \p StoreNodes).
547     bool MergeConsecutiveStores(StoreSDNode *N);
548
549     /// \brief Try to transform a truncation where C is a constant:
550     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
551     ///
552     /// \p N needs to be a truncation and its first operand an AND. Other
553     /// requirements are checked by the function (e.g. that trunc is
554     /// single-use) and if missed an empty SDValue is returned.
555     SDValue distributeTruncateThroughAnd(SDNode *N);
556
557   public:
558     /// Runs the dag combiner on all nodes in the work list
559     void Run(CombineLevel AtLevel);
560
561     SelectionDAG &getDAG() const { return DAG; }
562
563     /// Returns a type large enough to hold any valid shift amount - before type
564     /// legalization these can be huge.
565     EVT getShiftAmountTy(EVT LHSTy) {
566       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
567       if (LHSTy.isVector())
568         return LHSTy;
569       auto &DL = DAG.getDataLayout();
570       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
571                         : TLI.getPointerTy(DL);
572     }
573
574     /// This method returns true if we are running before type legalization or
575     /// if the specified VT is legal.
576     bool isTypeLegal(const EVT &VT) {
577       if (!LegalTypes) return true;
578       return TLI.isTypeLegal(VT);
579     }
580
581     /// Convenience wrapper around TargetLowering::getSetCCResultType
582     EVT getSetCCResultType(EVT VT) const {
583       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
584     }
585   };
586
587 /// This class is a DAGUpdateListener that removes any deleted
588 /// nodes from the worklist.
589 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
590   DAGCombiner &DC;
591
592 public:
593   explicit WorklistRemover(DAGCombiner &dc)
594     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
595
596   void NodeDeleted(SDNode *N, SDNode *E) override {
597     DC.removeFromWorklist(N);
598   }
599 };
600
601 } // end anonymous namespace
602
603 //===----------------------------------------------------------------------===//
604 //  TargetLowering::DAGCombinerInfo implementation
605 //===----------------------------------------------------------------------===//
606
607 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
608   ((DAGCombiner*)DC)->AddToWorklist(N);
609 }
610
611 SDValue TargetLowering::DAGCombinerInfo::
612 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
613   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
614 }
615
616 SDValue TargetLowering::DAGCombinerInfo::
617 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
618   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
619 }
620
621 SDValue TargetLowering::DAGCombinerInfo::
622 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
623   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
624 }
625
626 void TargetLowering::DAGCombinerInfo::
627 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
628   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
629 }
630
631 //===----------------------------------------------------------------------===//
632 // Helper Functions
633 //===----------------------------------------------------------------------===//
634
635 void DAGCombiner::deleteAndRecombine(SDNode *N) {
636   removeFromWorklist(N);
637
638   // If the operands of this node are only used by the node, they will now be
639   // dead. Make sure to re-visit them and recursively delete dead nodes.
640   for (const SDValue &Op : N->ops())
641     // For an operand generating multiple values, one of the values may
642     // become dead allowing further simplification (e.g. split index
643     // arithmetic from an indexed load).
644     if (Op->hasOneUse() || Op->getNumValues() > 1)
645       AddToWorklist(Op.getNode());
646
647   DAG.DeleteNode(N);
648 }
649
650 /// Return 1 if we can compute the negated form of the specified expression for
651 /// the same cost as the expression itself, or 2 if we can compute the negated
652 /// form more cheaply than the expression itself.
653 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
654                                const TargetLowering &TLI,
655                                const TargetOptions *Options,
656                                unsigned Depth = 0) {
657   // fneg is removable even if it has multiple uses.
658   if (Op.getOpcode() == ISD::FNEG) return 2;
659
660   // Don't allow anything with multiple uses.
661   if (!Op.hasOneUse()) return 0;
662
663   // Don't recurse exponentially.
664   if (Depth > 6) return 0;
665
666   switch (Op.getOpcode()) {
667   default: return false;
668   case ISD::ConstantFP: {
669     if (!LegalOperations)
670       return 1;
671
672     // Don't invert constant FP values after legalization unless the target says
673     // the negated constant is legal.
674     EVT VT = Op.getValueType();
675     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
676       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
677   }
678   case ISD::FADD:
679     // FIXME: determine better conditions for this xform.
680     if (!Options->UnsafeFPMath) return 0;
681
682     // After operation legalization, it might not be legal to create new FSUBs.
683     if (LegalOperations &&
684         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
685       return 0;
686
687     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
688     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
689                                     Options, Depth + 1))
690       return V;
691     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
692     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
693                               Depth + 1);
694   case ISD::FSUB:
695     // We can't turn -(A-B) into B-A when we honor signed zeros.
696     if (!Options->NoSignedZerosFPMath &&
697         !Op.getNode()->getFlags().hasNoSignedZeros())
698       return 0;
699
700     // fold (fneg (fsub A, B)) -> (fsub B, A)
701     return 1;
702
703   case ISD::FMUL:
704   case ISD::FDIV:
705     if (Options->HonorSignDependentRoundingFPMath()) return 0;
706
707     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
708     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
709                                     Options, Depth + 1))
710       return V;
711
712     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
713                               Depth + 1);
714
715   case ISD::FP_EXTEND:
716   case ISD::FP_ROUND:
717   case ISD::FSIN:
718     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
719                               Depth + 1);
720   }
721 }
722
723 /// If isNegatibleForFree returns true, return the newly negated expression.
724 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
725                                     bool LegalOperations, unsigned Depth = 0) {
726   const TargetOptions &Options = DAG.getTarget().Options;
727   // fneg is removable even if it has multiple uses.
728   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
729
730   // Don't allow anything with multiple uses.
731   assert(Op.hasOneUse() && "Unknown reuse!");
732
733   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
734
735   const SDNodeFlags Flags = Op.getNode()->getFlags();
736
737   switch (Op.getOpcode()) {
738   default: llvm_unreachable("Unknown code");
739   case ISD::ConstantFP: {
740     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
741     V.changeSign();
742     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
743   }
744   case ISD::FADD:
745     // FIXME: determine better conditions for this xform.
746     assert(Options.UnsafeFPMath);
747
748     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
749     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
750                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
751       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
752                          GetNegatedExpression(Op.getOperand(0), DAG,
753                                               LegalOperations, Depth+1),
754                          Op.getOperand(1), Flags);
755     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
756     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
757                        GetNegatedExpression(Op.getOperand(1), DAG,
758                                             LegalOperations, Depth+1),
759                        Op.getOperand(0), Flags);
760   case ISD::FSUB:
761     // fold (fneg (fsub 0, B)) -> B
762     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
763       if (N0CFP->isZero())
764         return Op.getOperand(1);
765
766     // fold (fneg (fsub A, B)) -> (fsub B, A)
767     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
768                        Op.getOperand(1), Op.getOperand(0), Flags);
769
770   case ISD::FMUL:
771   case ISD::FDIV:
772     assert(!Options.HonorSignDependentRoundingFPMath());
773
774     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
775     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
776                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
777       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
778                          GetNegatedExpression(Op.getOperand(0), DAG,
779                                               LegalOperations, Depth+1),
780                          Op.getOperand(1), Flags);
781
782     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
783     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
784                        Op.getOperand(0),
785                        GetNegatedExpression(Op.getOperand(1), DAG,
786                                             LegalOperations, Depth+1), Flags);
787
788   case ISD::FP_EXTEND:
789   case ISD::FSIN:
790     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
791                        GetNegatedExpression(Op.getOperand(0), DAG,
792                                             LegalOperations, Depth+1));
793   case ISD::FP_ROUND:
794       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
795                          GetNegatedExpression(Op.getOperand(0), DAG,
796                                               LegalOperations, Depth+1),
797                          Op.getOperand(1));
798   }
799 }
800
801 // APInts must be the same size for most operations, this helper
802 // function zero extends the shorter of the pair so that they match.
803 // We provide an Offset so that we can create bitwidths that won't overflow.
804 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
805   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
806   LHS = LHS.zextOrSelf(Bits);
807   RHS = RHS.zextOrSelf(Bits);
808 }
809
810 // Return true if this node is a setcc, or is a select_cc
811 // that selects between the target values used for true and false, making it
812 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
813 // the appropriate nodes based on the type of node we are checking. This
814 // simplifies life a bit for the callers.
815 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
816                                     SDValue &CC) const {
817   if (N.getOpcode() == ISD::SETCC) {
818     LHS = N.getOperand(0);
819     RHS = N.getOperand(1);
820     CC  = N.getOperand(2);
821     return true;
822   }
823
824   if (N.getOpcode() != ISD::SELECT_CC ||
825       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
826       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
827     return false;
828
829   if (TLI.getBooleanContents(N.getValueType()) ==
830       TargetLowering::UndefinedBooleanContent)
831     return false;
832
833   LHS = N.getOperand(0);
834   RHS = N.getOperand(1);
835   CC  = N.getOperand(4);
836   return true;
837 }
838
839 /// Return true if this is a SetCC-equivalent operation with only one use.
840 /// If this is true, it allows the users to invert the operation for free when
841 /// it is profitable to do so.
842 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
843   SDValue N0, N1, N2;
844   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
845     return true;
846   return false;
847 }
848
849 // \brief Returns the SDNode if it is a constant float BuildVector
850 // or constant float.
851 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
852   if (isa<ConstantFPSDNode>(N))
853     return N.getNode();
854   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
855     return N.getNode();
856   return nullptr;
857 }
858
859 // Determines if it is a constant integer or a build vector of constant
860 // integers (and undefs).
861 // Do not permit build vector implicit truncation.
862 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
863   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
864     return !(Const->isOpaque() && NoOpaques);
865   if (N.getOpcode() != ISD::BUILD_VECTOR)
866     return false;
867   unsigned BitWidth = N.getScalarValueSizeInBits();
868   for (const SDValue &Op : N->op_values()) {
869     if (Op.isUndef())
870       continue;
871     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
872     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
873         (Const->isOpaque() && NoOpaques))
874       return false;
875   }
876   return true;
877 }
878
879 // Determines if it is a constant null integer or a splatted vector of a
880 // constant null integer (with no undefs).
881 // Build vector implicit truncation is not an issue for null values.
882 static bool isNullConstantOrNullSplatConstant(SDValue N) {
883   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
884     return Splat->isNullValue();
885   return false;
886 }
887
888 // Determines if it is a constant integer of one or a splatted vector of a
889 // constant integer of one (with no undefs).
890 // Do not permit build vector implicit truncation.
891 static bool isOneConstantOrOneSplatConstant(SDValue N) {
892   unsigned BitWidth = N.getScalarValueSizeInBits();
893   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
894     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
895   return false;
896 }
897
898 // Determines if it is a constant integer of all ones or a splatted vector of a
899 // constant integer of all ones (with no undefs).
900 // Do not permit build vector implicit truncation.
901 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
902   unsigned BitWidth = N.getScalarValueSizeInBits();
903   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
904     return Splat->isAllOnesValue() &&
905            Splat->getAPIntValue().getBitWidth() == BitWidth;
906   return false;
907 }
908
909 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
910 // undef's.
911 static bool isAnyConstantBuildVector(const SDNode *N) {
912   return ISD::isBuildVectorOfConstantSDNodes(N) ||
913          ISD::isBuildVectorOfConstantFPSDNodes(N);
914 }
915
916 // Attempt to match a unary predicate against a scalar/splat constant or
917 // every element of a constant BUILD_VECTOR.
918 static bool matchUnaryPredicate(SDValue Op,
919                                 std::function<bool(ConstantSDNode *)> Match) {
920   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
921     return Match(Cst);
922
923   if (ISD::BUILD_VECTOR != Op.getOpcode())
924     return false;
925
926   EVT SVT = Op.getValueType().getScalarType();
927   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
928     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
929     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
930       return false;
931   }
932   return true;
933 }
934
935 // Attempt to match a binary predicate against a pair of scalar/splat constants
936 // or every element of a pair of constant BUILD_VECTORs.
937 static bool matchBinaryPredicate(
938     SDValue LHS, SDValue RHS,
939     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
940   if (LHS.getValueType() != RHS.getValueType())
941     return false;
942
943   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
944     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
945       return Match(LHSCst, RHSCst);
946
947   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
948       ISD::BUILD_VECTOR != RHS.getOpcode())
949     return false;
950
951   EVT SVT = LHS.getValueType().getScalarType();
952   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
953     auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
954     auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
955     if (!LHSCst || !RHSCst)
956       return false;
957     if (LHSCst->getValueType(0) != SVT ||
958         LHSCst->getValueType(0) != RHSCst->getValueType(0))
959       return false;
960     if (!Match(LHSCst, RHSCst))
961       return false;
962   }
963   return true;
964 }
965
966 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
967                                     SDValue N1) {
968   EVT VT = N0.getValueType();
969   if (N0.getOpcode() == Opc) {
970     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
971       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
972         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
973         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
974           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
975         return SDValue();
976       }
977       if (N0.hasOneUse()) {
978         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
979         // use
980         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
981         if (!OpNode.getNode())
982           return SDValue();
983         AddToWorklist(OpNode.getNode());
984         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
985       }
986     }
987   }
988
989   if (N1.getOpcode() == Opc) {
990     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
991       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
992         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
993         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
994           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
995         return SDValue();
996       }
997       if (N1.hasOneUse()) {
998         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
999         // use
1000         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
1001         if (!OpNode.getNode())
1002           return SDValue();
1003         AddToWorklist(OpNode.getNode());
1004         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
1005       }
1006     }
1007   }
1008
1009   return SDValue();
1010 }
1011
1012 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1013                                bool AddTo) {
1014   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1015   ++NodesCombined;
1016   DEBUG(dbgs() << "\nReplacing.1 ";
1017         N->dump(&DAG);
1018         dbgs() << "\nWith: ";
1019         To[0].getNode()->dump(&DAG);
1020         dbgs() << " and " << NumTo-1 << " other values\n");
1021   for (unsigned i = 0, e = NumTo; i != e; ++i)
1022     assert((!To[i].getNode() ||
1023             N->getValueType(i) == To[i].getValueType()) &&
1024            "Cannot combine value to value of different type!");
1025
1026   WorklistRemover DeadNodes(*this);
1027   DAG.ReplaceAllUsesWith(N, To);
1028   if (AddTo) {
1029     // Push the new nodes and any users onto the worklist
1030     for (unsigned i = 0, e = NumTo; i != e; ++i) {
1031       if (To[i].getNode()) {
1032         AddToWorklist(To[i].getNode());
1033         AddUsersToWorklist(To[i].getNode());
1034       }
1035     }
1036   }
1037
1038   // Finally, if the node is now dead, remove it from the graph.  The node
1039   // may not be dead if the replacement process recursively simplified to
1040   // something else needing this node.
1041   if (N->use_empty())
1042     deleteAndRecombine(N);
1043   return SDValue(N, 0);
1044 }
1045
1046 void DAGCombiner::
1047 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1048   // Replace all uses.  If any nodes become isomorphic to other nodes and
1049   // are deleted, make sure to remove them from our worklist.
1050   WorklistRemover DeadNodes(*this);
1051   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1052
1053   // Push the new node and any (possibly new) users onto the worklist.
1054   AddToWorklist(TLO.New.getNode());
1055   AddUsersToWorklist(TLO.New.getNode());
1056
1057   // Finally, if the node is now dead, remove it from the graph.  The node
1058   // may not be dead if the replacement process recursively simplified to
1059   // something else needing this node.
1060   if (TLO.Old.getNode()->use_empty())
1061     deleteAndRecombine(TLO.Old.getNode());
1062 }
1063
1064 /// Check the specified integer node value to see if it can be simplified or if
1065 /// things it uses can be simplified by bit propagation. If so, return true.
1066 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1067   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1068   KnownBits Known;
1069   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1070     return false;
1071
1072   // Revisit the node.
1073   AddToWorklist(Op.getNode());
1074
1075   // Replace the old value with the new one.
1076   ++NodesCombined;
1077   DEBUG(dbgs() << "\nReplacing.2 ";
1078         TLO.Old.getNode()->dump(&DAG);
1079         dbgs() << "\nWith: ";
1080         TLO.New.getNode()->dump(&DAG);
1081         dbgs() << '\n');
1082
1083   CommitTargetLoweringOpt(TLO);
1084   return true;
1085 }
1086
1087 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1088   SDLoc DL(Load);
1089   EVT VT = Load->getValueType(0);
1090   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1091
1092   DEBUG(dbgs() << "\nReplacing.9 ";
1093         Load->dump(&DAG);
1094         dbgs() << "\nWith: ";
1095         Trunc.getNode()->dump(&DAG);
1096         dbgs() << '\n');
1097   WorklistRemover DeadNodes(*this);
1098   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1099   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1100   deleteAndRecombine(Load);
1101   AddToWorklist(Trunc.getNode());
1102 }
1103
1104 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1105   Replace = false;
1106   SDLoc DL(Op);
1107   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1108     LoadSDNode *LD = cast<LoadSDNode>(Op);
1109     EVT MemVT = LD->getMemoryVT();
1110     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1111       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1112                                                        : ISD::EXTLOAD)
1113       : LD->getExtensionType();
1114     Replace = true;
1115     return DAG.getExtLoad(ExtType, DL, PVT,
1116                           LD->getChain(), LD->getBasePtr(),
1117                           MemVT, LD->getMemOperand());
1118   }
1119
1120   unsigned Opc = Op.getOpcode();
1121   switch (Opc) {
1122   default: break;
1123   case ISD::AssertSext:
1124     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1125       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1126     break;
1127   case ISD::AssertZext:
1128     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1129       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1130     break;
1131   case ISD::Constant: {
1132     unsigned ExtOpc =
1133       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1134     return DAG.getNode(ExtOpc, DL, PVT, Op);
1135   }
1136   }
1137
1138   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1139     return SDValue();
1140   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1141 }
1142
1143 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1144   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1145     return SDValue();
1146   EVT OldVT = Op.getValueType();
1147   SDLoc DL(Op);
1148   bool Replace = false;
1149   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1150   if (!NewOp.getNode())
1151     return SDValue();
1152   AddToWorklist(NewOp.getNode());
1153
1154   if (Replace)
1155     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1156   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1157                      DAG.getValueType(OldVT));
1158 }
1159
1160 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1161   EVT OldVT = Op.getValueType();
1162   SDLoc DL(Op);
1163   bool Replace = false;
1164   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1165   if (!NewOp.getNode())
1166     return SDValue();
1167   AddToWorklist(NewOp.getNode());
1168
1169   if (Replace)
1170     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1171   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1172 }
1173
1174 /// Promote the specified integer binary operation if the target indicates it is
1175 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1176 /// i32 since i16 instructions are longer.
1177 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1178   if (!LegalOperations)
1179     return SDValue();
1180
1181   EVT VT = Op.getValueType();
1182   if (VT.isVector() || !VT.isInteger())
1183     return SDValue();
1184
1185   // If operation type is 'undesirable', e.g. i16 on x86, consider
1186   // promoting it.
1187   unsigned Opc = Op.getOpcode();
1188   if (TLI.isTypeDesirableForOp(Opc, VT))
1189     return SDValue();
1190
1191   EVT PVT = VT;
1192   // Consult target whether it is a good idea to promote this operation and
1193   // what's the right type to promote it to.
1194   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1195     assert(PVT != VT && "Don't know what type to promote to!");
1196
1197     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1198
1199     bool Replace0 = false;
1200     SDValue N0 = Op.getOperand(0);
1201     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1202
1203     bool Replace1 = false;
1204     SDValue N1 = Op.getOperand(1);
1205     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1206     SDLoc DL(Op);
1207
1208     SDValue RV =
1209         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1210
1211     // We are always replacing N0/N1's use in N and only need
1212     // additional replacements if there are additional uses.
1213     Replace0 &= !N0->hasOneUse();
1214     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1215
1216     // Combine Op here so it is preserved past replacements.
1217     CombineTo(Op.getNode(), RV);
1218
1219     // If operands have a use ordering, make sure we deal with
1220     // predecessor first.
1221     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1222       std::swap(N0, N1);
1223       std::swap(NN0, NN1);
1224     }
1225
1226     if (Replace0) {
1227       AddToWorklist(NN0.getNode());
1228       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1229     }
1230     if (Replace1) {
1231       AddToWorklist(NN1.getNode());
1232       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1233     }
1234     return Op;
1235   }
1236   return SDValue();
1237 }
1238
1239 /// Promote the specified integer shift operation if the target indicates it is
1240 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1241 /// i32 since i16 instructions are longer.
1242 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1243   if (!LegalOperations)
1244     return SDValue();
1245
1246   EVT VT = Op.getValueType();
1247   if (VT.isVector() || !VT.isInteger())
1248     return SDValue();
1249
1250   // If operation type is 'undesirable', e.g. i16 on x86, consider
1251   // promoting it.
1252   unsigned Opc = Op.getOpcode();
1253   if (TLI.isTypeDesirableForOp(Opc, VT))
1254     return SDValue();
1255
1256   EVT PVT = VT;
1257   // Consult target whether it is a good idea to promote this operation and
1258   // what's the right type to promote it to.
1259   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1260     assert(PVT != VT && "Don't know what type to promote to!");
1261
1262     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1263
1264     bool Replace = false;
1265     SDValue N0 = Op.getOperand(0);
1266     SDValue N1 = Op.getOperand(1);
1267     if (Opc == ISD::SRA)
1268       N0 = SExtPromoteOperand(N0, PVT);
1269     else if (Opc == ISD::SRL)
1270       N0 = ZExtPromoteOperand(N0, PVT);
1271     else
1272       N0 = PromoteOperand(N0, PVT, Replace);
1273
1274     if (!N0.getNode())
1275       return SDValue();
1276
1277     SDLoc DL(Op);
1278     SDValue RV =
1279         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1280
1281     AddToWorklist(N0.getNode());
1282     if (Replace)
1283       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1284
1285     // Deal with Op being deleted.
1286     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1287       return RV;
1288   }
1289   return SDValue();
1290 }
1291
1292 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1293   if (!LegalOperations)
1294     return SDValue();
1295
1296   EVT VT = Op.getValueType();
1297   if (VT.isVector() || !VT.isInteger())
1298     return SDValue();
1299
1300   // If operation type is 'undesirable', e.g. i16 on x86, consider
1301   // promoting it.
1302   unsigned Opc = Op.getOpcode();
1303   if (TLI.isTypeDesirableForOp(Opc, VT))
1304     return SDValue();
1305
1306   EVT PVT = VT;
1307   // Consult target whether it is a good idea to promote this operation and
1308   // what's the right type to promote it to.
1309   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1310     assert(PVT != VT && "Don't know what type to promote to!");
1311     // fold (aext (aext x)) -> (aext x)
1312     // fold (aext (zext x)) -> (zext x)
1313     // fold (aext (sext x)) -> (sext x)
1314     DEBUG(dbgs() << "\nPromoting ";
1315           Op.getNode()->dump(&DAG));
1316     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1317   }
1318   return SDValue();
1319 }
1320
1321 bool DAGCombiner::PromoteLoad(SDValue Op) {
1322   if (!LegalOperations)
1323     return false;
1324
1325   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1326     return false;
1327
1328   EVT VT = Op.getValueType();
1329   if (VT.isVector() || !VT.isInteger())
1330     return false;
1331
1332   // If operation type is 'undesirable', e.g. i16 on x86, consider
1333   // promoting it.
1334   unsigned Opc = Op.getOpcode();
1335   if (TLI.isTypeDesirableForOp(Opc, VT))
1336     return false;
1337
1338   EVT PVT = VT;
1339   // Consult target whether it is a good idea to promote this operation and
1340   // what's the right type to promote it to.
1341   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1342     assert(PVT != VT && "Don't know what type to promote to!");
1343
1344     SDLoc DL(Op);
1345     SDNode *N = Op.getNode();
1346     LoadSDNode *LD = cast<LoadSDNode>(N);
1347     EVT MemVT = LD->getMemoryVT();
1348     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1349       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1350                                                        : ISD::EXTLOAD)
1351       : LD->getExtensionType();
1352     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1353                                    LD->getChain(), LD->getBasePtr(),
1354                                    MemVT, LD->getMemOperand());
1355     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1356
1357     DEBUG(dbgs() << "\nPromoting ";
1358           N->dump(&DAG);
1359           dbgs() << "\nTo: ";
1360           Result.getNode()->dump(&DAG);
1361           dbgs() << '\n');
1362     WorklistRemover DeadNodes(*this);
1363     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1364     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1365     deleteAndRecombine(N);
1366     AddToWorklist(Result.getNode());
1367     return true;
1368   }
1369   return false;
1370 }
1371
1372 /// \brief Recursively delete a node which has no uses and any operands for
1373 /// which it is the only use.
1374 ///
1375 /// Note that this both deletes the nodes and removes them from the worklist.
1376 /// It also adds any nodes who have had a user deleted to the worklist as they
1377 /// may now have only one use and subject to other combines.
1378 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1379   if (!N->use_empty())
1380     return false;
1381
1382   SmallSetVector<SDNode *, 16> Nodes;
1383   Nodes.insert(N);
1384   do {
1385     N = Nodes.pop_back_val();
1386     if (!N)
1387       continue;
1388
1389     if (N->use_empty()) {
1390       for (const SDValue &ChildN : N->op_values())
1391         Nodes.insert(ChildN.getNode());
1392
1393       removeFromWorklist(N);
1394       DAG.DeleteNode(N);
1395     } else {
1396       AddToWorklist(N);
1397     }
1398   } while (!Nodes.empty());
1399   return true;
1400 }
1401
1402 //===----------------------------------------------------------------------===//
1403 //  Main DAG Combiner implementation
1404 //===----------------------------------------------------------------------===//
1405
1406 void DAGCombiner::Run(CombineLevel AtLevel) {
1407   // set the instance variables, so that the various visit routines may use it.
1408   Level = AtLevel;
1409   LegalOperations = Level >= AfterLegalizeVectorOps;
1410   LegalTypes = Level >= AfterLegalizeTypes;
1411
1412   // Add all the dag nodes to the worklist.
1413   for (SDNode &Node : DAG.allnodes())
1414     AddToWorklist(&Node);
1415
1416   // Create a dummy node (which is not added to allnodes), that adds a reference
1417   // to the root node, preventing it from being deleted, and tracking any
1418   // changes of the root.
1419   HandleSDNode Dummy(DAG.getRoot());
1420
1421   // While the worklist isn't empty, find a node and try to combine it.
1422   while (!WorklistMap.empty()) {
1423     SDNode *N;
1424     // The Worklist holds the SDNodes in order, but it may contain null entries.
1425     do {
1426       N = Worklist.pop_back_val();
1427     } while (!N);
1428
1429     bool GoodWorklistEntry = WorklistMap.erase(N);
1430     (void)GoodWorklistEntry;
1431     assert(GoodWorklistEntry &&
1432            "Found a worklist entry without a corresponding map entry!");
1433
1434     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1435     // N is deleted from the DAG, since they too may now be dead or may have a
1436     // reduced number of uses, allowing other xforms.
1437     if (recursivelyDeleteUnusedNodes(N))
1438       continue;
1439
1440     WorklistRemover DeadNodes(*this);
1441
1442     // If this combine is running after legalizing the DAG, re-legalize any
1443     // nodes pulled off the worklist.
1444     if (Level == AfterLegalizeDAG) {
1445       SmallSetVector<SDNode *, 16> UpdatedNodes;
1446       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1447
1448       for (SDNode *LN : UpdatedNodes) {
1449         AddToWorklist(LN);
1450         AddUsersToWorklist(LN);
1451       }
1452       if (!NIsValid)
1453         continue;
1454     }
1455
1456     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1457
1458     // Add any operands of the new node which have not yet been combined to the
1459     // worklist as well. Because the worklist uniques things already, this
1460     // won't repeatedly process the same operand.
1461     CombinedNodes.insert(N);
1462     for (const SDValue &ChildN : N->op_values())
1463       if (!CombinedNodes.count(ChildN.getNode()))
1464         AddToWorklist(ChildN.getNode());
1465
1466     SDValue RV = combine(N);
1467
1468     if (!RV.getNode())
1469       continue;
1470
1471     ++NodesCombined;
1472
1473     // If we get back the same node we passed in, rather than a new node or
1474     // zero, we know that the node must have defined multiple values and
1475     // CombineTo was used.  Since CombineTo takes care of the worklist
1476     // mechanics for us, we have no work to do in this case.
1477     if (RV.getNode() == N)
1478       continue;
1479
1480     assert(N->getOpcode() != ISD::DELETED_NODE &&
1481            RV.getOpcode() != ISD::DELETED_NODE &&
1482            "Node was deleted but visit returned new node!");
1483
1484     DEBUG(dbgs() << " ... into: ";
1485           RV.getNode()->dump(&DAG));
1486
1487     if (N->getNumValues() == RV.getNode()->getNumValues())
1488       DAG.ReplaceAllUsesWith(N, RV.getNode());
1489     else {
1490       assert(N->getValueType(0) == RV.getValueType() &&
1491              N->getNumValues() == 1 && "Type mismatch");
1492       DAG.ReplaceAllUsesWith(N, &RV);
1493     }
1494
1495     // Push the new node and any users onto the worklist
1496     AddToWorklist(RV.getNode());
1497     AddUsersToWorklist(RV.getNode());
1498
1499     // Finally, if the node is now dead, remove it from the graph.  The node
1500     // may not be dead if the replacement process recursively simplified to
1501     // something else needing this node. This will also take care of adding any
1502     // operands which have lost a user to the worklist.
1503     recursivelyDeleteUnusedNodes(N);
1504   }
1505
1506   // If the root changed (e.g. it was a dead load, update the root).
1507   DAG.setRoot(Dummy.getValue());
1508   DAG.RemoveDeadNodes();
1509 }
1510
1511 SDValue DAGCombiner::visit(SDNode *N) {
1512   switch (N->getOpcode()) {
1513   default: break;
1514   case ISD::TokenFactor:        return visitTokenFactor(N);
1515   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1516   case ISD::ADD:                return visitADD(N);
1517   case ISD::SUB:                return visitSUB(N);
1518   case ISD::ADDC:               return visitADDC(N);
1519   case ISD::UADDO:              return visitUADDO(N);
1520   case ISD::SUBC:               return visitSUBC(N);
1521   case ISD::USUBO:              return visitUSUBO(N);
1522   case ISD::ADDE:               return visitADDE(N);
1523   case ISD::ADDCARRY:           return visitADDCARRY(N);
1524   case ISD::SUBE:               return visitSUBE(N);
1525   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1526   case ISD::MUL:                return visitMUL(N);
1527   case ISD::SDIV:               return visitSDIV(N);
1528   case ISD::UDIV:               return visitUDIV(N);
1529   case ISD::SREM:
1530   case ISD::UREM:               return visitREM(N);
1531   case ISD::MULHU:              return visitMULHU(N);
1532   case ISD::MULHS:              return visitMULHS(N);
1533   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1534   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1535   case ISD::SMULO:              return visitSMULO(N);
1536   case ISD::UMULO:              return visitUMULO(N);
1537   case ISD::SMIN:
1538   case ISD::SMAX:
1539   case ISD::UMIN:
1540   case ISD::UMAX:               return visitIMINMAX(N);
1541   case ISD::AND:                return visitAND(N);
1542   case ISD::OR:                 return visitOR(N);
1543   case ISD::XOR:                return visitXOR(N);
1544   case ISD::SHL:                return visitSHL(N);
1545   case ISD::SRA:                return visitSRA(N);
1546   case ISD::SRL:                return visitSRL(N);
1547   case ISD::ROTR:
1548   case ISD::ROTL:               return visitRotate(N);
1549   case ISD::ABS:                return visitABS(N);
1550   case ISD::BSWAP:              return visitBSWAP(N);
1551   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1552   case ISD::CTLZ:               return visitCTLZ(N);
1553   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1554   case ISD::CTTZ:               return visitCTTZ(N);
1555   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1556   case ISD::CTPOP:              return visitCTPOP(N);
1557   case ISD::SELECT:             return visitSELECT(N);
1558   case ISD::VSELECT:            return visitVSELECT(N);
1559   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1560   case ISD::SETCC:              return visitSETCC(N);
1561   case ISD::SETCCE:             return visitSETCCE(N);
1562   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1563   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1564   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1565   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1566   case ISD::AssertSext:
1567   case ISD::AssertZext:         return visitAssertExt(N);
1568   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1569   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1570   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1571   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1572   case ISD::BITCAST:            return visitBITCAST(N);
1573   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1574   case ISD::FADD:               return visitFADD(N);
1575   case ISD::FSUB:               return visitFSUB(N);
1576   case ISD::FMUL:               return visitFMUL(N);
1577   case ISD::FMA:                return visitFMA(N);
1578   case ISD::FDIV:               return visitFDIV(N);
1579   case ISD::FREM:               return visitFREM(N);
1580   case ISD::FSQRT:              return visitFSQRT(N);
1581   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1582   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1583   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1584   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1585   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1586   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1587   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1588   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1589   case ISD::FNEG:               return visitFNEG(N);
1590   case ISD::FABS:               return visitFABS(N);
1591   case ISD::FFLOOR:             return visitFFLOOR(N);
1592   case ISD::FMINNUM:            return visitFMINNUM(N);
1593   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1594   case ISD::FCEIL:              return visitFCEIL(N);
1595   case ISD::FTRUNC:             return visitFTRUNC(N);
1596   case ISD::BRCOND:             return visitBRCOND(N);
1597   case ISD::BR_CC:              return visitBR_CC(N);
1598   case ISD::LOAD:               return visitLOAD(N);
1599   case ISD::STORE:              return visitSTORE(N);
1600   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1601   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1602   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1603   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1604   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1605   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1606   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1607   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1608   case ISD::MGATHER:            return visitMGATHER(N);
1609   case ISD::MLOAD:              return visitMLOAD(N);
1610   case ISD::MSCATTER:           return visitMSCATTER(N);
1611   case ISD::MSTORE:             return visitMSTORE(N);
1612   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1613   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1614   }
1615   return SDValue();
1616 }
1617
1618 SDValue DAGCombiner::combine(SDNode *N) {
1619   SDValue RV = visit(N);
1620
1621   // If nothing happened, try a target-specific DAG combine.
1622   if (!RV.getNode()) {
1623     assert(N->getOpcode() != ISD::DELETED_NODE &&
1624            "Node was deleted but visit returned NULL!");
1625
1626     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1627         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1628
1629       // Expose the DAG combiner to the target combiner impls.
1630       TargetLowering::DAGCombinerInfo
1631         DagCombineInfo(DAG, Level, false, this);
1632
1633       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1634     }
1635   }
1636
1637   // If nothing happened still, try promoting the operation.
1638   if (!RV.getNode()) {
1639     switch (N->getOpcode()) {
1640     default: break;
1641     case ISD::ADD:
1642     case ISD::SUB:
1643     case ISD::MUL:
1644     case ISD::AND:
1645     case ISD::OR:
1646     case ISD::XOR:
1647       RV = PromoteIntBinOp(SDValue(N, 0));
1648       break;
1649     case ISD::SHL:
1650     case ISD::SRA:
1651     case ISD::SRL:
1652       RV = PromoteIntShiftOp(SDValue(N, 0));
1653       break;
1654     case ISD::SIGN_EXTEND:
1655     case ISD::ZERO_EXTEND:
1656     case ISD::ANY_EXTEND:
1657       RV = PromoteExtend(SDValue(N, 0));
1658       break;
1659     case ISD::LOAD:
1660       if (PromoteLoad(SDValue(N, 0)))
1661         RV = SDValue(N, 0);
1662       break;
1663     }
1664   }
1665
1666   // If N is a commutative binary node, try eliminate it if the commuted
1667   // version is already present in the DAG.
1668   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1669       N->getNumValues() == 1) {
1670     SDValue N0 = N->getOperand(0);
1671     SDValue N1 = N->getOperand(1);
1672
1673     // Constant operands are canonicalized to RHS.
1674     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1675       SDValue Ops[] = {N1, N0};
1676       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1677                                             N->getFlags());
1678       if (CSENode)
1679         return SDValue(CSENode, 0);
1680     }
1681   }
1682
1683   return RV;
1684 }
1685
1686 /// Given a node, return its input chain if it has one, otherwise return a null
1687 /// sd operand.
1688 static SDValue getInputChainForNode(SDNode *N) {
1689   if (unsigned NumOps = N->getNumOperands()) {
1690     if (N->getOperand(0).getValueType() == MVT::Other)
1691       return N->getOperand(0);
1692     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1693       return N->getOperand(NumOps-1);
1694     for (unsigned i = 1; i < NumOps-1; ++i)
1695       if (N->getOperand(i).getValueType() == MVT::Other)
1696         return N->getOperand(i);
1697   }
1698   return SDValue();
1699 }
1700
1701 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1702   // If N has two operands, where one has an input chain equal to the other,
1703   // the 'other' chain is redundant.
1704   if (N->getNumOperands() == 2) {
1705     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1706       return N->getOperand(0);
1707     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1708       return N->getOperand(1);
1709   }
1710
1711   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1712   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1713   SmallPtrSet<SDNode*, 16> SeenOps;
1714   bool Changed = false;             // If we should replace this token factor.
1715
1716   // Start out with this token factor.
1717   TFs.push_back(N);
1718
1719   // Iterate through token factors.  The TFs grows when new token factors are
1720   // encountered.
1721   for (unsigned i = 0; i < TFs.size(); ++i) {
1722     SDNode *TF = TFs[i];
1723
1724     // Check each of the operands.
1725     for (const SDValue &Op : TF->op_values()) {
1726       switch (Op.getOpcode()) {
1727       case ISD::EntryToken:
1728         // Entry tokens don't need to be added to the list. They are
1729         // redundant.
1730         Changed = true;
1731         break;
1732
1733       case ISD::TokenFactor:
1734         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1735           // Queue up for processing.
1736           TFs.push_back(Op.getNode());
1737           // Clean up in case the token factor is removed.
1738           AddToWorklist(Op.getNode());
1739           Changed = true;
1740           break;
1741         }
1742         LLVM_FALLTHROUGH;
1743
1744       default:
1745         // Only add if it isn't already in the list.
1746         if (SeenOps.insert(Op.getNode()).second)
1747           Ops.push_back(Op);
1748         else
1749           Changed = true;
1750         break;
1751       }
1752     }
1753   }
1754
1755   // Remove Nodes that are chained to another node in the list. Do so
1756   // by walking up chains breath-first stopping when we've seen
1757   // another operand. In general we must climb to the EntryNode, but we can exit
1758   // early if we find all remaining work is associated with just one operand as
1759   // no further pruning is possible.
1760
1761   // List of nodes to search through and original Ops from which they originate.
1762   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1763   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1764   SmallPtrSet<SDNode *, 16> SeenChains;
1765   bool DidPruneOps = false;
1766
1767   unsigned NumLeftToConsider = 0;
1768   for (const SDValue &Op : Ops) {
1769     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1770     OpWorkCount.push_back(1);
1771   }
1772
1773   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1774     // If this is an Op, we can remove the op from the list. Remark any
1775     // search associated with it as from the current OpNumber.
1776     if (SeenOps.count(Op) != 0) {
1777       Changed = true;
1778       DidPruneOps = true;
1779       unsigned OrigOpNumber = 0;
1780       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1781         OrigOpNumber++;
1782       assert((OrigOpNumber != Ops.size()) &&
1783              "expected to find TokenFactor Operand");
1784       // Re-mark worklist from OrigOpNumber to OpNumber
1785       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1786         if (Worklist[i].second == OrigOpNumber) {
1787           Worklist[i].second = OpNumber;
1788         }
1789       }
1790       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1791       OpWorkCount[OrigOpNumber] = 0;
1792       NumLeftToConsider--;
1793     }
1794     // Add if it's a new chain
1795     if (SeenChains.insert(Op).second) {
1796       OpWorkCount[OpNumber]++;
1797       Worklist.push_back(std::make_pair(Op, OpNumber));
1798     }
1799   };
1800
1801   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1802     // We need at least be consider at least 2 Ops to prune.
1803     if (NumLeftToConsider <= 1)
1804       break;
1805     auto CurNode = Worklist[i].first;
1806     auto CurOpNumber = Worklist[i].second;
1807     assert((OpWorkCount[CurOpNumber] > 0) &&
1808            "Node should not appear in worklist");
1809     switch (CurNode->getOpcode()) {
1810     case ISD::EntryToken:
1811       // Hitting EntryToken is the only way for the search to terminate without
1812       // hitting
1813       // another operand's search. Prevent us from marking this operand
1814       // considered.
1815       NumLeftToConsider++;
1816       break;
1817     case ISD::TokenFactor:
1818       for (const SDValue &Op : CurNode->op_values())
1819         AddToWorklist(i, Op.getNode(), CurOpNumber);
1820       break;
1821     case ISD::CopyFromReg:
1822     case ISD::CopyToReg:
1823       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1824       break;
1825     default:
1826       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1827         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1828       break;
1829     }
1830     OpWorkCount[CurOpNumber]--;
1831     if (OpWorkCount[CurOpNumber] == 0)
1832       NumLeftToConsider--;
1833   }
1834
1835   // If we've changed things around then replace token factor.
1836   if (Changed) {
1837     SDValue Result;
1838     if (Ops.empty()) {
1839       // The entry token is the only possible outcome.
1840       Result = DAG.getEntryNode();
1841     } else {
1842       if (DidPruneOps) {
1843         SmallVector<SDValue, 8> PrunedOps;
1844         //
1845         for (const SDValue &Op : Ops) {
1846           if (SeenChains.count(Op.getNode()) == 0)
1847             PrunedOps.push_back(Op);
1848         }
1849         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1850       } else {
1851         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1852       }
1853     }
1854     return Result;
1855   }
1856   return SDValue();
1857 }
1858
1859 /// MERGE_VALUES can always be eliminated.
1860 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1861   WorklistRemover DeadNodes(*this);
1862   // Replacing results may cause a different MERGE_VALUES to suddenly
1863   // be CSE'd with N, and carry its uses with it. Iterate until no
1864   // uses remain, to ensure that the node can be safely deleted.
1865   // First add the users of this node to the work list so that they
1866   // can be tried again once they have new operands.
1867   AddUsersToWorklist(N);
1868   do {
1869     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1870       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1871   } while (!N->use_empty());
1872   deleteAndRecombine(N);
1873   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1874 }
1875
1876 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1877 /// ConstantSDNode pointer else nullptr.
1878 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1879   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1880   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1881 }
1882
1883 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1884   auto BinOpcode = BO->getOpcode();
1885   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1886           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1887           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1888           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1889           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1890           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1891           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1892           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1893           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1894          "Unexpected binary operator");
1895
1896   // Bail out if any constants are opaque because we can't constant fold those.
1897   SDValue C1 = BO->getOperand(1);
1898   if (!isConstantOrConstantVector(C1, true) &&
1899       !isConstantFPBuildVectorOrConstantFP(C1))
1900     return SDValue();
1901
1902   // Don't do this unless the old select is going away. We want to eliminate the
1903   // binary operator, not replace a binop with a select.
1904   // TODO: Handle ISD::SELECT_CC.
1905   SDValue Sel = BO->getOperand(0);
1906   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1907     return SDValue();
1908
1909   SDValue CT = Sel.getOperand(1);
1910   if (!isConstantOrConstantVector(CT, true) &&
1911       !isConstantFPBuildVectorOrConstantFP(CT))
1912     return SDValue();
1913
1914   SDValue CF = Sel.getOperand(2);
1915   if (!isConstantOrConstantVector(CF, true) &&
1916       !isConstantFPBuildVectorOrConstantFP(CF))
1917     return SDValue();
1918
1919   // We have a select-of-constants followed by a binary operator with a
1920   // constant. Eliminate the binop by pulling the constant math into the select.
1921   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1922   EVT VT = Sel.getValueType();
1923   SDLoc DL(Sel);
1924   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1925   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1926           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1927          "Failed to constant fold a binop with constant operands");
1928
1929   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1930   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1931           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1932          "Failed to constant fold a binop with constant operands");
1933
1934   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1935 }
1936
1937 SDValue DAGCombiner::visitADD(SDNode *N) {
1938   SDValue N0 = N->getOperand(0);
1939   SDValue N1 = N->getOperand(1);
1940   EVT VT = N0.getValueType();
1941   SDLoc DL(N);
1942
1943   // fold vector ops
1944   if (VT.isVector()) {
1945     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1946       return FoldedVOp;
1947
1948     // fold (add x, 0) -> x, vector edition
1949     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1950       return N0;
1951     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1952       return N1;
1953   }
1954
1955   // fold (add x, undef) -> undef
1956   if (N0.isUndef())
1957     return N0;
1958
1959   if (N1.isUndef())
1960     return N1;
1961
1962   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1963     // canonicalize constant to RHS
1964     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1965       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1966     // fold (add c1, c2) -> c1+c2
1967     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1968                                       N1.getNode());
1969   }
1970
1971   // fold (add x, 0) -> x
1972   if (isNullConstant(N1))
1973     return N0;
1974
1975   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1976     // fold ((c1-A)+c2) -> (c1+c2)-A
1977     if (N0.getOpcode() == ISD::SUB &&
1978         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1979       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1980       return DAG.getNode(ISD::SUB, DL, VT,
1981                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1982                          N0.getOperand(1));
1983     }
1984
1985     // add (sext i1 X), 1 -> zext (not i1 X)
1986     // We don't transform this pattern:
1987     //   add (zext i1 X), -1 -> sext (not i1 X)
1988     // because most (?) targets generate better code for the zext form.
1989     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1990         isOneConstantOrOneSplatConstant(N1)) {
1991       SDValue X = N0.getOperand(0);
1992       if ((!LegalOperations ||
1993            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1994             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1995           X.getScalarValueSizeInBits() == 1) {
1996         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1997         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1998       }
1999     }
2000
2001     // Undo the add -> or combine to merge constant offsets from a frame index.
2002     if (N0.getOpcode() == ISD::OR &&
2003         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2004         isa<ConstantSDNode>(N0.getOperand(1)) &&
2005         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2006       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2007       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2008     }
2009   }
2010
2011   if (SDValue NewSel = foldBinOpIntoSelect(N))
2012     return NewSel;
2013
2014   // reassociate add
2015   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
2016     return RADD;
2017
2018   // fold ((0-A) + B) -> B-A
2019   if (N0.getOpcode() == ISD::SUB &&
2020       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2021     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2022
2023   // fold (A + (0-B)) -> A-B
2024   if (N1.getOpcode() == ISD::SUB &&
2025       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2026     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2027
2028   // fold (A+(B-A)) -> B
2029   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2030     return N1.getOperand(0);
2031
2032   // fold ((B-A)+A) -> B
2033   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2034     return N0.getOperand(0);
2035
2036   // fold (A+(B-(A+C))) to (B-C)
2037   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2038       N0 == N1.getOperand(1).getOperand(0))
2039     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2040                        N1.getOperand(1).getOperand(1));
2041
2042   // fold (A+(B-(C+A))) to (B-C)
2043   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2044       N0 == N1.getOperand(1).getOperand(1))
2045     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2046                        N1.getOperand(1).getOperand(0));
2047
2048   // fold (A+((B-A)+or-C)) to (B+or-C)
2049   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2050       N1.getOperand(0).getOpcode() == ISD::SUB &&
2051       N0 == N1.getOperand(0).getOperand(1))
2052     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2053                        N1.getOperand(1));
2054
2055   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2056   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2057     SDValue N00 = N0.getOperand(0);
2058     SDValue N01 = N0.getOperand(1);
2059     SDValue N10 = N1.getOperand(0);
2060     SDValue N11 = N1.getOperand(1);
2061
2062     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2063       return DAG.getNode(ISD::SUB, DL, VT,
2064                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2065                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2066   }
2067
2068   if (SimplifyDemandedBits(SDValue(N, 0)))
2069     return SDValue(N, 0);
2070
2071   // fold (a+b) -> (a|b) iff a and b share no bits.
2072   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2073       DAG.haveNoCommonBitsSet(N0, N1))
2074     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2075
2076   if (SDValue Combined = visitADDLike(N0, N1, N))
2077     return Combined;
2078
2079   if (SDValue Combined = visitADDLike(N1, N0, N))
2080     return Combined;
2081
2082   return SDValue();
2083 }
2084
2085 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2086   bool Masked = false;
2087
2088   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2089   while (true) {
2090     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2091       V = V.getOperand(0);
2092       continue;
2093     }
2094
2095     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2096       Masked = true;
2097       V = V.getOperand(0);
2098       continue;
2099     }
2100
2101     break;
2102   }
2103
2104   // If this is not a carry, return.
2105   if (V.getResNo() != 1)
2106     return SDValue();
2107
2108   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2109       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2110     return SDValue();
2111
2112   // If the result is masked, then no matter what kind of bool it is we can
2113   // return. If it isn't, then we need to make sure the bool type is either 0 or
2114   // 1 and not other values.
2115   if (Masked ||
2116       TLI.getBooleanContents(V.getValueType()) ==
2117           TargetLoweringBase::ZeroOrOneBooleanContent)
2118     return V;
2119
2120   return SDValue();
2121 }
2122
2123 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2124   EVT VT = N0.getValueType();
2125   SDLoc DL(LocReference);
2126
2127   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2128   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2129       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2130     return DAG.getNode(ISD::SUB, DL, VT, N0,
2131                        DAG.getNode(ISD::SHL, DL, VT,
2132                                    N1.getOperand(0).getOperand(1),
2133                                    N1.getOperand(1)));
2134
2135   if (N1.getOpcode() == ISD::AND) {
2136     SDValue AndOp0 = N1.getOperand(0);
2137     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2138     unsigned DestBits = VT.getScalarSizeInBits();
2139
2140     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2141     // and similar xforms where the inner op is either ~0 or 0.
2142     if (NumSignBits == DestBits &&
2143         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2144       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2145   }
2146
2147   // add (sext i1), X -> sub X, (zext i1)
2148   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2149       N0.getOperand(0).getValueType() == MVT::i1 &&
2150       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2151     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2152     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2153   }
2154
2155   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2156   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2157     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2158     if (TN->getVT() == MVT::i1) {
2159       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2160                                  DAG.getConstant(1, DL, VT));
2161       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2162     }
2163   }
2164
2165   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2166   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2167       N1.getResNo() == 0)
2168     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2169                        N0, N1.getOperand(0), N1.getOperand(2));
2170
2171   // (add X, Carry) -> (addcarry X, 0, Carry)
2172   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2173     if (SDValue Carry = getAsCarry(TLI, N1))
2174       return DAG.getNode(ISD::ADDCARRY, DL,
2175                          DAG.getVTList(VT, Carry.getValueType()), N0,
2176                          DAG.getConstant(0, DL, VT), Carry);
2177
2178   return SDValue();
2179 }
2180
2181 SDValue DAGCombiner::visitADDC(SDNode *N) {
2182   SDValue N0 = N->getOperand(0);
2183   SDValue N1 = N->getOperand(1);
2184   EVT VT = N0.getValueType();
2185   SDLoc DL(N);
2186
2187   // If the flag result is dead, turn this into an ADD.
2188   if (!N->hasAnyUseOfValue(1))
2189     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2190                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2191
2192   // canonicalize constant to RHS.
2193   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2194   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2195   if (N0C && !N1C)
2196     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2197
2198   // fold (addc x, 0) -> x + no carry out
2199   if (isNullConstant(N1))
2200     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2201                                         DL, MVT::Glue));
2202
2203   // If it cannot overflow, transform into an add.
2204   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2205     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2206                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2207
2208   return SDValue();
2209 }
2210
2211 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2212   SDValue N0 = N->getOperand(0);
2213   SDValue N1 = N->getOperand(1);
2214   EVT VT = N0.getValueType();
2215   if (VT.isVector())
2216     return SDValue();
2217
2218   EVT CarryVT = N->getValueType(1);
2219   SDLoc DL(N);
2220
2221   // If the flag result is dead, turn this into an ADD.
2222   if (!N->hasAnyUseOfValue(1))
2223     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2224                      DAG.getUNDEF(CarryVT));
2225
2226   // canonicalize constant to RHS.
2227   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2228   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2229   if (N0C && !N1C)
2230     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2231
2232   // fold (uaddo x, 0) -> x + no carry out
2233   if (isNullConstant(N1))
2234     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2235
2236   // If it cannot overflow, transform into an add.
2237   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2238     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2239                      DAG.getConstant(0, DL, CarryVT));
2240
2241   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2242     return Combined;
2243
2244   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2245     return Combined;
2246
2247   return SDValue();
2248 }
2249
2250 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2251   auto VT = N0.getValueType();
2252
2253   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2254   // If Y + 1 cannot overflow.
2255   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2256     SDValue Y = N1.getOperand(0);
2257     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2258     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2259       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2260                          N1.getOperand(2));
2261   }
2262
2263   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2264   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2265     if (SDValue Carry = getAsCarry(TLI, N1))
2266       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2267                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2268
2269   return SDValue();
2270 }
2271
2272 SDValue DAGCombiner::visitADDE(SDNode *N) {
2273   SDValue N0 = N->getOperand(0);
2274   SDValue N1 = N->getOperand(1);
2275   SDValue CarryIn = N->getOperand(2);
2276
2277   // canonicalize constant to RHS
2278   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2280   if (N0C && !N1C)
2281     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2282                        N1, N0, CarryIn);
2283
2284   // fold (adde x, y, false) -> (addc x, y)
2285   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2286     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2287
2288   return SDValue();
2289 }
2290
2291 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2292   SDValue N0 = N->getOperand(0);
2293   SDValue N1 = N->getOperand(1);
2294   SDValue CarryIn = N->getOperand(2);
2295   SDLoc DL(N);
2296
2297   // canonicalize constant to RHS
2298   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2299   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2300   if (N0C && !N1C)
2301     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2302
2303   // fold (addcarry x, y, false) -> (uaddo x, y)
2304   if (isNullConstant(CarryIn))
2305     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2306
2307   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2308   if (isNullConstant(N0) && isNullConstant(N1)) {
2309     EVT VT = N0.getValueType();
2310     EVT CarryVT = CarryIn.getValueType();
2311     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2312     AddToWorklist(CarryExt.getNode());
2313     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2314                                     DAG.getConstant(1, DL, VT)),
2315                      DAG.getConstant(0, DL, CarryVT));
2316   }
2317
2318   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2319     return Combined;
2320
2321   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2322     return Combined;
2323
2324   return SDValue();
2325 }
2326
2327 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2328                                        SDNode *N) {
2329   // Iff the flag result is dead:
2330   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2331   if ((N0.getOpcode() == ISD::ADD ||
2332        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2333       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2334     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2335                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2336
2337   /**
2338    * When one of the addcarry argument is itself a carry, we may be facing
2339    * a diamond carry propagation. In which case we try to transform the DAG
2340    * to ensure linear carry propagation if that is possible.
2341    *
2342    * We are trying to get:
2343    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2344    */
2345   if (auto Y = getAsCarry(TLI, N1)) {
2346     /**
2347      *            (uaddo A, B)
2348      *             /       \
2349      *          Carry      Sum
2350      *            |          \
2351      *            | (addcarry *, 0, Z)
2352      *            |       /
2353      *             \   Carry
2354      *              |   /
2355      * (addcarry X, *, *)
2356      */
2357     if (Y.getOpcode() == ISD::UADDO &&
2358         CarryIn.getResNo() == 1 &&
2359         CarryIn.getOpcode() == ISD::ADDCARRY &&
2360         isNullConstant(CarryIn.getOperand(1)) &&
2361         CarryIn.getOperand(0) == Y.getValue(0)) {
2362       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2363                               Y.getOperand(0), Y.getOperand(1),
2364                               CarryIn.getOperand(2));
2365       AddToWorklist(NewY.getNode());
2366       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2367                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2368                          NewY.getValue(1));
2369     }
2370   }
2371
2372   return SDValue();
2373 }
2374
2375 // Since it may not be valid to emit a fold to zero for vector initializers
2376 // check if we can before folding.
2377 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2378                              SelectionDAG &DAG, bool LegalOperations,
2379                              bool LegalTypes) {
2380   if (!VT.isVector())
2381     return DAG.getConstant(0, DL, VT);
2382   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2383     return DAG.getConstant(0, DL, VT);
2384   return SDValue();
2385 }
2386
2387 SDValue DAGCombiner::visitSUB(SDNode *N) {
2388   SDValue N0 = N->getOperand(0);
2389   SDValue N1 = N->getOperand(1);
2390   EVT VT = N0.getValueType();
2391   SDLoc DL(N);
2392
2393   // fold vector ops
2394   if (VT.isVector()) {
2395     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2396       return FoldedVOp;
2397
2398     // fold (sub x, 0) -> x, vector edition
2399     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2400       return N0;
2401   }
2402
2403   // fold (sub x, x) -> 0
2404   // FIXME: Refactor this and xor and other similar operations together.
2405   if (N0 == N1)
2406     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2407   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2408       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2409     // fold (sub c1, c2) -> c1-c2
2410     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2411                                       N1.getNode());
2412   }
2413
2414   if (SDValue NewSel = foldBinOpIntoSelect(N))
2415     return NewSel;
2416
2417   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2418
2419   // fold (sub x, c) -> (add x, -c)
2420   if (N1C) {
2421     return DAG.getNode(ISD::ADD, DL, VT, N0,
2422                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2423   }
2424
2425   if (isNullConstantOrNullSplatConstant(N0)) {
2426     unsigned BitWidth = VT.getScalarSizeInBits();
2427     // Right-shifting everything out but the sign bit followed by negation is
2428     // the same as flipping arithmetic/logical shift type without the negation:
2429     // -(X >>u 31) -> (X >>s 31)
2430     // -(X >>s 31) -> (X >>u 31)
2431     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2432       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2433       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2434         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2435         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2436           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2437       }
2438     }
2439
2440     // 0 - X --> 0 if the sub is NUW.
2441     if (N->getFlags().hasNoUnsignedWrap())
2442       return N0;
2443
2444     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2445       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2446       // N1 must be 0 because negating the minimum signed value is undefined.
2447       if (N->getFlags().hasNoSignedWrap())
2448         return N0;
2449
2450       // 0 - X --> X if X is 0 or the minimum signed value.
2451       return N1;
2452     }
2453   }
2454
2455   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2456   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2457     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2458
2459   // fold A-(A-B) -> B
2460   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2461     return N1.getOperand(1);
2462
2463   // fold (A+B)-A -> B
2464   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2465     return N0.getOperand(1);
2466
2467   // fold (A+B)-B -> A
2468   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2469     return N0.getOperand(0);
2470
2471   // fold C2-(A+C1) -> (C2-C1)-A
2472   if (N1.getOpcode() == ISD::ADD) {
2473     SDValue N11 = N1.getOperand(1);
2474     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2475         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2476       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2477       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2478     }
2479   }
2480
2481   // fold ((A+(B+or-C))-B) -> A+or-C
2482   if (N0.getOpcode() == ISD::ADD &&
2483       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2484        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2485       N0.getOperand(1).getOperand(0) == N1)
2486     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2487                        N0.getOperand(1).getOperand(1));
2488
2489   // fold ((A+(C+B))-B) -> A+C
2490   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2491       N0.getOperand(1).getOperand(1) == N1)
2492     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2493                        N0.getOperand(1).getOperand(0));
2494
2495   // fold ((A-(B-C))-C) -> A-B
2496   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2497       N0.getOperand(1).getOperand(1) == N1)
2498     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2499                        N0.getOperand(1).getOperand(0));
2500
2501   // If either operand of a sub is undef, the result is undef
2502   if (N0.isUndef())
2503     return N0;
2504   if (N1.isUndef())
2505     return N1;
2506
2507   // If the relocation model supports it, consider symbol offsets.
2508   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2509     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2510       // fold (sub Sym, c) -> Sym-c
2511       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2512         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2513                                     GA->getOffset() -
2514                                         (uint64_t)N1C->getSExtValue());
2515       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2516       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2517         if (GA->getGlobal() == GB->getGlobal())
2518           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2519                                  DL, VT);
2520     }
2521
2522   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2523   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2524     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2525     if (TN->getVT() == MVT::i1) {
2526       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2527                                  DAG.getConstant(1, DL, VT));
2528       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2529     }
2530   }
2531
2532   return SDValue();
2533 }
2534
2535 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2536   SDValue N0 = N->getOperand(0);
2537   SDValue N1 = N->getOperand(1);
2538   EVT VT = N0.getValueType();
2539   SDLoc DL(N);
2540
2541   // If the flag result is dead, turn this into an SUB.
2542   if (!N->hasAnyUseOfValue(1))
2543     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2544                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2545
2546   // fold (subc x, x) -> 0 + no borrow
2547   if (N0 == N1)
2548     return CombineTo(N, DAG.getConstant(0, DL, VT),
2549                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2550
2551   // fold (subc x, 0) -> x + no borrow
2552   if (isNullConstant(N1))
2553     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2554
2555   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2556   if (isAllOnesConstant(N0))
2557     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2558                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2559
2560   return SDValue();
2561 }
2562
2563 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2564   SDValue N0 = N->getOperand(0);
2565   SDValue N1 = N->getOperand(1);
2566   EVT VT = N0.getValueType();
2567   if (VT.isVector())
2568     return SDValue();
2569
2570   EVT CarryVT = N->getValueType(1);
2571   SDLoc DL(N);
2572
2573   // If the flag result is dead, turn this into an SUB.
2574   if (!N->hasAnyUseOfValue(1))
2575     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2576                      DAG.getUNDEF(CarryVT));
2577
2578   // fold (usubo x, x) -> 0 + no borrow
2579   if (N0 == N1)
2580     return CombineTo(N, DAG.getConstant(0, DL, VT),
2581                      DAG.getConstant(0, DL, CarryVT));
2582
2583   // fold (usubo x, 0) -> x + no borrow
2584   if (isNullConstant(N1))
2585     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2586
2587   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2588   if (isAllOnesConstant(N0))
2589     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2590                      DAG.getConstant(0, DL, CarryVT));
2591
2592   return SDValue();
2593 }
2594
2595 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2596   SDValue N0 = N->getOperand(0);
2597   SDValue N1 = N->getOperand(1);
2598   SDValue CarryIn = N->getOperand(2);
2599
2600   // fold (sube x, y, false) -> (subc x, y)
2601   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2602     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2603
2604   return SDValue();
2605 }
2606
2607 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2608   SDValue N0 = N->getOperand(0);
2609   SDValue N1 = N->getOperand(1);
2610   SDValue CarryIn = N->getOperand(2);
2611
2612   // fold (subcarry x, y, false) -> (usubo x, y)
2613   if (isNullConstant(CarryIn))
2614     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2615
2616   return SDValue();
2617 }
2618
2619 SDValue DAGCombiner::visitMUL(SDNode *N) {
2620   SDValue N0 = N->getOperand(0);
2621   SDValue N1 = N->getOperand(1);
2622   EVT VT = N0.getValueType();
2623
2624   // fold (mul x, undef) -> 0
2625   if (N0.isUndef() || N1.isUndef())
2626     return DAG.getConstant(0, SDLoc(N), VT);
2627
2628   bool N0IsConst = false;
2629   bool N1IsConst = false;
2630   bool N1IsOpaqueConst = false;
2631   bool N0IsOpaqueConst = false;
2632   APInt ConstValue0, ConstValue1;
2633   // fold vector ops
2634   if (VT.isVector()) {
2635     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2636       return FoldedVOp;
2637
2638     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2639     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2640     assert((!N0IsConst ||
2641             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2642            "Splat APInt should be element width");
2643     assert((!N1IsConst ||
2644             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2645            "Splat APInt should be element width");
2646   } else {
2647     N0IsConst = isa<ConstantSDNode>(N0);
2648     if (N0IsConst) {
2649       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2650       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2651     }
2652     N1IsConst = isa<ConstantSDNode>(N1);
2653     if (N1IsConst) {
2654       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2655       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2656     }
2657   }
2658
2659   // fold (mul c1, c2) -> c1*c2
2660   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2661     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2662                                       N0.getNode(), N1.getNode());
2663
2664   // canonicalize constant to RHS (vector doesn't have to splat)
2665   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2666      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2667     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2668   // fold (mul x, 0) -> 0
2669   if (N1IsConst && ConstValue1.isNullValue())
2670     return N1;
2671   // fold (mul x, 1) -> x
2672   if (N1IsConst && ConstValue1.isOneValue())
2673     return N0;
2674
2675   if (SDValue NewSel = foldBinOpIntoSelect(N))
2676     return NewSel;
2677
2678   // fold (mul x, -1) -> 0-x
2679   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2680     SDLoc DL(N);
2681     return DAG.getNode(ISD::SUB, DL, VT,
2682                        DAG.getConstant(0, DL, VT), N0);
2683   }
2684   // fold (mul x, (1 << c)) -> x << c
2685   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2686       DAG.isKnownToBeAPowerOfTwo(N1) &&
2687       (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2688     SDLoc DL(N);
2689     SDValue LogBase2 = BuildLogBase2(N1, DL);
2690     AddToWorklist(LogBase2.getNode());
2691
2692     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2693     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2694     AddToWorklist(Trunc.getNode());
2695     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2696   }
2697   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2698   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2699     unsigned Log2Val = (-ConstValue1).logBase2();
2700     SDLoc DL(N);
2701     // FIXME: If the input is something that is easily negated (e.g. a
2702     // single-use add), we should put the negate there.
2703     return DAG.getNode(ISD::SUB, DL, VT,
2704                        DAG.getConstant(0, DL, VT),
2705                        DAG.getNode(ISD::SHL, DL, VT, N0,
2706                             DAG.getConstant(Log2Val, DL,
2707                                       getShiftAmountTy(N0.getValueType()))));
2708   }
2709
2710   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2711   if (N0.getOpcode() == ISD::SHL &&
2712       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2713       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2714     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2715     if (isConstantOrConstantVector(C3))
2716       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2717   }
2718
2719   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2720   // use.
2721   {
2722     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2723
2724     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2725     if (N0.getOpcode() == ISD::SHL &&
2726         isConstantOrConstantVector(N0.getOperand(1)) &&
2727         N0.getNode()->hasOneUse()) {
2728       Sh = N0; Y = N1;
2729     } else if (N1.getOpcode() == ISD::SHL &&
2730                isConstantOrConstantVector(N1.getOperand(1)) &&
2731                N1.getNode()->hasOneUse()) {
2732       Sh = N1; Y = N0;
2733     }
2734
2735     if (Sh.getNode()) {
2736       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2737       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2738     }
2739   }
2740
2741   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2742   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2743       N0.getOpcode() == ISD::ADD &&
2744       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2745       isMulAddWithConstProfitable(N, N0, N1))
2746       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2747                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2748                                      N0.getOperand(0), N1),
2749                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2750                                      N0.getOperand(1), N1));
2751
2752   // reassociate mul
2753   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2754     return RMUL;
2755
2756   return SDValue();
2757 }
2758
2759 /// Return true if divmod libcall is available.
2760 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2761                                      const TargetLowering &TLI) {
2762   RTLIB::Libcall LC;
2763   EVT NodeType = Node->getValueType(0);
2764   if (!NodeType.isSimple())
2765     return false;
2766   switch (NodeType.getSimpleVT().SimpleTy) {
2767   default: return false; // No libcall for vector types.
2768   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2769   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2770   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2771   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2772   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2773   }
2774
2775   return TLI.getLibcallName(LC) != nullptr;
2776 }
2777
2778 /// Issue divrem if both quotient and remainder are needed.
2779 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2780   if (Node->use_empty())
2781     return SDValue(); // This is a dead node, leave it alone.
2782
2783   unsigned Opcode = Node->getOpcode();
2784   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2785   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2786
2787   // DivMod lib calls can still work on non-legal types if using lib-calls.
2788   EVT VT = Node->getValueType(0);
2789   if (VT.isVector() || !VT.isInteger())
2790     return SDValue();
2791
2792   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2793     return SDValue();
2794
2795   // If DIVREM is going to get expanded into a libcall,
2796   // but there is no libcall available, then don't combine.
2797   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2798       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2799     return SDValue();
2800
2801   // If div is legal, it's better to do the normal expansion
2802   unsigned OtherOpcode = 0;
2803   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2804     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2805     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2806       return SDValue();
2807   } else {
2808     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2809     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2810       return SDValue();
2811   }
2812
2813   SDValue Op0 = Node->getOperand(0);
2814   SDValue Op1 = Node->getOperand(1);
2815   SDValue combined;
2816   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2817          UE = Op0.getNode()->use_end(); UI != UE;) {
2818     SDNode *User = *UI++;
2819     if (User == Node || User->use_empty())
2820       continue;
2821     // Convert the other matching node(s), too;
2822     // otherwise, the DIVREM may get target-legalized into something
2823     // target-specific that we won't be able to recognize.
2824     unsigned UserOpc = User->getOpcode();
2825     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2826         User->getOperand(0) == Op0 &&
2827         User->getOperand(1) == Op1) {
2828       if (!combined) {
2829         if (UserOpc == OtherOpcode) {
2830           SDVTList VTs = DAG.getVTList(VT, VT);
2831           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2832         } else if (UserOpc == DivRemOpc) {
2833           combined = SDValue(User, 0);
2834         } else {
2835           assert(UserOpc == Opcode);
2836           continue;
2837         }
2838       }
2839       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2840         CombineTo(User, combined);
2841       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2842         CombineTo(User, combined.getValue(1));
2843     }
2844   }
2845   return combined;
2846 }
2847
2848 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2849   SDValue N0 = N->getOperand(0);
2850   SDValue N1 = N->getOperand(1);
2851   EVT VT = N->getValueType(0);
2852   SDLoc DL(N);
2853
2854   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2855     return DAG.getUNDEF(VT);
2856
2857   // undef / X -> 0
2858   // undef % X -> 0
2859   if (N0.isUndef())
2860     return DAG.getConstant(0, DL, VT);
2861
2862   return SDValue();
2863 }
2864
2865 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2866   SDValue N0 = N->getOperand(0);
2867   SDValue N1 = N->getOperand(1);
2868   EVT VT = N->getValueType(0);
2869
2870   // fold vector ops
2871   if (VT.isVector())
2872     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2873       return FoldedVOp;
2874
2875   SDLoc DL(N);
2876
2877   // fold (sdiv c1, c2) -> c1/c2
2878   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2879   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2880   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2881     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2882   // fold (sdiv X, 1) -> X
2883   if (N1C && N1C->isOne())
2884     return N0;
2885   // fold (sdiv X, -1) -> 0-X
2886   if (N1C && N1C->isAllOnesValue())
2887     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2888
2889   if (SDValue V = simplifyDivRem(N, DAG))
2890     return V;
2891
2892   if (SDValue NewSel = foldBinOpIntoSelect(N))
2893     return NewSel;
2894
2895   // If we know the sign bits of both operands are zero, strength reduce to a
2896   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2897   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2898     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2899
2900   // fold (sdiv X, pow2) -> simple ops after legalize
2901   // FIXME: We check for the exact bit here because the generic lowering gives
2902   // better results in that case. The target-specific lowering should learn how
2903   // to handle exact sdivs efficiently.
2904   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2905       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2906                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2907     // Target-specific implementation of sdiv x, pow2.
2908     if (SDValue Res = BuildSDIVPow2(N))
2909       return Res;
2910
2911     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2912
2913     // Splat the sign bit into the register
2914     SDValue SGN =
2915         DAG.getNode(ISD::SRA, DL, VT, N0,
2916                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2917                                     getShiftAmountTy(N0.getValueType())));
2918     AddToWorklist(SGN.getNode());
2919
2920     // Add (N0 < 0) ? abs2 - 1 : 0;
2921     SDValue SRL =
2922         DAG.getNode(ISD::SRL, DL, VT, SGN,
2923                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2924                                     getShiftAmountTy(SGN.getValueType())));
2925     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2926     AddToWorklist(SRL.getNode());
2927     AddToWorklist(ADD.getNode());    // Divide by pow2
2928     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2929                   DAG.getConstant(lg2, DL,
2930                                   getShiftAmountTy(ADD.getValueType())));
2931
2932     // If we're dividing by a positive value, we're done.  Otherwise, we must
2933     // negate the result.
2934     if (N1C->getAPIntValue().isNonNegative())
2935       return SRA;
2936
2937     AddToWorklist(SRA.getNode());
2938     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2939   }
2940
2941   // If integer divide is expensive and we satisfy the requirements, emit an
2942   // alternate sequence.  Targets may check function attributes for size/speed
2943   // trade-offs.
2944   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
2945   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2946     if (SDValue Op = BuildSDIV(N))
2947       return Op;
2948
2949   // sdiv, srem -> sdivrem
2950   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2951   // true.  Otherwise, we break the simplification logic in visitREM().
2952   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2953     if (SDValue DivRem = useDivRem(N))
2954         return DivRem;
2955
2956   return SDValue();
2957 }
2958
2959 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2960   SDValue N0 = N->getOperand(0);
2961   SDValue N1 = N->getOperand(1);
2962   EVT VT = N->getValueType(0);
2963
2964   // fold vector ops
2965   if (VT.isVector())
2966     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2967       return FoldedVOp;
2968
2969   SDLoc DL(N);
2970
2971   // fold (udiv c1, c2) -> c1/c2
2972   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2973   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2974   if (N0C && N1C)
2975     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2976                                                     N0C, N1C))
2977       return Folded;
2978
2979   if (SDValue V = simplifyDivRem(N, DAG))
2980     return V;
2981
2982   if (SDValue NewSel = foldBinOpIntoSelect(N))
2983     return NewSel;
2984
2985   // fold (udiv x, (1 << c)) -> x >>u c
2986   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2987       DAG.isKnownToBeAPowerOfTwo(N1)) {
2988     SDValue LogBase2 = BuildLogBase2(N1, DL);
2989     AddToWorklist(LogBase2.getNode());
2990
2991     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2992     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2993     AddToWorklist(Trunc.getNode());
2994     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2995   }
2996
2997   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2998   if (N1.getOpcode() == ISD::SHL) {
2999     SDValue N10 = N1.getOperand(0);
3000     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3001         DAG.isKnownToBeAPowerOfTwo(N10)) {
3002       SDValue LogBase2 = BuildLogBase2(N10, DL);
3003       AddToWorklist(LogBase2.getNode());
3004
3005       EVT ADDVT = N1.getOperand(1).getValueType();
3006       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3007       AddToWorklist(Trunc.getNode());
3008       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3009       AddToWorklist(Add.getNode());
3010       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3011     }
3012   }
3013
3014   // fold (udiv x, c) -> alternate
3015   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3016   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3017     if (SDValue Op = BuildUDIV(N))
3018       return Op;
3019
3020   // sdiv, srem -> sdivrem
3021   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3022   // true.  Otherwise, we break the simplification logic in visitREM().
3023   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3024     if (SDValue DivRem = useDivRem(N))
3025         return DivRem;
3026
3027   return SDValue();
3028 }
3029
3030 // handles ISD::SREM and ISD::UREM
3031 SDValue DAGCombiner::visitREM(SDNode *N) {
3032   unsigned Opcode = N->getOpcode();
3033   SDValue N0 = N->getOperand(0);
3034   SDValue N1 = N->getOperand(1);
3035   EVT VT = N->getValueType(0);
3036   bool isSigned = (Opcode == ISD::SREM);
3037   SDLoc DL(N);
3038
3039   // fold (rem c1, c2) -> c1%c2
3040   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3041   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3042   if (N0C && N1C)
3043     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3044       return Folded;
3045
3046   if (SDValue V = simplifyDivRem(N, DAG))
3047     return V;
3048
3049   if (SDValue NewSel = foldBinOpIntoSelect(N))
3050     return NewSel;
3051
3052   if (isSigned) {
3053     // If we know the sign bits of both operands are zero, strength reduce to a
3054     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3055     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3056       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3057   } else {
3058     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3059     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3060       // fold (urem x, pow2) -> (and x, pow2-1)
3061       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3062       AddToWorklist(Add.getNode());
3063       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3064     }
3065     if (N1.getOpcode() == ISD::SHL &&
3066         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3067       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3068       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3069       AddToWorklist(Add.getNode());
3070       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3071     }
3072   }
3073
3074   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3075
3076   // If X/C can be simplified by the division-by-constant logic, lower
3077   // X%C to the equivalent of X-X/C*C.
3078   // To avoid mangling nodes, this simplification requires that the combine()
3079   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3080   // against this by skipping the simplification if isIntDivCheap().  When
3081   // div is not cheap, combine will not return a DIVREM.  Regardless,
3082   // checking cheapness here makes sense since the simplification results in
3083   // fatter code.
3084   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3085     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3086     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3087     AddToWorklist(Div.getNode());
3088     SDValue OptimizedDiv = combine(Div.getNode());
3089     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3090       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
3091              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
3092       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3093       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3094       AddToWorklist(Mul.getNode());
3095       return Sub;
3096     }
3097   }
3098
3099   // sdiv, srem -> sdivrem
3100   if (SDValue DivRem = useDivRem(N))
3101     return DivRem.getValue(1);
3102
3103   return SDValue();
3104 }
3105
3106 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3107   SDValue N0 = N->getOperand(0);
3108   SDValue N1 = N->getOperand(1);
3109   EVT VT = N->getValueType(0);
3110   SDLoc DL(N);
3111
3112   if (VT.isVector()) {
3113     // fold (mulhs x, 0) -> 0
3114     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3115       return N1;
3116     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3117       return N0;
3118   }
3119
3120   // fold (mulhs x, 0) -> 0
3121   if (isNullConstant(N1))
3122     return N1;
3123   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3124   if (isOneConstant(N1))
3125     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3126                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3127                                        getShiftAmountTy(N0.getValueType())));
3128
3129   // fold (mulhs x, undef) -> 0
3130   if (N0.isUndef() || N1.isUndef())
3131     return DAG.getConstant(0, DL, VT);
3132
3133   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3134   // plus a shift.
3135   if (VT.isSimple() && !VT.isVector()) {
3136     MVT Simple = VT.getSimpleVT();
3137     unsigned SimpleSize = Simple.getSizeInBits();
3138     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3139     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3140       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3141       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3142       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3143       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3144             DAG.getConstant(SimpleSize, DL,
3145                             getShiftAmountTy(N1.getValueType())));
3146       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3147     }
3148   }
3149
3150   return SDValue();
3151 }
3152
3153 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3154   SDValue N0 = N->getOperand(0);
3155   SDValue N1 = N->getOperand(1);
3156   EVT VT = N->getValueType(0);
3157   SDLoc DL(N);
3158
3159   if (VT.isVector()) {
3160     // fold (mulhu x, 0) -> 0
3161     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3162       return N1;
3163     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3164       return N0;
3165   }
3166
3167   // fold (mulhu x, 0) -> 0
3168   if (isNullConstant(N1))
3169     return N1;
3170   // fold (mulhu x, 1) -> 0
3171   if (isOneConstant(N1))
3172     return DAG.getConstant(0, DL, N0.getValueType());
3173   // fold (mulhu x, undef) -> 0
3174   if (N0.isUndef() || N1.isUndef())
3175     return DAG.getConstant(0, DL, VT);
3176
3177   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3178   // plus a shift.
3179   if (VT.isSimple() && !VT.isVector()) {
3180     MVT Simple = VT.getSimpleVT();
3181     unsigned SimpleSize = Simple.getSizeInBits();
3182     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3183     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3184       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3185       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3186       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3187       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3188             DAG.getConstant(SimpleSize, DL,
3189                             getShiftAmountTy(N1.getValueType())));
3190       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3191     }
3192   }
3193
3194   return SDValue();
3195 }
3196
3197 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3198 /// give the opcodes for the two computations that are being performed. Return
3199 /// true if a simplification was made.
3200 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3201                                                 unsigned HiOp) {
3202   // If the high half is not needed, just compute the low half.
3203   bool HiExists = N->hasAnyUseOfValue(1);
3204   if (!HiExists &&
3205       (!LegalOperations ||
3206        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3207     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3208     return CombineTo(N, Res, Res);
3209   }
3210
3211   // If the low half is not needed, just compute the high half.
3212   bool LoExists = N->hasAnyUseOfValue(0);
3213   if (!LoExists &&
3214       (!LegalOperations ||
3215        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3216     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3217     return CombineTo(N, Res, Res);
3218   }
3219
3220   // If both halves are used, return as it is.
3221   if (LoExists && HiExists)
3222     return SDValue();
3223
3224   // If the two computed results can be simplified separately, separate them.
3225   if (LoExists) {
3226     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3227     AddToWorklist(Lo.getNode());
3228     SDValue LoOpt = combine(Lo.getNode());
3229     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3230         (!LegalOperations ||
3231          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3232       return CombineTo(N, LoOpt, LoOpt);
3233   }
3234
3235   if (HiExists) {
3236     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3237     AddToWorklist(Hi.getNode());
3238     SDValue HiOpt = combine(Hi.getNode());
3239     if (HiOpt.getNode() && HiOpt != Hi &&
3240         (!LegalOperations ||
3241          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3242       return CombineTo(N, HiOpt, HiOpt);
3243   }
3244
3245   return SDValue();
3246 }
3247
3248 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3249   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3250     return Res;
3251
3252   EVT VT = N->getValueType(0);
3253   SDLoc DL(N);
3254
3255   // If the type is twice as wide is legal, transform the mulhu to a wider
3256   // multiply plus a shift.
3257   if (VT.isSimple() && !VT.isVector()) {
3258     MVT Simple = VT.getSimpleVT();
3259     unsigned SimpleSize = Simple.getSizeInBits();
3260     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3261     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3262       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3263       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3264       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3265       // Compute the high part as N1.
3266       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3267             DAG.getConstant(SimpleSize, DL,
3268                             getShiftAmountTy(Lo.getValueType())));
3269       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3270       // Compute the low part as N0.
3271       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3272       return CombineTo(N, Lo, Hi);
3273     }
3274   }
3275
3276   return SDValue();
3277 }
3278
3279 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3280   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3281     return Res;
3282
3283   EVT VT = N->getValueType(0);
3284   SDLoc DL(N);
3285
3286   // If the type is twice as wide is legal, transform the mulhu to a wider
3287   // multiply plus a shift.
3288   if (VT.isSimple() && !VT.isVector()) {
3289     MVT Simple = VT.getSimpleVT();
3290     unsigned SimpleSize = Simple.getSizeInBits();
3291     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3292     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3293       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3294       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3295       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3296       // Compute the high part as N1.
3297       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3298             DAG.getConstant(SimpleSize, DL,
3299                             getShiftAmountTy(Lo.getValueType())));
3300       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3301       // Compute the low part as N0.
3302       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3303       return CombineTo(N, Lo, Hi);
3304     }
3305   }
3306
3307   return SDValue();
3308 }
3309
3310 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3311   // (smulo x, 2) -> (saddo x, x)
3312   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3313     if (C2->getAPIntValue() == 2)
3314       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3315                          N->getOperand(0), N->getOperand(0));
3316
3317   return SDValue();
3318 }
3319
3320 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3321   // (umulo x, 2) -> (uaddo x, x)
3322   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3323     if (C2->getAPIntValue() == 2)
3324       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3325                          N->getOperand(0), N->getOperand(0));
3326
3327   return SDValue();
3328 }
3329
3330 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3331   SDValue N0 = N->getOperand(0);
3332   SDValue N1 = N->getOperand(1);
3333   EVT VT = N0.getValueType();
3334
3335   // fold vector ops
3336   if (VT.isVector())
3337     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3338       return FoldedVOp;
3339
3340   // fold operation with constant operands.
3341   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3342   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3343   if (N0C && N1C)
3344     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3345
3346   // canonicalize constant to RHS
3347   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3348      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3349     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3350
3351   return SDValue();
3352 }
3353
3354 /// If this is a binary operator with two operands of the same opcode, try to
3355 /// simplify it.
3356 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3357   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3358   EVT VT = N0.getValueType();
3359   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3360
3361   // Bail early if none of these transforms apply.
3362   if (N0.getNumOperands() == 0) return SDValue();
3363
3364   // For each of OP in AND/OR/XOR:
3365   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3366   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3367   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3368   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3369   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3370   //
3371   // do not sink logical op inside of a vector extend, since it may combine
3372   // into a vsetcc.
3373   EVT Op0VT = N0.getOperand(0).getValueType();
3374   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3375        N0.getOpcode() == ISD::SIGN_EXTEND ||
3376        N0.getOpcode() == ISD::BSWAP ||
3377        // Avoid infinite looping with PromoteIntBinOp.
3378        (N0.getOpcode() == ISD::ANY_EXTEND &&
3379         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3380        (N0.getOpcode() == ISD::TRUNCATE &&
3381         (!TLI.isZExtFree(VT, Op0VT) ||
3382          !TLI.isTruncateFree(Op0VT, VT)) &&
3383         TLI.isTypeLegal(Op0VT))) &&
3384       !VT.isVector() &&
3385       Op0VT == N1.getOperand(0).getValueType() &&
3386       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3387     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3388                                  N0.getOperand(0).getValueType(),
3389                                  N0.getOperand(0), N1.getOperand(0));
3390     AddToWorklist(ORNode.getNode());
3391     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3392   }
3393
3394   // For each of OP in SHL/SRL/SRA/AND...
3395   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3396   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3397   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3398   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3399        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3400       N0.getOperand(1) == N1.getOperand(1)) {
3401     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3402                                  N0.getOperand(0).getValueType(),
3403                                  N0.getOperand(0), N1.getOperand(0));
3404     AddToWorklist(ORNode.getNode());
3405     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3406                        ORNode, N0.getOperand(1));
3407   }
3408
3409   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3410   // Only perform this optimization up until type legalization, before
3411   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3412   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3413   // we don't want to undo this promotion.
3414   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3415   // on scalars.
3416   if ((N0.getOpcode() == ISD::BITCAST ||
3417        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3418        Level <= AfterLegalizeTypes) {
3419     SDValue In0 = N0.getOperand(0);
3420     SDValue In1 = N1.getOperand(0);
3421     EVT In0Ty = In0.getValueType();
3422     EVT In1Ty = In1.getValueType();
3423     SDLoc DL(N);
3424     // If both incoming values are integers, and the original types are the
3425     // same.
3426     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3427       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3428       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3429       AddToWorklist(Op.getNode());
3430       return BC;
3431     }
3432   }
3433
3434   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3435   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3436   // If both shuffles use the same mask, and both shuffle within a single
3437   // vector, then it is worthwhile to move the swizzle after the operation.
3438   // The type-legalizer generates this pattern when loading illegal
3439   // vector types from memory. In many cases this allows additional shuffle
3440   // optimizations.
3441   // There are other cases where moving the shuffle after the xor/and/or
3442   // is profitable even if shuffles don't perform a swizzle.
3443   // If both shuffles use the same mask, and both shuffles have the same first
3444   // or second operand, then it might still be profitable to move the shuffle
3445   // after the xor/and/or operation.
3446   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3447     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3448     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3449
3450     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3451            "Inputs to shuffles are not the same type");
3452
3453     // Check that both shuffles use the same mask. The masks are known to be of
3454     // the same length because the result vector type is the same.
3455     // Check also that shuffles have only one use to avoid introducing extra
3456     // instructions.
3457     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3458         SVN0->getMask().equals(SVN1->getMask())) {
3459       SDValue ShOp = N0->getOperand(1);
3460
3461       // Don't try to fold this node if it requires introducing a
3462       // build vector of all zeros that might be illegal at this stage.
3463       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3464         if (!LegalTypes)
3465           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3466         else
3467           ShOp = SDValue();
3468       }
3469
3470       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3471       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3472       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3473       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3474         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3475                                       N0->getOperand(0), N1->getOperand(0));
3476         AddToWorklist(NewNode.getNode());
3477         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3478                                     SVN0->getMask());
3479       }
3480
3481       // Don't try to fold this node if it requires introducing a
3482       // build vector of all zeros that might be illegal at this stage.
3483       ShOp = N0->getOperand(0);
3484       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3485         if (!LegalTypes)
3486           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3487         else
3488           ShOp = SDValue();
3489       }
3490
3491       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3492       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3493       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3494       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3495         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3496                                       N0->getOperand(1), N1->getOperand(1));
3497         AddToWorklist(NewNode.getNode());
3498         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3499                                     SVN0->getMask());
3500       }
3501     }
3502   }
3503
3504   return SDValue();
3505 }
3506
3507 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3508 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3509                                        const SDLoc &DL) {
3510   SDValue LL, LR, RL, RR, N0CC, N1CC;
3511   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3512       !isSetCCEquivalent(N1, RL, RR, N1CC))
3513     return SDValue();
3514
3515   assert(N0.getValueType() == N1.getValueType() &&
3516          "Unexpected operand types for bitwise logic op");
3517   assert(LL.getValueType() == LR.getValueType() &&
3518          RL.getValueType() == RR.getValueType() &&
3519          "Unexpected operand types for setcc");
3520
3521   // If we're here post-legalization or the logic op type is not i1, the logic
3522   // op type must match a setcc result type. Also, all folds require new
3523   // operations on the left and right operands, so those types must match.
3524   EVT VT = N0.getValueType();
3525   EVT OpVT = LL.getValueType();
3526   if (LegalOperations || VT != MVT::i1)
3527     if (VT != getSetCCResultType(OpVT))
3528       return SDValue();
3529   if (OpVT != RL.getValueType())
3530     return SDValue();
3531
3532   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3533   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3534   bool IsInteger = OpVT.isInteger();
3535   if (LR == RR && CC0 == CC1 && IsInteger) {
3536     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3537     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3538
3539     // All bits clear?
3540     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3541     // All sign bits clear?
3542     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3543     // Any bits set?
3544     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3545     // Any sign bits set?
3546     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3547
3548     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3549     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3550     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3551     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3552     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3553       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3554       AddToWorklist(Or.getNode());
3555       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3556     }
3557
3558     // All bits set?
3559     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3560     // All sign bits set?
3561     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3562     // Any bits clear?
3563     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3564     // Any sign bits clear?
3565     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3566
3567     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3568     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3569     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3570     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3571     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3572       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3573       AddToWorklist(And.getNode());
3574       return DAG.getSetCC(DL, VT, And, LR, CC1);
3575     }
3576   }
3577
3578   // TODO: What is the 'or' equivalent of this fold?
3579   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3580   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3581       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3582        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3583     SDValue One = DAG.getConstant(1, DL, OpVT);
3584     SDValue Two = DAG.getConstant(2, DL, OpVT);
3585     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3586     AddToWorklist(Add.getNode());
3587     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3588   }
3589
3590   // Try more general transforms if the predicates match and the only user of
3591   // the compares is the 'and' or 'or'.
3592   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3593       N0.hasOneUse() && N1.hasOneUse()) {
3594     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3595     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3596     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3597       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3598       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3599       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3600       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3601       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3602     }
3603   }
3604
3605   // Canonicalize equivalent operands to LL == RL.
3606   if (LL == RR && LR == RL) {
3607     CC1 = ISD::getSetCCSwappedOperands(CC1);
3608     std::swap(RL, RR);
3609   }
3610
3611   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3612   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3613   if (LL == RL && LR == RR) {
3614     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3615                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3616     if (NewCC != ISD::SETCC_INVALID &&
3617         (!LegalOperations ||
3618          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3619           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3620       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3621   }
3622
3623   return SDValue();
3624 }
3625
3626 /// This contains all DAGCombine rules which reduce two values combined by
3627 /// an And operation to a single value. This makes them reusable in the context
3628 /// of visitSELECT(). Rules involving constants are not included as
3629 /// visitSELECT() already handles those cases.
3630 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3631   EVT VT = N1.getValueType();
3632   SDLoc DL(N);
3633
3634   // fold (and x, undef) -> 0
3635   if (N0.isUndef() || N1.isUndef())
3636     return DAG.getConstant(0, DL, VT);
3637
3638   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3639     return V;
3640
3641   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3642       VT.getSizeInBits() <= 64) {
3643     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3644       APInt ADDC = ADDI->getAPIntValue();
3645       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3646         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3647         // immediate for an add, but it is legal if its top c2 bits are set,
3648         // transform the ADD so the immediate doesn't need to be materialized
3649         // in a register.
3650         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3651           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3652                                              SRLI->getZExtValue());
3653           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3654             ADDC |= Mask;
3655             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3656               SDLoc DL0(N0);
3657               SDValue NewAdd =
3658                 DAG.getNode(ISD::ADD, DL0, VT,
3659                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3660               CombineTo(N0.getNode(), NewAdd);
3661               // Return N so it doesn't get rechecked!
3662               return SDValue(N, 0);
3663             }
3664           }
3665         }
3666       }
3667     }
3668   }
3669
3670   // Reduce bit extract of low half of an integer to the narrower type.
3671   // (and (srl i64:x, K), KMask) ->
3672   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3673   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3674     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3675       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3676         unsigned Size = VT.getSizeInBits();
3677         const APInt &AndMask = CAnd->getAPIntValue();
3678         unsigned ShiftBits = CShift->getZExtValue();
3679
3680         // Bail out, this node will probably disappear anyway.
3681         if (ShiftBits == 0)
3682           return SDValue();
3683
3684         unsigned MaskBits = AndMask.countTrailingOnes();
3685         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3686
3687         if (AndMask.isMask() &&
3688             // Required bits must not span the two halves of the integer and
3689             // must fit in the half size type.
3690             (ShiftBits + MaskBits <= Size / 2) &&
3691             TLI.isNarrowingProfitable(VT, HalfVT) &&
3692             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3693             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3694             TLI.isTruncateFree(VT, HalfVT) &&
3695             TLI.isZExtFree(HalfVT, VT)) {
3696           // The isNarrowingProfitable is to avoid regressions on PPC and
3697           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3698           // on downstream users of this. Those patterns could probably be
3699           // extended to handle extensions mixed in.
3700
3701           SDValue SL(N0);
3702           assert(MaskBits <= Size);
3703
3704           // Extracting the highest bit of the low half.
3705           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3706           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3707                                       N0.getOperand(0));
3708
3709           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3710           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3711           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3712           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3713           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3714         }
3715       }
3716     }
3717   }
3718
3719   return SDValue();
3720 }
3721
3722 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3723                                    EVT LoadResultTy, EVT &ExtVT) {
3724   if (!AndC->getAPIntValue().isMask())
3725     return false;
3726
3727   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3728
3729   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3730   EVT LoadedVT = LoadN->getMemoryVT();
3731
3732   if (ExtVT == LoadedVT &&
3733       (!LegalOperations ||
3734        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3735     // ZEXTLOAD will match without needing to change the size of the value being
3736     // loaded.
3737     return true;
3738   }
3739
3740   // Do not change the width of a volatile load.
3741   if (LoadN->isVolatile())
3742     return false;
3743
3744   // Do not generate loads of non-round integer types since these can
3745   // be expensive (and would be wrong if the type is not byte sized).
3746   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3747     return false;
3748
3749   if (LegalOperations &&
3750       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3751     return false;
3752
3753   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3754     return false;
3755
3756   return true;
3757 }
3758
3759 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
3760                                     EVT &ExtVT, unsigned ShAmt) {
3761   // Don't transform one with multiple uses, this would require adding a new
3762   // load.
3763   if (!SDValue(LoadN, 0).hasOneUse())
3764     return false;
3765
3766   if (LegalOperations &&
3767       !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT))
3768     return false;
3769
3770   // Do not generate loads of non-round integer types since these can
3771   // be expensive (and would be wrong if the type is not byte sized).
3772   if (!ExtVT.isRound())
3773     return false;
3774
3775   // Don't change the width of a volatile load.
3776   if (LoadN->isVolatile())
3777     return false;
3778
3779   // Verify that we are actually reducing a load width here.
3780   if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits())
3781     return false;
3782
3783   // For the transform to be legal, the load must produce only two values
3784   // (the value loaded and the chain).  Don't transform a pre-increment
3785   // load, for example, which produces an extra value.  Otherwise the
3786   // transformation is not equivalent, and the downstream logic to replace
3787   // uses gets things wrong.
3788   if (LoadN->getNumValues() > 2)
3789     return false;
3790
3791   // If the load that we're shrinking is an extload and we're not just
3792   // discarding the extension we can't simply shrink the load. Bail.
3793   // TODO: It would be possible to merge the extensions in some cases.
3794   if (LoadN->getExtensionType() != ISD::NON_EXTLOAD &&
3795       LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
3796     return false;
3797
3798   if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT))
3799     return false;
3800
3801   // It's not possible to generate a constant of extended or untyped type.
3802   EVT PtrType = LoadN->getOperand(1).getValueType();
3803   if (PtrType == MVT::Untyped || PtrType.isExtended())
3804     return false;
3805
3806   return true;
3807 }
3808
3809 bool DAGCombiner::SearchForAndLoads(SDNode *N,
3810                                     SmallPtrSetImpl<LoadSDNode*> &Loads,
3811                                     SmallPtrSetImpl<SDNode*> &NodesWithConsts,
3812                                     ConstantSDNode *Mask,
3813                                     SDNode *&NodeToMask) {
3814   // Recursively search for the operands, looking for loads which can be
3815   // narrowed.
3816   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
3817     SDValue Op = N->getOperand(i);
3818
3819     if (Op.getValueType().isVector())
3820       return false;
3821
3822     // Some constants may need fixing up later if they are too large.
3823     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3824       if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
3825           (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
3826         NodesWithConsts.insert(N);
3827       continue;
3828     }
3829
3830     if (!Op.hasOneUse())
3831       return false;
3832
3833     switch(Op.getOpcode()) {
3834     case ISD::LOAD: {
3835       auto *Load = cast<LoadSDNode>(Op);
3836       EVT ExtVT;
3837       if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
3838           isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) {
3839         // Only add this load if we can make it more narrow.
3840         if (ExtVT.bitsLT(Load->getMemoryVT()))
3841           Loads.insert(Load);
3842         continue;
3843       }
3844       return false;
3845     }
3846     case ISD::ZERO_EXTEND:
3847     case ISD::ANY_EXTEND:
3848     case ISD::AssertZext: {
3849       unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
3850       EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3851       EVT VT = Op.getOpcode() == ISD::AssertZext ?
3852         cast<VTSDNode>(Op.getOperand(1))->getVT() :
3853         Op.getOperand(0).getValueType();
3854
3855       // We can accept extending nodes if the mask is wider or an equal
3856       // width to the original type.
3857       if (ExtVT.bitsGE(VT))
3858         continue;
3859       break;
3860     }
3861     case ISD::OR:
3862     case ISD::XOR:
3863     case ISD::AND:
3864       if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
3865                              NodeToMask))
3866         return false;
3867       continue;
3868     }
3869
3870     // Allow one node which will masked along with any loads found.
3871     if (NodeToMask)
3872       return false;
3873     NodeToMask = Op.getNode();
3874   }
3875   return true;
3876 }
3877
3878 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
3879   auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
3880   if (!Mask)
3881     return false;
3882
3883   if (!Mask->getAPIntValue().isMask())
3884     return false;
3885
3886   // No need to do anything if the and directly uses a load.
3887   if (isa<LoadSDNode>(N->getOperand(0)))
3888     return false;
3889
3890   SmallPtrSet<LoadSDNode*, 8> Loads;
3891   SmallPtrSet<SDNode*, 2> NodesWithConsts;
3892   SDNode *FixupNode = nullptr;
3893   if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
3894     if (Loads.size() == 0)
3895       return false;
3896
3897     SDValue MaskOp = N->getOperand(1);
3898
3899     // If it exists, fixup the single node we allow in the tree that needs
3900     // masking.
3901     if (FixupNode) {
3902       SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
3903                                 FixupNode->getValueType(0),
3904                                 SDValue(FixupNode, 0), MaskOp);
3905       DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
3906       DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
3907                              MaskOp);
3908     }
3909
3910     // Narrow any constants that need it.
3911     for (auto *LogicN : NodesWithConsts) {
3912       auto *C = cast<ConstantSDNode>(LogicN->getOperand(1));
3913       SDValue And = DAG.getNode(ISD::AND, SDLoc(C), C->getValueType(0),
3914                                 SDValue(C, 0), MaskOp);
3915       DAG.UpdateNodeOperands(LogicN, LogicN->getOperand(0), And);
3916     }
3917
3918     // Create narrow loads.
3919     for (auto *Load : Loads) {
3920       SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
3921                                 SDValue(Load, 0), MaskOp);
3922       DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
3923       DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
3924       SDValue NewLoad = ReduceLoadWidth(And.getNode());
3925       assert(NewLoad &&
3926              "Shouldn't be masking the load if it can't be narrowed");
3927       CombineTo(Load, NewLoad, NewLoad.getValue(1));
3928     }
3929     DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
3930     return true;
3931   }
3932   return false;
3933 }
3934
3935 SDValue DAGCombiner::visitAND(SDNode *N) {
3936   SDValue N0 = N->getOperand(0);
3937   SDValue N1 = N->getOperand(1);
3938   EVT VT = N1.getValueType();
3939
3940   // x & x --> x
3941   if (N0 == N1)
3942     return N0;
3943
3944   // fold vector ops
3945   if (VT.isVector()) {
3946     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3947       return FoldedVOp;
3948
3949     // fold (and x, 0) -> 0, vector edition
3950     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3951       // do not return N0, because undef node may exist in N0
3952       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3953                              SDLoc(N), N0.getValueType());
3954     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3955       // do not return N1, because undef node may exist in N1
3956       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3957                              SDLoc(N), N1.getValueType());
3958
3959     // fold (and x, -1) -> x, vector edition
3960     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3961       return N1;
3962     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3963       return N0;
3964   }
3965
3966   // fold (and c1, c2) -> c1&c2
3967   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3968   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3969   if (N0C && N1C && !N1C->isOpaque())
3970     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3971   // canonicalize constant to RHS
3972   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3973      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3974     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3975   // fold (and x, -1) -> x
3976   if (isAllOnesConstant(N1))
3977     return N0;
3978   // if (and x, c) is known to be zero, return 0
3979   unsigned BitWidth = VT.getScalarSizeInBits();
3980   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3981                                    APInt::getAllOnesValue(BitWidth)))
3982     return DAG.getConstant(0, SDLoc(N), VT);
3983
3984   if (SDValue NewSel = foldBinOpIntoSelect(N))
3985     return NewSel;
3986
3987   // reassociate and
3988   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3989     return RAND;
3990   // fold (and (or x, C), D) -> D if (C & D) == D
3991   if (N1C && N0.getOpcode() == ISD::OR)
3992     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3993       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3994         return N1;
3995   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3996   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3997     SDValue N0Op0 = N0.getOperand(0);
3998     APInt Mask = ~N1C->getAPIntValue();
3999     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4000     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4001       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4002                                  N0.getValueType(), N0Op0);
4003
4004       // Replace uses of the AND with uses of the Zero extend node.
4005       CombineTo(N, Zext);
4006
4007       // We actually want to replace all uses of the any_extend with the
4008       // zero_extend, to avoid duplicating things.  This will later cause this
4009       // AND to be folded.
4010       CombineTo(N0.getNode(), Zext);
4011       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4012     }
4013   }
4014   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4015   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4016   // already be zero by virtue of the width of the base type of the load.
4017   //
4018   // the 'X' node here can either be nothing or an extract_vector_elt to catch
4019   // more cases.
4020   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4021        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4022        N0.getOperand(0).getOpcode() == ISD::LOAD &&
4023        N0.getOperand(0).getResNo() == 0) ||
4024       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4025     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4026                                          N0 : N0.getOperand(0) );
4027
4028     // Get the constant (if applicable) the zero'th operand is being ANDed with.
4029     // This can be a pure constant or a vector splat, in which case we treat the
4030     // vector as a scalar and use the splat value.
4031     APInt Constant = APInt::getNullValue(1);
4032     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4033       Constant = C->getAPIntValue();
4034     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4035       APInt SplatValue, SplatUndef;
4036       unsigned SplatBitSize;
4037       bool HasAnyUndefs;
4038       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4039                                              SplatBitSize, HasAnyUndefs);
4040       if (IsSplat) {
4041         // Undef bits can contribute to a possible optimisation if set, so
4042         // set them.
4043         SplatValue |= SplatUndef;
4044
4045         // The splat value may be something like "0x00FFFFFF", which means 0 for
4046         // the first vector value and FF for the rest, repeating. We need a mask
4047         // that will apply equally to all members of the vector, so AND all the
4048         // lanes of the constant together.
4049         EVT VT = Vector->getValueType(0);
4050         unsigned BitWidth = VT.getScalarSizeInBits();
4051
4052         // If the splat value has been compressed to a bitlength lower
4053         // than the size of the vector lane, we need to re-expand it to
4054         // the lane size.
4055         if (BitWidth > SplatBitSize)
4056           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4057                SplatBitSize < BitWidth;
4058                SplatBitSize = SplatBitSize * 2)
4059             SplatValue |= SplatValue.shl(SplatBitSize);
4060
4061         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4062         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4063         if (SplatBitSize % BitWidth == 0) {
4064           Constant = APInt::getAllOnesValue(BitWidth);
4065           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4066             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4067         }
4068       }
4069     }
4070
4071     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4072     // actually legal and isn't going to get expanded, else this is a false
4073     // optimisation.
4074     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4075                                                     Load->getValueType(0),
4076                                                     Load->getMemoryVT());
4077
4078     // Resize the constant to the same size as the original memory access before
4079     // extension. If it is still the AllOnesValue then this AND is completely
4080     // unneeded.
4081     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4082
4083     bool B;
4084     switch (Load->getExtensionType()) {
4085     default: B = false; break;
4086     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4087     case ISD::ZEXTLOAD:
4088     case ISD::NON_EXTLOAD: B = true; break;
4089     }
4090
4091     if (B && Constant.isAllOnesValue()) {
4092       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4093       // preserve semantics once we get rid of the AND.
4094       SDValue NewLoad(Load, 0);
4095
4096       // Fold the AND away. NewLoad may get replaced immediately.
4097       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4098
4099       if (Load->getExtensionType() == ISD::EXTLOAD) {
4100         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4101                               Load->getValueType(0), SDLoc(Load),
4102                               Load->getChain(), Load->getBasePtr(),
4103                               Load->getOffset(), Load->getMemoryVT(),
4104                               Load->getMemOperand());
4105         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4106         if (Load->getNumValues() == 3) {
4107           // PRE/POST_INC loads have 3 values.
4108           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4109                            NewLoad.getValue(2) };
4110           CombineTo(Load, To, 3, true);
4111         } else {
4112           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4113         }
4114       }
4115
4116       return SDValue(N, 0); // Return N so it doesn't get rechecked!
4117     }
4118   }
4119
4120   // fold (and (load x), 255) -> (zextload x, i8)
4121   // fold (and (extload x, i16), 255) -> (zextload x, i8)
4122   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4123   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4124                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
4125                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4126     if (SDValue Res = ReduceLoadWidth(N)) {
4127       LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4128         ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4129
4130       AddToWorklist(N);
4131       CombineTo(LN0, Res, Res.getValue(1));
4132       return SDValue(N, 0);
4133     }
4134   }
4135
4136   if (Level >= AfterLegalizeTypes) {
4137     // Attempt to propagate the AND back up to the leaves which, if they're
4138     // loads, can be combined to narrow loads and the AND node can be removed.
4139     // Perform after legalization so that extend nodes will already be
4140     // combined into the loads.
4141     if (BackwardsPropagateMask(N, DAG)) {
4142       return SDValue(N, 0);
4143     }
4144   }
4145
4146   if (SDValue Combined = visitANDLike(N0, N1, N))
4147     return Combined;
4148
4149   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
4150   if (N0.getOpcode() == N1.getOpcode())
4151     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4152       return Tmp;
4153
4154   // Masking the negated extension of a boolean is just the zero-extended
4155   // boolean:
4156   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4157   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4158   //
4159   // Note: the SimplifyDemandedBits fold below can make an information-losing
4160   // transform, and then we have no way to find this better fold.
4161   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4162     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4163       SDValue SubRHS = N0.getOperand(1);
4164       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4165           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4166         return SubRHS;
4167       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4168           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4169         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4170     }
4171   }
4172
4173   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4174   // fold (and (sra)) -> (and (srl)) when possible.
4175   if (SimplifyDemandedBits(SDValue(N, 0)))
4176     return SDValue(N, 0);
4177
4178   // fold (zext_inreg (extload x)) -> (zextload x)
4179   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4180     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4181     EVT MemVT = LN0->getMemoryVT();
4182     // If we zero all the possible extended bits, then we can turn this into
4183     // a zextload if we are running before legalize or the operation is legal.
4184     unsigned BitWidth = N1.getScalarValueSizeInBits();
4185     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4186                            BitWidth - MemVT.getScalarSizeInBits())) &&
4187         ((!LegalOperations && !LN0->isVolatile()) ||
4188          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4189       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4190                                        LN0->getChain(), LN0->getBasePtr(),
4191                                        MemVT, LN0->getMemOperand());
4192       AddToWorklist(N);
4193       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4194       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4195     }
4196   }
4197   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4198   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4199       N0.hasOneUse()) {
4200     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4201     EVT MemVT = LN0->getMemoryVT();
4202     // If we zero all the possible extended bits, then we can turn this into
4203     // a zextload if we are running before legalize or the operation is legal.
4204     unsigned BitWidth = N1.getScalarValueSizeInBits();
4205     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4206                            BitWidth - MemVT.getScalarSizeInBits())) &&
4207         ((!LegalOperations && !LN0->isVolatile()) ||
4208          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4209       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4210                                        LN0->getChain(), LN0->getBasePtr(),
4211                                        MemVT, LN0->getMemOperand());
4212       AddToWorklist(N);
4213       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4214       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4215     }
4216   }
4217   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4218   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4219     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4220                                            N0.getOperand(1), false))
4221       return BSwap;
4222   }
4223
4224   return SDValue();
4225 }
4226
4227 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4228 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4229                                         bool DemandHighBits) {
4230   if (!LegalOperations)
4231     return SDValue();
4232
4233   EVT VT = N->getValueType(0);
4234   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4235     return SDValue();
4236   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4237     return SDValue();
4238
4239   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4240   bool LookPassAnd0 = false;
4241   bool LookPassAnd1 = false;
4242   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4243       std::swap(N0, N1);
4244   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4245       std::swap(N0, N1);
4246   if (N0.getOpcode() == ISD::AND) {
4247     if (!N0.getNode()->hasOneUse())
4248       return SDValue();
4249     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4250     if (!N01C || N01C->getZExtValue() != 0xFF00)
4251       return SDValue();
4252     N0 = N0.getOperand(0);
4253     LookPassAnd0 = true;
4254   }
4255
4256   if (N1.getOpcode() == ISD::AND) {
4257     if (!N1.getNode()->hasOneUse())
4258       return SDValue();
4259     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4260     if (!N11C || N11C->getZExtValue() != 0xFF)
4261       return SDValue();
4262     N1 = N1.getOperand(0);
4263     LookPassAnd1 = true;
4264   }
4265
4266   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4267     std::swap(N0, N1);
4268   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4269     return SDValue();
4270   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4271     return SDValue();
4272
4273   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4274   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4275   if (!N01C || !N11C)
4276     return SDValue();
4277   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4278     return SDValue();
4279
4280   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4281   SDValue N00 = N0->getOperand(0);
4282   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4283     if (!N00.getNode()->hasOneUse())
4284       return SDValue();
4285     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4286     if (!N001C || N001C->getZExtValue() != 0xFF)
4287       return SDValue();
4288     N00 = N00.getOperand(0);
4289     LookPassAnd0 = true;
4290   }
4291
4292   SDValue N10 = N1->getOperand(0);
4293   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4294     if (!N10.getNode()->hasOneUse())
4295       return SDValue();
4296     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4297     if (!N101C || N101C->getZExtValue() != 0xFF00)
4298       return SDValue();
4299     N10 = N10.getOperand(0);
4300     LookPassAnd1 = true;
4301   }
4302
4303   if (N00 != N10)
4304     return SDValue();
4305
4306   // Make sure everything beyond the low halfword gets set to zero since the SRL
4307   // 16 will clear the top bits.
4308   unsigned OpSizeInBits = VT.getSizeInBits();
4309   if (DemandHighBits && OpSizeInBits > 16) {
4310     // If the left-shift isn't masked out then the only way this is a bswap is
4311     // if all bits beyond the low 8 are 0. In that case the entire pattern
4312     // reduces to a left shift anyway: leave it for other parts of the combiner.
4313     if (!LookPassAnd0)
4314       return SDValue();
4315
4316     // However, if the right shift isn't masked out then it might be because
4317     // it's not needed. See if we can spot that too.
4318     if (!LookPassAnd1 &&
4319         !DAG.MaskedValueIsZero(
4320             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4321       return SDValue();
4322   }
4323
4324   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4325   if (OpSizeInBits > 16) {
4326     SDLoc DL(N);
4327     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4328                       DAG.getConstant(OpSizeInBits - 16, DL,
4329                                       getShiftAmountTy(VT)));
4330   }
4331   return Res;
4332 }
4333
4334 /// Return true if the specified node is an element that makes up a 32-bit
4335 /// packed halfword byteswap.
4336 /// ((x & 0x000000ff) << 8) |
4337 /// ((x & 0x0000ff00) >> 8) |
4338 /// ((x & 0x00ff0000) << 8) |
4339 /// ((x & 0xff000000) >> 8)
4340 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4341   if (!N.getNode()->hasOneUse())
4342     return false;
4343
4344   unsigned Opc = N.getOpcode();
4345   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4346     return false;
4347
4348   SDValue N0 = N.getOperand(0);
4349   unsigned Opc0 = N0.getOpcode();
4350   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4351     return false;
4352
4353   ConstantSDNode *N1C = nullptr;
4354   // SHL or SRL: look upstream for AND mask operand
4355   if (Opc == ISD::AND)
4356     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4357   else if (Opc0 == ISD::AND)
4358     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4359   if (!N1C)
4360     return false;
4361
4362   unsigned MaskByteOffset;
4363   switch (N1C->getZExtValue()) {
4364   default:
4365     return false;
4366   case 0xFF:       MaskByteOffset = 0; break;
4367   case 0xFF00:     MaskByteOffset = 1; break;
4368   case 0xFF0000:   MaskByteOffset = 2; break;
4369   case 0xFF000000: MaskByteOffset = 3; break;
4370   }
4371
4372   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4373   if (Opc == ISD::AND) {
4374     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4375       // (x >> 8) & 0xff
4376       // (x >> 8) & 0xff0000
4377       if (Opc0 != ISD::SRL)
4378         return false;
4379       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4380       if (!C || C->getZExtValue() != 8)
4381         return false;
4382     } else {
4383       // (x << 8) & 0xff00
4384       // (x << 8) & 0xff000000
4385       if (Opc0 != ISD::SHL)
4386         return false;
4387       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4388       if (!C || C->getZExtValue() != 8)
4389         return false;
4390     }
4391   } else if (Opc == ISD::SHL) {
4392     // (x & 0xff) << 8
4393     // (x & 0xff0000) << 8
4394     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4395       return false;
4396     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4397     if (!C || C->getZExtValue() != 8)
4398       return false;
4399   } else { // Opc == ISD::SRL
4400     // (x & 0xff00) >> 8
4401     // (x & 0xff000000) >> 8
4402     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4403       return false;
4404     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4405     if (!C || C->getZExtValue() != 8)
4406       return false;
4407   }
4408
4409   if (Parts[MaskByteOffset])
4410     return false;
4411
4412   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4413   return true;
4414 }
4415
4416 /// Match a 32-bit packed halfword bswap. That is
4417 /// ((x & 0x000000ff) << 8) |
4418 /// ((x & 0x0000ff00) >> 8) |
4419 /// ((x & 0x00ff0000) << 8) |
4420 /// ((x & 0xff000000) >> 8)
4421 /// => (rotl (bswap x), 16)
4422 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4423   if (!LegalOperations)
4424     return SDValue();
4425
4426   EVT VT = N->getValueType(0);
4427   if (VT != MVT::i32)
4428     return SDValue();
4429   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4430     return SDValue();
4431
4432   // Look for either
4433   // (or (or (and), (and)), (or (and), (and)))
4434   // (or (or (or (and), (and)), (and)), (and))
4435   if (N0.getOpcode() != ISD::OR)
4436     return SDValue();
4437   SDValue N00 = N0.getOperand(0);
4438   SDValue N01 = N0.getOperand(1);
4439   SDNode *Parts[4] = {};
4440
4441   if (N1.getOpcode() == ISD::OR &&
4442       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4443     // (or (or (and), (and)), (or (and), (and)))
4444     if (!isBSwapHWordElement(N00, Parts))
4445       return SDValue();
4446
4447     if (!isBSwapHWordElement(N01, Parts))
4448       return SDValue();
4449     SDValue N10 = N1.getOperand(0);
4450     if (!isBSwapHWordElement(N10, Parts))
4451       return SDValue();
4452     SDValue N11 = N1.getOperand(1);
4453     if (!isBSwapHWordElement(N11, Parts))
4454       return SDValue();
4455   } else {
4456     // (or (or (or (and), (and)), (and)), (and))
4457     if (!isBSwapHWordElement(N1, Parts))
4458       return SDValue();
4459     if (!isBSwapHWordElement(N01, Parts))
4460       return SDValue();
4461     if (N00.getOpcode() != ISD::OR)
4462       return SDValue();
4463     SDValue N000 = N00.getOperand(0);
4464     if (!isBSwapHWordElement(N000, Parts))
4465       return SDValue();
4466     SDValue N001 = N00.getOperand(1);
4467     if (!isBSwapHWordElement(N001, Parts))
4468       return SDValue();
4469   }
4470
4471   // Make sure the parts are all coming from the same node.
4472   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4473     return SDValue();
4474
4475   SDLoc DL(N);
4476   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4477                               SDValue(Parts[0], 0));
4478
4479   // Result of the bswap should be rotated by 16. If it's not legal, then
4480   // do  (x << 16) | (x >> 16).
4481   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4482   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4483     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4484   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4485     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4486   return DAG.getNode(ISD::OR, DL, VT,
4487                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4488                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4489 }
4490
4491 /// This contains all DAGCombine rules which reduce two values combined by
4492 /// an Or operation to a single value \see visitANDLike().
4493 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4494   EVT VT = N1.getValueType();
4495   SDLoc DL(N);
4496
4497   // fold (or x, undef) -> -1
4498   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4499     return DAG.getAllOnesConstant(DL, VT);
4500
4501   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4502     return V;
4503
4504   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4505   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4506       // Don't increase # computations.
4507       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4508     // We can only do this xform if we know that bits from X that are set in C2
4509     // but not in C1 are already zero.  Likewise for Y.
4510     if (const ConstantSDNode *N0O1C =
4511         getAsNonOpaqueConstant(N0.getOperand(1))) {
4512       if (const ConstantSDNode *N1O1C =
4513           getAsNonOpaqueConstant(N1.getOperand(1))) {
4514         // We can only do this xform if we know that bits from X that are set in
4515         // C2 but not in C1 are already zero.  Likewise for Y.
4516         const APInt &LHSMask = N0O1C->getAPIntValue();
4517         const APInt &RHSMask = N1O1C->getAPIntValue();
4518
4519         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4520             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4521           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4522                                   N0.getOperand(0), N1.getOperand(0));
4523           return DAG.getNode(ISD::AND, DL, VT, X,
4524                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4525         }
4526       }
4527     }
4528   }
4529
4530   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4531   if (N0.getOpcode() == ISD::AND &&
4532       N1.getOpcode() == ISD::AND &&
4533       N0.getOperand(0) == N1.getOperand(0) &&
4534       // Don't increase # computations.
4535       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4536     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4537                             N0.getOperand(1), N1.getOperand(1));
4538     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4539   }
4540
4541   return SDValue();
4542 }
4543
4544 SDValue DAGCombiner::visitOR(SDNode *N) {
4545   SDValue N0 = N->getOperand(0);
4546   SDValue N1 = N->getOperand(1);
4547   EVT VT = N1.getValueType();
4548
4549   // x | x --> x
4550   if (N0 == N1)
4551     return N0;
4552
4553   // fold vector ops
4554   if (VT.isVector()) {
4555     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4556       return FoldedVOp;
4557
4558     // fold (or x, 0) -> x, vector edition
4559     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4560       return N1;
4561     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4562       return N0;
4563
4564     // fold (or x, -1) -> -1, vector edition
4565     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4566       // do not return N0, because undef node may exist in N0
4567       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4568     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4569       // do not return N1, because undef node may exist in N1
4570       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4571
4572     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4573     // Do this only if the resulting shuffle is legal.
4574     if (isa<ShuffleVectorSDNode>(N0) &&
4575         isa<ShuffleVectorSDNode>(N1) &&
4576         // Avoid folding a node with illegal type.
4577         TLI.isTypeLegal(VT)) {
4578       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4579       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4580       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4581       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4582       // Ensure both shuffles have a zero input.
4583       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4584         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4585         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4586         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4587         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4588         bool CanFold = true;
4589         int NumElts = VT.getVectorNumElements();
4590         SmallVector<int, 4> Mask(NumElts);
4591
4592         for (int i = 0; i != NumElts; ++i) {
4593           int M0 = SV0->getMaskElt(i);
4594           int M1 = SV1->getMaskElt(i);
4595
4596           // Determine if either index is pointing to a zero vector.
4597           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4598           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4599
4600           // If one element is zero and the otherside is undef, keep undef.
4601           // This also handles the case that both are undef.
4602           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4603             Mask[i] = -1;
4604             continue;
4605           }
4606
4607           // Make sure only one of the elements is zero.
4608           if (M0Zero == M1Zero) {
4609             CanFold = false;
4610             break;
4611           }
4612
4613           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4614
4615           // We have a zero and non-zero element. If the non-zero came from
4616           // SV0 make the index a LHS index. If it came from SV1, make it
4617           // a RHS index. We need to mod by NumElts because we don't care
4618           // which operand it came from in the original shuffles.
4619           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4620         }
4621
4622         if (CanFold) {
4623           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4624           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4625
4626           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4627           if (!LegalMask) {
4628             std::swap(NewLHS, NewRHS);
4629             ShuffleVectorSDNode::commuteMask(Mask);
4630             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4631           }
4632
4633           if (LegalMask)
4634             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4635         }
4636       }
4637     }
4638   }
4639
4640   // fold (or c1, c2) -> c1|c2
4641   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4642   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4643   if (N0C && N1C && !N1C->isOpaque())
4644     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4645   // canonicalize constant to RHS
4646   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4647      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4648     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4649   // fold (or x, 0) -> x
4650   if (isNullConstant(N1))
4651     return N0;
4652   // fold (or x, -1) -> -1
4653   if (isAllOnesConstant(N1))
4654     return N1;
4655
4656   if (SDValue NewSel = foldBinOpIntoSelect(N))
4657     return NewSel;
4658
4659   // fold (or x, c) -> c iff (x & ~c) == 0
4660   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4661     return N1;
4662
4663   if (SDValue Combined = visitORLike(N0, N1, N))
4664     return Combined;
4665
4666   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4667   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4668     return BSwap;
4669   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4670     return BSwap;
4671
4672   // reassociate or
4673   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4674     return ROR;
4675
4676   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4677   // iff (c1 & c2) != 0.
4678   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4679     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4680       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4681         if (SDValue COR =
4682                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4683           return DAG.getNode(
4684               ISD::AND, SDLoc(N), VT,
4685               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4686         return SDValue();
4687       }
4688     }
4689   }
4690
4691   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4692   if (N0.getOpcode() == N1.getOpcode())
4693     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4694       return Tmp;
4695
4696   // See if this is some rotate idiom.
4697   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4698     return SDValue(Rot, 0);
4699
4700   if (SDValue Load = MatchLoadCombine(N))
4701     return Load;
4702
4703   // Simplify the operands using demanded-bits information.
4704   if (SimplifyDemandedBits(SDValue(N, 0)))
4705     return SDValue(N, 0);
4706
4707   return SDValue();
4708 }
4709
4710 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4711 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4712   if (Op.getOpcode() == ISD::AND) {
4713     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4714       Mask = Op.getOperand(1);
4715       Op = Op.getOperand(0);
4716     } else {
4717       return false;
4718     }
4719   }
4720
4721   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4722     Shift = Op;
4723     return true;
4724   }
4725
4726   return false;
4727 }
4728
4729 // Return true if we can prove that, whenever Neg and Pos are both in the
4730 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4731 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4732 //
4733 //     (or (shift1 X, Neg), (shift2 X, Pos))
4734 //
4735 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4736 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4737 // to consider shift amounts with defined behavior.
4738 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4739   // If EltSize is a power of 2 then:
4740   //
4741   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4742   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4743   //
4744   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4745   // for the stronger condition:
4746   //
4747   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4748   //
4749   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4750   // we can just replace Neg with Neg' for the rest of the function.
4751   //
4752   // In other cases we check for the even stronger condition:
4753   //
4754   //     Neg == EltSize - Pos                                    [B]
4755   //
4756   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4757   // behavior if Pos == 0 (and consequently Neg == EltSize).
4758   //
4759   // We could actually use [A] whenever EltSize is a power of 2, but the
4760   // only extra cases that it would match are those uninteresting ones
4761   // where Neg and Pos are never in range at the same time.  E.g. for
4762   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4763   // as well as (sub 32, Pos), but:
4764   //
4765   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4766   //
4767   // always invokes undefined behavior for 32-bit X.
4768   //
4769   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4770   unsigned MaskLoBits = 0;
4771   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4772     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4773       if (NegC->getAPIntValue() == EltSize - 1) {
4774         Neg = Neg.getOperand(0);
4775         MaskLoBits = Log2_64(EltSize);
4776       }
4777     }
4778   }
4779
4780   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4781   if (Neg.getOpcode() != ISD::SUB)
4782     return false;
4783   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4784   if (!NegC)
4785     return false;
4786   SDValue NegOp1 = Neg.getOperand(1);
4787
4788   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4789   // Pos'.  The truncation is redundant for the purpose of the equality.
4790   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4791     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4792       if (PosC->getAPIntValue() == EltSize - 1)
4793         Pos = Pos.getOperand(0);
4794
4795   // The condition we need is now:
4796   //
4797   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4798   //
4799   // If NegOp1 == Pos then we need:
4800   //
4801   //              EltSize & Mask == NegC & Mask
4802   //
4803   // (because "x & Mask" is a truncation and distributes through subtraction).
4804   APInt Width;
4805   if (Pos == NegOp1)
4806     Width = NegC->getAPIntValue();
4807
4808   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4809   // Then the condition we want to prove becomes:
4810   //
4811   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4812   //
4813   // which, again because "x & Mask" is a truncation, becomes:
4814   //
4815   //                NegC & Mask == (EltSize - PosC) & Mask
4816   //             EltSize & Mask == (NegC + PosC) & Mask
4817   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4818     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4819       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4820     else
4821       return false;
4822   } else
4823     return false;
4824
4825   // Now we just need to check that EltSize & Mask == Width & Mask.
4826   if (MaskLoBits)
4827     // EltSize & Mask is 0 since Mask is EltSize - 1.
4828     return Width.getLoBits(MaskLoBits) == 0;
4829   return Width == EltSize;
4830 }
4831
4832 // A subroutine of MatchRotate used once we have found an OR of two opposite
4833 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4834 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4835 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4836 // Neg with outer conversions stripped away.
4837 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4838                                        SDValue Neg, SDValue InnerPos,
4839                                        SDValue InnerNeg, unsigned PosOpcode,
4840                                        unsigned NegOpcode, const SDLoc &DL) {
4841   // fold (or (shl x, (*ext y)),
4842   //          (srl x, (*ext (sub 32, y)))) ->
4843   //   (rotl x, y) or (rotr x, (sub 32, y))
4844   //
4845   // fold (or (shl x, (*ext (sub 32, y))),
4846   //          (srl x, (*ext y))) ->
4847   //   (rotr x, y) or (rotl x, (sub 32, y))
4848   EVT VT = Shifted.getValueType();
4849   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4850     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4851     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4852                        HasPos ? Pos : Neg).getNode();
4853   }
4854
4855   return nullptr;
4856 }
4857
4858 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4859 // idioms for rotate, and if the target supports rotation instructions, generate
4860 // a rot[lr].
4861 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4862   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4863   EVT VT = LHS.getValueType();
4864   if (!TLI.isTypeLegal(VT)) return nullptr;
4865
4866   // The target must have at least one rotate flavor.
4867   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4868   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4869   if (!HasROTL && !HasROTR) return nullptr;
4870
4871   // Check for truncated rotate.
4872   if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
4873       LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
4874     assert(LHS.getValueType() == RHS.getValueType());
4875     if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
4876       return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
4877                          SDValue(Rot, 0)).getNode();
4878     }
4879   }
4880
4881   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4882   SDValue LHSShift;   // The shift.
4883   SDValue LHSMask;    // AND value if any.
4884   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4885     return nullptr; // Not part of a rotate.
4886
4887   SDValue RHSShift;   // The shift.
4888   SDValue RHSMask;    // AND value if any.
4889   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4890     return nullptr; // Not part of a rotate.
4891
4892   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4893     return nullptr;   // Not shifting the same value.
4894
4895   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4896     return nullptr;   // Shifts must disagree.
4897
4898   // Canonicalize shl to left side in a shl/srl pair.
4899   if (RHSShift.getOpcode() == ISD::SHL) {
4900     std::swap(LHS, RHS);
4901     std::swap(LHSShift, RHSShift);
4902     std::swap(LHSMask, RHSMask);
4903   }
4904
4905   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4906   SDValue LHSShiftArg = LHSShift.getOperand(0);
4907   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4908   SDValue RHSShiftArg = RHSShift.getOperand(0);
4909   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4910
4911   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4912   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4913   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4914                                         ConstantSDNode *RHS) {
4915     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4916   };
4917   if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4918     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4919                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4920
4921     // If there is an AND of either shifted operand, apply it to the result.
4922     if (LHSMask.getNode() || RHSMask.getNode()) {
4923       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4924       SDValue Mask = AllOnes;
4925
4926       if (LHSMask.getNode()) {
4927         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4928         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4929                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4930       }
4931       if (RHSMask.getNode()) {
4932         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4933         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4934                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4935       }
4936
4937       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4938     }
4939
4940     return Rot.getNode();
4941   }
4942
4943   // If there is a mask here, and we have a variable shift, we can't be sure
4944   // that we're masking out the right stuff.
4945   if (LHSMask.getNode() || RHSMask.getNode())
4946     return nullptr;
4947
4948   // If the shift amount is sign/zext/any-extended just peel it off.
4949   SDValue LExtOp0 = LHSShiftAmt;
4950   SDValue RExtOp0 = RHSShiftAmt;
4951   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4952        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4953        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4954        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4955       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4956        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4957        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4958        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4959     LExtOp0 = LHSShiftAmt.getOperand(0);
4960     RExtOp0 = RHSShiftAmt.getOperand(0);
4961   }
4962
4963   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4964                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4965   if (TryL)
4966     return TryL;
4967
4968   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4969                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4970   if (TryR)
4971     return TryR;
4972
4973   return nullptr;
4974 }
4975
4976 namespace {
4977
4978 /// Represents known origin of an individual byte in load combine pattern. The
4979 /// value of the byte is either constant zero or comes from memory.
4980 struct ByteProvider {
4981   // For constant zero providers Load is set to nullptr. For memory providers
4982   // Load represents the node which loads the byte from memory.
4983   // ByteOffset is the offset of the byte in the value produced by the load.
4984   LoadSDNode *Load = nullptr;
4985   unsigned ByteOffset = 0;
4986
4987   ByteProvider() = default;
4988
4989   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4990     return ByteProvider(Load, ByteOffset);
4991   }
4992
4993   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4994
4995   bool isConstantZero() const { return !Load; }
4996   bool isMemory() const { return Load; }
4997
4998   bool operator==(const ByteProvider &Other) const {
4999     return Other.Load == Load && Other.ByteOffset == ByteOffset;
5000   }
5001
5002 private:
5003   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5004       : Load(Load), ByteOffset(ByteOffset) {}
5005 };
5006
5007 } // end anonymous namespace
5008
5009 /// Recursively traverses the expression calculating the origin of the requested
5010 /// byte of the given value. Returns None if the provider can't be calculated.
5011 ///
5012 /// For all the values except the root of the expression verifies that the value
5013 /// has exactly one use and if it's not true return None. This way if the origin
5014 /// of the byte is returned it's guaranteed that the values which contribute to
5015 /// the byte are not used outside of this expression.
5016 ///
5017 /// Because the parts of the expression are not allowed to have more than one
5018 /// use this function iterates over trees, not DAGs. So it never visits the same
5019 /// node more than once.
5020 static const Optional<ByteProvider>
5021 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5022                       bool Root = false) {
5023   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5024   if (Depth == 10)
5025     return None;
5026
5027   if (!Root && !Op.hasOneUse())
5028     return None;
5029
5030   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
5031   unsigned BitWidth = Op.getValueSizeInBits();
5032   if (BitWidth % 8 != 0)
5033     return None;
5034   unsigned ByteWidth = BitWidth / 8;
5035   assert(Index < ByteWidth && "invalid index requested");
5036   (void) ByteWidth;
5037
5038   switch (Op.getOpcode()) {
5039   case ISD::OR: {
5040     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5041     if (!LHS)
5042       return None;
5043     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5044     if (!RHS)
5045       return None;
5046
5047     if (LHS->isConstantZero())
5048       return RHS;
5049     if (RHS->isConstantZero())
5050       return LHS;
5051     return None;
5052   }
5053   case ISD::SHL: {
5054     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5055     if (!ShiftOp)
5056       return None;
5057
5058     uint64_t BitShift = ShiftOp->getZExtValue();
5059     if (BitShift % 8 != 0)
5060       return None;
5061     uint64_t ByteShift = BitShift / 8;
5062
5063     return Index < ByteShift
5064                ? ByteProvider::getConstantZero()
5065                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5066                                        Depth + 1);
5067   }
5068   case ISD::ANY_EXTEND:
5069   case ISD::SIGN_EXTEND:
5070   case ISD::ZERO_EXTEND: {
5071     SDValue NarrowOp = Op->getOperand(0);
5072     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5073     if (NarrowBitWidth % 8 != 0)
5074       return None;
5075     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5076
5077     if (Index >= NarrowByteWidth)
5078       return Op.getOpcode() == ISD::ZERO_EXTEND
5079                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5080                  : None;
5081     return calculateByteProvider(NarrowOp, Index, Depth + 1);
5082   }
5083   case ISD::BSWAP:
5084     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5085                                  Depth + 1);
5086   case ISD::LOAD: {
5087     auto L = cast<LoadSDNode>(Op.getNode());
5088     if (L->isVolatile() || L->isIndexed())
5089       return None;
5090
5091     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5092     if (NarrowBitWidth % 8 != 0)
5093       return None;
5094     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5095
5096     if (Index >= NarrowByteWidth)
5097       return L->getExtensionType() == ISD::ZEXTLOAD
5098                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5099                  : None;
5100     return ByteProvider::getMemory(L, Index);
5101   }
5102   }
5103
5104   return None;
5105 }
5106
5107 /// Match a pattern where a wide type scalar value is loaded by several narrow
5108 /// loads and combined by shifts and ors. Fold it into a single load or a load
5109 /// and a BSWAP if the targets supports it.
5110 ///
5111 /// Assuming little endian target:
5112 ///  i8 *a = ...
5113 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5114 /// =>
5115 ///  i32 val = *((i32)a)
5116 ///
5117 ///  i8 *a = ...
5118 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5119 /// =>
5120 ///  i32 val = BSWAP(*((i32)a))
5121 ///
5122 /// TODO: This rule matches complex patterns with OR node roots and doesn't
5123 /// interact well with the worklist mechanism. When a part of the pattern is
5124 /// updated (e.g. one of the loads) its direct users are put into the worklist,
5125 /// but the root node of the pattern which triggers the load combine is not
5126 /// necessarily a direct user of the changed node. For example, once the address
5127 /// of t28 load is reassociated load combine won't be triggered:
5128 ///             t25: i32 = add t4, Constant:i32<2>
5129 ///           t26: i64 = sign_extend t25
5130 ///        t27: i64 = add t2, t26
5131 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5132 ///     t29: i32 = zero_extend t28
5133 ///   t32: i32 = shl t29, Constant:i8<8>
5134 /// t33: i32 = or t23, t32
5135 /// As a possible fix visitLoad can check if the load can be a part of a load
5136 /// combine pattern and add corresponding OR roots to the worklist.
5137 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5138   assert(N->getOpcode() == ISD::OR &&
5139          "Can only match load combining against OR nodes");
5140
5141   // Handles simple types only
5142   EVT VT = N->getValueType(0);
5143   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5144     return SDValue();
5145   unsigned ByteWidth = VT.getSizeInBits() / 8;
5146
5147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5148   // Before legalize we can introduce too wide illegal loads which will be later
5149   // split into legal sized loads. This enables us to combine i64 load by i8
5150   // patterns to a couple of i32 loads on 32 bit targets.
5151   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5152     return SDValue();
5153
5154   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5155     unsigned BW, unsigned i) { return i; };
5156   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5157     unsigned BW, unsigned i) { return BW - i - 1; };
5158
5159   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5160   auto MemoryByteOffset = [&] (ByteProvider P) {
5161     assert(P.isMemory() && "Must be a memory byte provider");
5162     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5163     assert(LoadBitWidth % 8 == 0 &&
5164            "can only analyze providers for individual bytes not bit");
5165     unsigned LoadByteWidth = LoadBitWidth / 8;
5166     return IsBigEndianTarget
5167             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5168             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5169   };
5170
5171   Optional<BaseIndexOffset> Base;
5172   SDValue Chain;
5173
5174   SmallSet<LoadSDNode *, 8> Loads;
5175   Optional<ByteProvider> FirstByteProvider;
5176   int64_t FirstOffset = INT64_MAX;
5177
5178   // Check if all the bytes of the OR we are looking at are loaded from the same
5179   // base address. Collect bytes offsets from Base address in ByteOffsets.
5180   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5181   for (unsigned i = 0; i < ByteWidth; i++) {
5182     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5183     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5184       return SDValue();
5185
5186     LoadSDNode *L = P->Load;
5187     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5188            "Must be enforced by calculateByteProvider");
5189     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5190
5191     // All loads must share the same chain
5192     SDValue LChain = L->getChain();
5193     if (!Chain)
5194       Chain = LChain;
5195     else if (Chain != LChain)
5196       return SDValue();
5197
5198     // Loads must share the same base address
5199     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
5200     int64_t ByteOffsetFromBase = 0;
5201     if (!Base)
5202       Base = Ptr;
5203     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5204       return SDValue();
5205
5206     // Calculate the offset of the current byte from the base address
5207     ByteOffsetFromBase += MemoryByteOffset(*P);
5208     ByteOffsets[i] = ByteOffsetFromBase;
5209
5210     // Remember the first byte load
5211     if (ByteOffsetFromBase < FirstOffset) {
5212       FirstByteProvider = P;
5213       FirstOffset = ByteOffsetFromBase;
5214     }
5215
5216     Loads.insert(L);
5217   }
5218   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5219          "memory, so there must be at least one load which produces the value");
5220   assert(Base && "Base address of the accessed memory location must be set");
5221   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5222
5223   // Check if the bytes of the OR we are looking at match with either big or
5224   // little endian value load
5225   bool BigEndian = true, LittleEndian = true;
5226   for (unsigned i = 0; i < ByteWidth; i++) {
5227     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5228     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5229     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5230     if (!BigEndian && !LittleEndian)
5231       return SDValue();
5232   }
5233   assert((BigEndian != LittleEndian) && "should be either or");
5234   assert(FirstByteProvider && "must be set");
5235
5236   // Ensure that the first byte is loaded from zero offset of the first load.
5237   // So the combined value can be loaded from the first load address.
5238   if (MemoryByteOffset(*FirstByteProvider) != 0)
5239     return SDValue();
5240   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5241
5242   // The node we are looking at matches with the pattern, check if we can
5243   // replace it with a single load and bswap if needed.
5244
5245   // If the load needs byte swap check if the target supports it
5246   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5247
5248   // Before legalize we can introduce illegal bswaps which will be later
5249   // converted to an explicit bswap sequence. This way we end up with a single
5250   // load and byte shuffling instead of several loads and byte shuffling.
5251   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5252     return SDValue();
5253
5254   // Check that a load of the wide type is both allowed and fast on the target
5255   bool Fast = false;
5256   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5257                                         VT, FirstLoad->getAddressSpace(),
5258                                         FirstLoad->getAlignment(), &Fast);
5259   if (!Allowed || !Fast)
5260     return SDValue();
5261
5262   SDValue NewLoad =
5263       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5264                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5265
5266   // Transfer chain users from old loads to the new load.
5267   for (LoadSDNode *L : Loads)
5268     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5269
5270   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5271 }
5272
5273 SDValue DAGCombiner::visitXOR(SDNode *N) {
5274   SDValue N0 = N->getOperand(0);
5275   SDValue N1 = N->getOperand(1);
5276   EVT VT = N0.getValueType();
5277
5278   // fold vector ops
5279   if (VT.isVector()) {
5280     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5281       return FoldedVOp;
5282
5283     // fold (xor x, 0) -> x, vector edition
5284     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5285       return N1;
5286     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5287       return N0;
5288   }
5289
5290   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5291   if (N0.isUndef() && N1.isUndef())
5292     return DAG.getConstant(0, SDLoc(N), VT);
5293   // fold (xor x, undef) -> undef
5294   if (N0.isUndef())
5295     return N0;
5296   if (N1.isUndef())
5297     return N1;
5298   // fold (xor c1, c2) -> c1^c2
5299   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5300   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5301   if (N0C && N1C)
5302     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5303   // canonicalize constant to RHS
5304   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5305      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5306     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5307   // fold (xor x, 0) -> x
5308   if (isNullConstant(N1))
5309     return N0;
5310
5311   if (SDValue NewSel = foldBinOpIntoSelect(N))
5312     return NewSel;
5313
5314   // reassociate xor
5315   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5316     return RXOR;
5317
5318   // fold !(x cc y) -> (x !cc y)
5319   SDValue LHS, RHS, CC;
5320   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5321     bool isInt = LHS.getValueType().isInteger();
5322     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5323                                                isInt);
5324
5325     if (!LegalOperations ||
5326         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5327       switch (N0.getOpcode()) {
5328       default:
5329         llvm_unreachable("Unhandled SetCC Equivalent!");
5330       case ISD::SETCC:
5331         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5332       case ISD::SELECT_CC:
5333         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5334                                N0.getOperand(3), NotCC);
5335       }
5336     }
5337   }
5338
5339   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5340   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5341       N0.getNode()->hasOneUse() &&
5342       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5343     SDValue V = N0.getOperand(0);
5344     SDLoc DL(N0);
5345     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5346                     DAG.getConstant(1, DL, V.getValueType()));
5347     AddToWorklist(V.getNode());
5348     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5349   }
5350
5351   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5352   if (isOneConstant(N1) && VT == MVT::i1 &&
5353       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5354     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5355     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5356       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5357       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5358       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5359       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5360       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5361     }
5362   }
5363   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5364   if (isAllOnesConstant(N1) &&
5365       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5366     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5367     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5368       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5369       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5370       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5371       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5372       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5373     }
5374   }
5375   // fold (xor (and x, y), y) -> (and (not x), y)
5376   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5377       N0->getOperand(1) == N1) {
5378     SDValue X = N0->getOperand(0);
5379     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5380     AddToWorklist(NotX.getNode());
5381     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5382   }
5383   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5384   if (N1C && N0.getOpcode() == ISD::XOR) {
5385     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5386       SDLoc DL(N);
5387       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5388                          DAG.getConstant(N1C->getAPIntValue() ^
5389                                          N00C->getAPIntValue(), DL, VT));
5390     }
5391     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5392       SDLoc DL(N);
5393       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5394                          DAG.getConstant(N1C->getAPIntValue() ^
5395                                          N01C->getAPIntValue(), DL, VT));
5396     }
5397   }
5398
5399   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5400   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5401   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5402       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5403       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5404     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5405       if (C->getAPIntValue() == (OpSizeInBits - 1))
5406         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5407   }
5408
5409   // fold (xor x, x) -> 0
5410   if (N0 == N1)
5411     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5412
5413   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5414   // Here is a concrete example of this equivalence:
5415   // i16   x ==  14
5416   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5417   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5418   //
5419   // =>
5420   //
5421   // i16     ~1      == 0b1111111111111110
5422   // i16 rol(~1, 14) == 0b1011111111111111
5423   //
5424   // Some additional tips to help conceptualize this transform:
5425   // - Try to see the operation as placing a single zero in a value of all ones.
5426   // - There exists no value for x which would allow the result to contain zero.
5427   // - Values of x larger than the bitwidth are undefined and do not require a
5428   //   consistent result.
5429   // - Pushing the zero left requires shifting one bits in from the right.
5430   // A rotate left of ~1 is a nice way of achieving the desired result.
5431   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5432       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5433     SDLoc DL(N);
5434     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5435                        N0.getOperand(1));
5436   }
5437
5438   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5439   if (N0.getOpcode() == N1.getOpcode())
5440     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5441       return Tmp;
5442
5443   // Simplify the expression using non-local knowledge.
5444   if (SimplifyDemandedBits(SDValue(N, 0)))
5445     return SDValue(N, 0);
5446
5447   return SDValue();
5448 }
5449
5450 /// Handle transforms common to the three shifts, when the shift amount is a
5451 /// constant.
5452 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5453   SDNode *LHS = N->getOperand(0).getNode();
5454   if (!LHS->hasOneUse()) return SDValue();
5455
5456   // We want to pull some binops through shifts, so that we have (and (shift))
5457   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5458   // thing happens with address calculations, so it's important to canonicalize
5459   // it.
5460   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5461
5462   switch (LHS->getOpcode()) {
5463   default: return SDValue();
5464   case ISD::OR:
5465   case ISD::XOR:
5466     HighBitSet = false; // We can only transform sra if the high bit is clear.
5467     break;
5468   case ISD::AND:
5469     HighBitSet = true;  // We can only transform sra if the high bit is set.
5470     break;
5471   case ISD::ADD:
5472     if (N->getOpcode() != ISD::SHL)
5473       return SDValue(); // only shl(add) not sr[al](add).
5474     HighBitSet = false; // We can only transform sra if the high bit is clear.
5475     break;
5476   }
5477
5478   // We require the RHS of the binop to be a constant and not opaque as well.
5479   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5480   if (!BinOpCst) return SDValue();
5481
5482   // FIXME: disable this unless the input to the binop is a shift by a constant
5483   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5484   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5485   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5486                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5487                  BinOpLHSVal->getOpcode() == ISD::SRL;
5488   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5489                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5490
5491   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5492       !isCopyOrSelect)
5493     return SDValue();
5494
5495   if (isCopyOrSelect && N->hasOneUse())
5496     return SDValue();
5497
5498   EVT VT = N->getValueType(0);
5499
5500   // If this is a signed shift right, and the high bit is modified by the
5501   // logical operation, do not perform the transformation. The highBitSet
5502   // boolean indicates the value of the high bit of the constant which would
5503   // cause it to be modified for this operation.
5504   if (N->getOpcode() == ISD::SRA) {
5505     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5506     if (BinOpRHSSignSet != HighBitSet)
5507       return SDValue();
5508   }
5509
5510   if (!TLI.isDesirableToCommuteWithShift(LHS))
5511     return SDValue();
5512
5513   // Fold the constants, shifting the binop RHS by the shift amount.
5514   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5515                                N->getValueType(0),
5516                                LHS->getOperand(1), N->getOperand(1));
5517   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5518
5519   // Create the new shift.
5520   SDValue NewShift = DAG.getNode(N->getOpcode(),
5521                                  SDLoc(LHS->getOperand(0)),
5522                                  VT, LHS->getOperand(0), N->getOperand(1));
5523
5524   // Create the new binop.
5525   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5526 }
5527
5528 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5529   assert(N->getOpcode() == ISD::TRUNCATE);
5530   assert(N->getOperand(0).getOpcode() == ISD::AND);
5531
5532   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5533   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5534     SDValue N01 = N->getOperand(0).getOperand(1);
5535     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5536       SDLoc DL(N);
5537       EVT TruncVT = N->getValueType(0);
5538       SDValue N00 = N->getOperand(0).getOperand(0);
5539       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5540       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5541       AddToWorklist(Trunc00.getNode());
5542       AddToWorklist(Trunc01.getNode());
5543       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5544     }
5545   }
5546
5547   return SDValue();
5548 }
5549
5550 SDValue DAGCombiner::visitRotate(SDNode *N) {
5551   SDLoc dl(N);
5552   SDValue N0 = N->getOperand(0);
5553   SDValue N1 = N->getOperand(1);
5554   EVT VT = N->getValueType(0);
5555   unsigned Bitsize = VT.getScalarSizeInBits();
5556
5557   // fold (rot x, 0) -> x
5558   if (isNullConstantOrNullSplatConstant(N1))
5559     return N0;
5560
5561   // fold (rot x, c) -> (rot x, c % BitSize)
5562   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5563     if (Cst->getAPIntValue().uge(Bitsize)) {
5564       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5565       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5566                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5567     }
5568   }
5569
5570   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5571   if (N1.getOpcode() == ISD::TRUNCATE &&
5572       N1.getOperand(0).getOpcode() == ISD::AND) {
5573     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5574       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5575   }
5576
5577   unsigned NextOp = N0.getOpcode();
5578   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5579   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5580     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5581     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5582     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5583       EVT ShiftVT = C1->getValueType(0);
5584       bool SameSide = (N->getOpcode() == NextOp);
5585       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5586       if (SDValue CombinedShift =
5587               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5588         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5589         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5590             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5591             BitsizeC.getNode());
5592         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5593                            CombinedShiftNorm);
5594       }
5595     }
5596   }
5597   return SDValue();
5598 }
5599
5600 SDValue DAGCombiner::visitSHL(SDNode *N) {
5601   SDValue N0 = N->getOperand(0);
5602   SDValue N1 = N->getOperand(1);
5603   EVT VT = N0.getValueType();
5604   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5605
5606   // fold vector ops
5607   if (VT.isVector()) {
5608     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5609       return FoldedVOp;
5610
5611     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5612     // If setcc produces all-one true value then:
5613     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5614     if (N1CV && N1CV->isConstant()) {
5615       if (N0.getOpcode() == ISD::AND) {
5616         SDValue N00 = N0->getOperand(0);
5617         SDValue N01 = N0->getOperand(1);
5618         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5619
5620         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5621             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5622                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5623           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5624                                                      N01CV, N1CV))
5625             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5626         }
5627       }
5628     }
5629   }
5630
5631   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5632
5633   // fold (shl c1, c2) -> c1<<c2
5634   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5635   if (N0C && N1C && !N1C->isOpaque())
5636     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5637   // fold (shl 0, x) -> 0
5638   if (isNullConstantOrNullSplatConstant(N0))
5639     return N0;
5640   // fold (shl x, c >= size(x)) -> undef
5641   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5642   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5643     return Val->getAPIntValue().uge(OpSizeInBits);
5644   };
5645   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5646     return DAG.getUNDEF(VT);
5647   // fold (shl x, 0) -> x
5648   if (N1C && N1C->isNullValue())
5649     return N0;
5650   // fold (shl undef, x) -> 0
5651   if (N0.isUndef())
5652     return DAG.getConstant(0, SDLoc(N), VT);
5653
5654   if (SDValue NewSel = foldBinOpIntoSelect(N))
5655     return NewSel;
5656
5657   // if (shl x, c) is known to be zero, return 0
5658   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5659                             APInt::getAllOnesValue(OpSizeInBits)))
5660     return DAG.getConstant(0, SDLoc(N), VT);
5661   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5662   if (N1.getOpcode() == ISD::TRUNCATE &&
5663       N1.getOperand(0).getOpcode() == ISD::AND) {
5664     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5665       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5666   }
5667
5668   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5669     return SDValue(N, 0);
5670
5671   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5672   if (N0.getOpcode() == ISD::SHL) {
5673     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5674                                           ConstantSDNode *RHS) {
5675       APInt c1 = LHS->getAPIntValue();
5676       APInt c2 = RHS->getAPIntValue();
5677       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5678       return (c1 + c2).uge(OpSizeInBits);
5679     };
5680     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5681       return DAG.getConstant(0, SDLoc(N), VT);
5682
5683     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5684                                        ConstantSDNode *RHS) {
5685       APInt c1 = LHS->getAPIntValue();
5686       APInt c2 = RHS->getAPIntValue();
5687       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5688       return (c1 + c2).ult(OpSizeInBits);
5689     };
5690     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5691       SDLoc DL(N);
5692       EVT ShiftVT = N1.getValueType();
5693       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5694       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5695     }
5696   }
5697
5698   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5699   // For this to be valid, the second form must not preserve any of the bits
5700   // that are shifted out by the inner shift in the first form.  This means
5701   // the outer shift size must be >= the number of bits added by the ext.
5702   // As a corollary, we don't care what kind of ext it is.
5703   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5704               N0.getOpcode() == ISD::ANY_EXTEND ||
5705               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5706       N0.getOperand(0).getOpcode() == ISD::SHL) {
5707     SDValue N0Op0 = N0.getOperand(0);
5708     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5709       APInt c1 = N0Op0C1->getAPIntValue();
5710       APInt c2 = N1C->getAPIntValue();
5711       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5712
5713       EVT InnerShiftVT = N0Op0.getValueType();
5714       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5715       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5716         SDLoc DL(N0);
5717         APInt Sum = c1 + c2;
5718         if (Sum.uge(OpSizeInBits))
5719           return DAG.getConstant(0, DL, VT);
5720
5721         return DAG.getNode(
5722             ISD::SHL, DL, VT,
5723             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5724             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5725       }
5726     }
5727   }
5728
5729   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5730   // Only fold this if the inner zext has no other uses to avoid increasing
5731   // the total number of instructions.
5732   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5733       N0.getOperand(0).getOpcode() == ISD::SRL) {
5734     SDValue N0Op0 = N0.getOperand(0);
5735     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5736       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5737         uint64_t c1 = N0Op0C1->getZExtValue();
5738         uint64_t c2 = N1C->getZExtValue();
5739         if (c1 == c2) {
5740           SDValue NewOp0 = N0.getOperand(0);
5741           EVT CountVT = NewOp0.getOperand(1).getValueType();
5742           SDLoc DL(N);
5743           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5744                                        NewOp0,
5745                                        DAG.getConstant(c2, DL, CountVT));
5746           AddToWorklist(NewSHL.getNode());
5747           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5748         }
5749       }
5750     }
5751   }
5752
5753   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5754   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5755   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5756       N0->getFlags().hasExact()) {
5757     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5758       uint64_t C1 = N0C1->getZExtValue();
5759       uint64_t C2 = N1C->getZExtValue();
5760       SDLoc DL(N);
5761       if (C1 <= C2)
5762         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5763                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5764       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5765                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5766     }
5767   }
5768
5769   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5770   //                               (and (srl x, (sub c1, c2), MASK)
5771   // Only fold this if the inner shift has no other uses -- if it does, folding
5772   // this will increase the total number of instructions.
5773   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5774     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5775       uint64_t c1 = N0C1->getZExtValue();
5776       if (c1 < OpSizeInBits) {
5777         uint64_t c2 = N1C->getZExtValue();
5778         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5779         SDValue Shift;
5780         if (c2 > c1) {
5781           Mask <<= c2 - c1;
5782           SDLoc DL(N);
5783           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5784                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5785         } else {
5786           Mask.lshrInPlace(c1 - c2);
5787           SDLoc DL(N);
5788           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5789                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5790         }
5791         SDLoc DL(N0);
5792         return DAG.getNode(ISD::AND, DL, VT, Shift,
5793                            DAG.getConstant(Mask, DL, VT));
5794       }
5795     }
5796   }
5797
5798   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5799   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5800       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5801     SDLoc DL(N);
5802     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5803     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5804     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5805   }
5806
5807   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5808   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5809   // Variant of version done on multiply, except mul by a power of 2 is turned
5810   // into a shift.
5811   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5812       N0.getNode()->hasOneUse() &&
5813       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5814       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5815     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5816     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5817     AddToWorklist(Shl0.getNode());
5818     AddToWorklist(Shl1.getNode());
5819     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5820   }
5821
5822   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5823   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5824       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5825       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5826     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5827     if (isConstantOrConstantVector(Shl))
5828       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5829   }
5830
5831   if (N1C && !N1C->isOpaque())
5832     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5833       return NewSHL;
5834
5835   return SDValue();
5836 }
5837
5838 SDValue DAGCombiner::visitSRA(SDNode *N) {
5839   SDValue N0 = N->getOperand(0);
5840   SDValue N1 = N->getOperand(1);
5841   EVT VT = N0.getValueType();
5842   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5843
5844   // Arithmetic shifting an all-sign-bit value is a no-op.
5845   // fold (sra 0, x) -> 0
5846   // fold (sra -1, x) -> -1
5847   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5848     return N0;
5849
5850   // fold vector ops
5851   if (VT.isVector())
5852     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5853       return FoldedVOp;
5854
5855   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5856
5857   // fold (sra c1, c2) -> (sra c1, c2)
5858   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5859   if (N0C && N1C && !N1C->isOpaque())
5860     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5861   // fold (sra x, c >= size(x)) -> undef
5862   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5863   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5864     return Val->getAPIntValue().uge(OpSizeInBits);
5865   };
5866   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5867     return DAG.getUNDEF(VT);
5868   // fold (sra x, 0) -> x
5869   if (N1C && N1C->isNullValue())
5870     return N0;
5871
5872   if (SDValue NewSel = foldBinOpIntoSelect(N))
5873     return NewSel;
5874
5875   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5876   // sext_inreg.
5877   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5878     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5879     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5880     if (VT.isVector())
5881       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5882                                ExtVT, VT.getVectorNumElements());
5883     if ((!LegalOperations ||
5884          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5885       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5886                          N0.getOperand(0), DAG.getValueType(ExtVT));
5887   }
5888
5889   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5890   if (N0.getOpcode() == ISD::SRA) {
5891     SDLoc DL(N);
5892     EVT ShiftVT = N1.getValueType();
5893
5894     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5895                                           ConstantSDNode *RHS) {
5896       APInt c1 = LHS->getAPIntValue();
5897       APInt c2 = RHS->getAPIntValue();
5898       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5899       return (c1 + c2).uge(OpSizeInBits);
5900     };
5901     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5902       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5903                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5904
5905     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5906                                        ConstantSDNode *RHS) {
5907       APInt c1 = LHS->getAPIntValue();
5908       APInt c2 = RHS->getAPIntValue();
5909       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5910       return (c1 + c2).ult(OpSizeInBits);
5911     };
5912     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5913       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5914       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5915     }
5916   }
5917
5918   // fold (sra (shl X, m), (sub result_size, n))
5919   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5920   // result_size - n != m.
5921   // If truncate is free for the target sext(shl) is likely to result in better
5922   // code.
5923   if (N0.getOpcode() == ISD::SHL && N1C) {
5924     // Get the two constanst of the shifts, CN0 = m, CN = n.
5925     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5926     if (N01C) {
5927       LLVMContext &Ctx = *DAG.getContext();
5928       // Determine what the truncate's result bitsize and type would be.
5929       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5930
5931       if (VT.isVector())
5932         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5933
5934       // Determine the residual right-shift amount.
5935       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5936
5937       // If the shift is not a no-op (in which case this should be just a sign
5938       // extend already), the truncated to type is legal, sign_extend is legal
5939       // on that type, and the truncate to that type is both legal and free,
5940       // perform the transform.
5941       if ((ShiftAmt > 0) &&
5942           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5943           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5944           TLI.isTruncateFree(VT, TruncVT)) {
5945         SDLoc DL(N);
5946         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5947             getShiftAmountTy(N0.getOperand(0).getValueType()));
5948         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5949                                     N0.getOperand(0), Amt);
5950         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5951                                     Shift);
5952         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5953                            N->getValueType(0), Trunc);
5954       }
5955     }
5956   }
5957
5958   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5959   if (N1.getOpcode() == ISD::TRUNCATE &&
5960       N1.getOperand(0).getOpcode() == ISD::AND) {
5961     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5962       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5963   }
5964
5965   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5966   //      if c1 is equal to the number of bits the trunc removes
5967   if (N0.getOpcode() == ISD::TRUNCATE &&
5968       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5969        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5970       N0.getOperand(0).hasOneUse() &&
5971       N0.getOperand(0).getOperand(1).hasOneUse() &&
5972       N1C) {
5973     SDValue N0Op0 = N0.getOperand(0);
5974     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5975       unsigned LargeShiftVal = LargeShift->getZExtValue();
5976       EVT LargeVT = N0Op0.getValueType();
5977
5978       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5979         SDLoc DL(N);
5980         SDValue Amt =
5981           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5982                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5983         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5984                                   N0Op0.getOperand(0), Amt);
5985         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5986       }
5987     }
5988   }
5989
5990   // Simplify, based on bits shifted out of the LHS.
5991   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5992     return SDValue(N, 0);
5993
5994   // If the sign bit is known to be zero, switch this to a SRL.
5995   if (DAG.SignBitIsZero(N0))
5996     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5997
5998   if (N1C && !N1C->isOpaque())
5999     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6000       return NewSRA;
6001
6002   return SDValue();
6003 }
6004
6005 SDValue DAGCombiner::visitSRL(SDNode *N) {
6006   SDValue N0 = N->getOperand(0);
6007   SDValue N1 = N->getOperand(1);
6008   EVT VT = N0.getValueType();
6009   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6010
6011   // fold vector ops
6012   if (VT.isVector())
6013     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6014       return FoldedVOp;
6015
6016   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6017
6018   // fold (srl c1, c2) -> c1 >>u c2
6019   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6020   if (N0C && N1C && !N1C->isOpaque())
6021     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6022   // fold (srl 0, x) -> 0
6023   if (isNullConstantOrNullSplatConstant(N0))
6024     return N0;
6025   // fold (srl x, c >= size(x)) -> undef
6026   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6027   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6028     return Val->getAPIntValue().uge(OpSizeInBits);
6029   };
6030   if (matchUnaryPredicate(N1, MatchShiftTooBig))
6031     return DAG.getUNDEF(VT);
6032   // fold (srl x, 0) -> x
6033   if (N1C && N1C->isNullValue())
6034     return N0;
6035
6036   if (SDValue NewSel = foldBinOpIntoSelect(N))
6037     return NewSel;
6038
6039   // if (srl x, c) is known to be zero, return 0
6040   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6041                                    APInt::getAllOnesValue(OpSizeInBits)))
6042     return DAG.getConstant(0, SDLoc(N), VT);
6043
6044   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6045   if (N0.getOpcode() == ISD::SRL) {
6046     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6047                                           ConstantSDNode *RHS) {
6048       APInt c1 = LHS->getAPIntValue();
6049       APInt c2 = RHS->getAPIntValue();
6050       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6051       return (c1 + c2).uge(OpSizeInBits);
6052     };
6053     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6054       return DAG.getConstant(0, SDLoc(N), VT);
6055
6056     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6057                                        ConstantSDNode *RHS) {
6058       APInt c1 = LHS->getAPIntValue();
6059       APInt c2 = RHS->getAPIntValue();
6060       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6061       return (c1 + c2).ult(OpSizeInBits);
6062     };
6063     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6064       SDLoc DL(N);
6065       EVT ShiftVT = N1.getValueType();
6066       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6067       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6068     }
6069   }
6070
6071   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6072   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6073       N0.getOperand(0).getOpcode() == ISD::SRL) {
6074     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6075       uint64_t c1 = N001C->getZExtValue();
6076       uint64_t c2 = N1C->getZExtValue();
6077       EVT InnerShiftVT = N0.getOperand(0).getValueType();
6078       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6079       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6080       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6081       if (c1 + OpSizeInBits == InnerShiftSize) {
6082         SDLoc DL(N0);
6083         if (c1 + c2 >= InnerShiftSize)
6084           return DAG.getConstant(0, DL, VT);
6085         return DAG.getNode(ISD::TRUNCATE, DL, VT,
6086                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6087                                        N0.getOperand(0).getOperand(0),
6088                                        DAG.getConstant(c1 + c2, DL,
6089                                                        ShiftCountVT)));
6090       }
6091     }
6092   }
6093
6094   // fold (srl (shl x, c), c) -> (and x, cst2)
6095   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6096       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6097     SDLoc DL(N);
6098     SDValue Mask =
6099         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6100     AddToWorklist(Mask.getNode());
6101     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6102   }
6103
6104   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6105   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6106     // Shifting in all undef bits?
6107     EVT SmallVT = N0.getOperand(0).getValueType();
6108     unsigned BitSize = SmallVT.getScalarSizeInBits();
6109     if (N1C->getZExtValue() >= BitSize)
6110       return DAG.getUNDEF(VT);
6111
6112     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6113       uint64_t ShiftAmt = N1C->getZExtValue();
6114       SDLoc DL0(N0);
6115       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6116                                        N0.getOperand(0),
6117                           DAG.getConstant(ShiftAmt, DL0,
6118                                           getShiftAmountTy(SmallVT)));
6119       AddToWorklist(SmallShift.getNode());
6120       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6121       SDLoc DL(N);
6122       return DAG.getNode(ISD::AND, DL, VT,
6123                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6124                          DAG.getConstant(Mask, DL, VT));
6125     }
6126   }
6127
6128   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
6129   // bit, which is unmodified by sra.
6130   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6131     if (N0.getOpcode() == ISD::SRA)
6132       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6133   }
6134
6135   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
6136   if (N1C && N0.getOpcode() == ISD::CTLZ &&
6137       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6138     KnownBits Known;
6139     DAG.computeKnownBits(N0.getOperand(0), Known);
6140
6141     // If any of the input bits are KnownOne, then the input couldn't be all
6142     // zeros, thus the result of the srl will always be zero.
6143     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6144
6145     // If all of the bits input the to ctlz node are known to be zero, then
6146     // the result of the ctlz is "32" and the result of the shift is one.
6147     APInt UnknownBits = ~Known.Zero;
6148     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6149
6150     // Otherwise, check to see if there is exactly one bit input to the ctlz.
6151     if (UnknownBits.isPowerOf2()) {
6152       // Okay, we know that only that the single bit specified by UnknownBits
6153       // could be set on input to the CTLZ node. If this bit is set, the SRL
6154       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6155       // to an SRL/XOR pair, which is likely to simplify more.
6156       unsigned ShAmt = UnknownBits.countTrailingZeros();
6157       SDValue Op = N0.getOperand(0);
6158
6159       if (ShAmt) {
6160         SDLoc DL(N0);
6161         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6162                   DAG.getConstant(ShAmt, DL,
6163                                   getShiftAmountTy(Op.getValueType())));
6164         AddToWorklist(Op.getNode());
6165       }
6166
6167       SDLoc DL(N);
6168       return DAG.getNode(ISD::XOR, DL, VT,
6169                          Op, DAG.getConstant(1, DL, VT));
6170     }
6171   }
6172
6173   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6174   if (N1.getOpcode() == ISD::TRUNCATE &&
6175       N1.getOperand(0).getOpcode() == ISD::AND) {
6176     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6177       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6178   }
6179
6180   // fold operands of srl based on knowledge that the low bits are not
6181   // demanded.
6182   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6183     return SDValue(N, 0);
6184
6185   if (N1C && !N1C->isOpaque())
6186     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6187       return NewSRL;
6188
6189   // Attempt to convert a srl of a load into a narrower zero-extending load.
6190   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6191     return NarrowLoad;
6192
6193   // Here is a common situation. We want to optimize:
6194   //
6195   //   %a = ...
6196   //   %b = and i32 %a, 2
6197   //   %c = srl i32 %b, 1
6198   //   brcond i32 %c ...
6199   //
6200   // into
6201   //
6202   //   %a = ...
6203   //   %b = and %a, 2
6204   //   %c = setcc eq %b, 0
6205   //   brcond %c ...
6206   //
6207   // However when after the source operand of SRL is optimized into AND, the SRL
6208   // itself may not be optimized further. Look for it and add the BRCOND into
6209   // the worklist.
6210   if (N->hasOneUse()) {
6211     SDNode *Use = *N->use_begin();
6212     if (Use->getOpcode() == ISD::BRCOND)
6213       AddToWorklist(Use);
6214     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6215       // Also look pass the truncate.
6216       Use = *Use->use_begin();
6217       if (Use->getOpcode() == ISD::BRCOND)
6218         AddToWorklist(Use);
6219     }
6220   }
6221
6222   return SDValue();
6223 }
6224
6225 SDValue DAGCombiner::visitABS(SDNode *N) {
6226   SDValue N0 = N->getOperand(0);
6227   EVT VT = N->getValueType(0);
6228
6229   // fold (abs c1) -> c2
6230   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6231     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6232   // fold (abs (abs x)) -> (abs x)
6233   if (N0.getOpcode() == ISD::ABS)
6234     return N0;
6235   // fold (abs x) -> x iff not-negative
6236   if (DAG.SignBitIsZero(N0))
6237     return N0;
6238   return SDValue();
6239 }
6240
6241 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6242   SDValue N0 = N->getOperand(0);
6243   EVT VT = N->getValueType(0);
6244
6245   // fold (bswap c1) -> c2
6246   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6247     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6248   // fold (bswap (bswap x)) -> x
6249   if (N0.getOpcode() == ISD::BSWAP)
6250     return N0->getOperand(0);
6251   return SDValue();
6252 }
6253
6254 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6255   SDValue N0 = N->getOperand(0);
6256   EVT VT = N->getValueType(0);
6257
6258   // fold (bitreverse c1) -> c2
6259   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6260     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6261   // fold (bitreverse (bitreverse x)) -> x
6262   if (N0.getOpcode() == ISD::BITREVERSE)
6263     return N0.getOperand(0);
6264   return SDValue();
6265 }
6266
6267 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6268   SDValue N0 = N->getOperand(0);
6269   EVT VT = N->getValueType(0);
6270
6271   // fold (ctlz c1) -> c2
6272   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6273     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6274   return SDValue();
6275 }
6276
6277 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6278   SDValue N0 = N->getOperand(0);
6279   EVT VT = N->getValueType(0);
6280
6281   // fold (ctlz_zero_undef c1) -> c2
6282   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6283     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6284   return SDValue();
6285 }
6286
6287 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6288   SDValue N0 = N->getOperand(0);
6289   EVT VT = N->getValueType(0);
6290
6291   // fold (cttz c1) -> c2
6292   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6293     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6294   return SDValue();
6295 }
6296
6297 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6298   SDValue N0 = N->getOperand(0);
6299   EVT VT = N->getValueType(0);
6300
6301   // fold (cttz_zero_undef c1) -> c2
6302   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6303     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6304   return SDValue();
6305 }
6306
6307 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6308   SDValue N0 = N->getOperand(0);
6309   EVT VT = N->getValueType(0);
6310
6311   // fold (ctpop c1) -> c2
6312   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6313     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6314   return SDValue();
6315 }
6316
6317 /// \brief Generate Min/Max node
6318 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6319                                    SDValue RHS, SDValue True, SDValue False,
6320                                    ISD::CondCode CC, const TargetLowering &TLI,
6321                                    SelectionDAG &DAG) {
6322   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6323     return SDValue();
6324
6325   switch (CC) {
6326   case ISD::SETOLT:
6327   case ISD::SETOLE:
6328   case ISD::SETLT:
6329   case ISD::SETLE:
6330   case ISD::SETULT:
6331   case ISD::SETULE: {
6332     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6333     if (TLI.isOperationLegal(Opcode, VT))
6334       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6335     return SDValue();
6336   }
6337   case ISD::SETOGT:
6338   case ISD::SETOGE:
6339   case ISD::SETGT:
6340   case ISD::SETGE:
6341   case ISD::SETUGT:
6342   case ISD::SETUGE: {
6343     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6344     if (TLI.isOperationLegal(Opcode, VT))
6345       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6346     return SDValue();
6347   }
6348   default:
6349     return SDValue();
6350   }
6351 }
6352
6353 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6354   SDValue Cond = N->getOperand(0);
6355   SDValue N1 = N->getOperand(1);
6356   SDValue N2 = N->getOperand(2);
6357   EVT VT = N->getValueType(0);
6358   EVT CondVT = Cond.getValueType();
6359   SDLoc DL(N);
6360
6361   if (!VT.isInteger())
6362     return SDValue();
6363
6364   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6365   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6366   if (!C1 || !C2)
6367     return SDValue();
6368
6369   // Only do this before legalization to avoid conflicting with target-specific
6370   // transforms in the other direction (create a select from a zext/sext). There
6371   // is also a target-independent combine here in DAGCombiner in the other
6372   // direction for (select Cond, -1, 0) when the condition is not i1.
6373   if (CondVT == MVT::i1 && !LegalOperations) {
6374     if (C1->isNullValue() && C2->isOne()) {
6375       // select Cond, 0, 1 --> zext (!Cond)
6376       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6377       if (VT != MVT::i1)
6378         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6379       return NotCond;
6380     }
6381     if (C1->isNullValue() && C2->isAllOnesValue()) {
6382       // select Cond, 0, -1 --> sext (!Cond)
6383       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6384       if (VT != MVT::i1)
6385         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6386       return NotCond;
6387     }
6388     if (C1->isOne() && C2->isNullValue()) {
6389       // select Cond, 1, 0 --> zext (Cond)
6390       if (VT != MVT::i1)
6391         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6392       return Cond;
6393     }
6394     if (C1->isAllOnesValue() && C2->isNullValue()) {
6395       // select Cond, -1, 0 --> sext (Cond)
6396       if (VT != MVT::i1)
6397         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6398       return Cond;
6399     }
6400
6401     // For any constants that differ by 1, we can transform the select into an
6402     // extend and add. Use a target hook because some targets may prefer to
6403     // transform in the other direction.
6404     if (TLI.convertSelectOfConstantsToMath(VT)) {
6405       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6406         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6407         if (VT != MVT::i1)
6408           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6409         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6410       }
6411       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6412         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6413         if (VT != MVT::i1)
6414           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6415         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6416       }
6417     }
6418
6419     return SDValue();
6420   }
6421
6422   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6423   // We can't do this reliably if integer based booleans have different contents
6424   // to floating point based booleans. This is because we can't tell whether we
6425   // have an integer-based boolean or a floating-point-based boolean unless we
6426   // can find the SETCC that produced it and inspect its operands. This is
6427   // fairly easy if C is the SETCC node, but it can potentially be
6428   // undiscoverable (or not reasonably discoverable). For example, it could be
6429   // in another basic block or it could require searching a complicated
6430   // expression.
6431   if (CondVT.isInteger() &&
6432       TLI.getBooleanContents(false, true) ==
6433           TargetLowering::ZeroOrOneBooleanContent &&
6434       TLI.getBooleanContents(false, false) ==
6435           TargetLowering::ZeroOrOneBooleanContent &&
6436       C1->isNullValue() && C2->isOne()) {
6437     SDValue NotCond =
6438         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6439     if (VT.bitsEq(CondVT))
6440       return NotCond;
6441     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6442   }
6443
6444   return SDValue();
6445 }
6446
6447 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6448   SDValue N0 = N->getOperand(0);
6449   SDValue N1 = N->getOperand(1);
6450   SDValue N2 = N->getOperand(2);
6451   EVT VT = N->getValueType(0);
6452   EVT VT0 = N0.getValueType();
6453   SDLoc DL(N);
6454
6455   // fold (select C, X, X) -> X
6456   if (N1 == N2)
6457     return N1;
6458
6459   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6460     // fold (select true, X, Y) -> X
6461     // fold (select false, X, Y) -> Y
6462     return !N0C->isNullValue() ? N1 : N2;
6463   }
6464
6465   // fold (select X, X, Y) -> (or X, Y)
6466   // fold (select X, 1, Y) -> (or C, Y)
6467   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6468     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6469
6470   if (SDValue V = foldSelectOfConstants(N))
6471     return V;
6472
6473   // fold (select C, 0, X) -> (and (not C), X)
6474   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6475     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6476     AddToWorklist(NOTNode.getNode());
6477     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6478   }
6479   // fold (select C, X, 1) -> (or (not C), X)
6480   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6481     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6482     AddToWorklist(NOTNode.getNode());
6483     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6484   }
6485   // fold (select X, Y, X) -> (and X, Y)
6486   // fold (select X, Y, 0) -> (and X, Y)
6487   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6488     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6489
6490   // If we can fold this based on the true/false value, do so.
6491   if (SimplifySelectOps(N, N1, N2))
6492     return SDValue(N, 0); // Don't revisit N.
6493
6494   if (VT0 == MVT::i1) {
6495     // The code in this block deals with the following 2 equivalences:
6496     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6497     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6498     // The target can specify its preferred form with the
6499     // shouldNormalizeToSelectSequence() callback. However we always transform
6500     // to the right anyway if we find the inner select exists in the DAG anyway
6501     // and we always transform to the left side if we know that we can further
6502     // optimize the combination of the conditions.
6503     bool normalizeToSequence =
6504         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6505     // select (and Cond0, Cond1), X, Y
6506     //   -> select Cond0, (select Cond1, X, Y), Y
6507     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6508       SDValue Cond0 = N0->getOperand(0);
6509       SDValue Cond1 = N0->getOperand(1);
6510       SDValue InnerSelect =
6511           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6512       if (normalizeToSequence || !InnerSelect.use_empty())
6513         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6514                            InnerSelect, N2);
6515     }
6516     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6517     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6518       SDValue Cond0 = N0->getOperand(0);
6519       SDValue Cond1 = N0->getOperand(1);
6520       SDValue InnerSelect =
6521           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6522       if (normalizeToSequence || !InnerSelect.use_empty())
6523         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6524                            InnerSelect);
6525     }
6526
6527     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6528     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6529       SDValue N1_0 = N1->getOperand(0);
6530       SDValue N1_1 = N1->getOperand(1);
6531       SDValue N1_2 = N1->getOperand(2);
6532       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6533         // Create the actual and node if we can generate good code for it.
6534         if (!normalizeToSequence) {
6535           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6536           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6537         }
6538         // Otherwise see if we can optimize the "and" to a better pattern.
6539         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6540           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6541                              N2);
6542       }
6543     }
6544     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6545     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6546       SDValue N2_0 = N2->getOperand(0);
6547       SDValue N2_1 = N2->getOperand(1);
6548       SDValue N2_2 = N2->getOperand(2);
6549       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6550         // Create the actual or node if we can generate good code for it.
6551         if (!normalizeToSequence) {
6552           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6553           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6554         }
6555         // Otherwise see if we can optimize to a better pattern.
6556         if (SDValue Combined = visitORLike(N0, N2_0, N))
6557           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6558                              N2_2);
6559       }
6560     }
6561   }
6562
6563   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6564   if (VT0 == MVT::i1) {
6565     if (N0->getOpcode() == ISD::XOR) {
6566       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6567         SDValue Cond0 = N0->getOperand(0);
6568         if (C->isOne())
6569           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6570       }
6571     }
6572   }
6573
6574   // fold selects based on a setcc into other things, such as min/max/abs
6575   if (N0.getOpcode() == ISD::SETCC) {
6576     // select x, y (fcmp lt x, y) -> fminnum x, y
6577     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6578     //
6579     // This is OK if we don't care about what happens if either operand is a
6580     // NaN.
6581     //
6582
6583     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6584     // no signed zeros as well as no nans.
6585     const TargetOptions &Options = DAG.getTarget().Options;
6586     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6587         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6588       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6589
6590       if (SDValue FMinMax = combineMinNumMaxNum(
6591               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6592         return FMinMax;
6593     }
6594
6595     if ((!LegalOperations &&
6596          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6597         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6598       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6599                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6600     return SimplifySelect(DL, N0, N1, N2);
6601   }
6602
6603   return SDValue();
6604 }
6605
6606 static
6607 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6608   SDLoc DL(N);
6609   EVT LoVT, HiVT;
6610   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6611
6612   // Split the inputs.
6613   SDValue Lo, Hi, LL, LH, RL, RH;
6614   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6615   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6616
6617   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6618   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6619
6620   return std::make_pair(Lo, Hi);
6621 }
6622
6623 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6624 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6625 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6626   SDLoc DL(N);
6627   SDValue Cond = N->getOperand(0);
6628   SDValue LHS = N->getOperand(1);
6629   SDValue RHS = N->getOperand(2);
6630   EVT VT = N->getValueType(0);
6631   int NumElems = VT.getVectorNumElements();
6632   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6633          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6634          Cond.getOpcode() == ISD::BUILD_VECTOR);
6635
6636   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6637   // binary ones here.
6638   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6639     return SDValue();
6640
6641   // We're sure we have an even number of elements due to the
6642   // concat_vectors we have as arguments to vselect.
6643   // Skip BV elements until we find one that's not an UNDEF
6644   // After we find an UNDEF element, keep looping until we get to half the
6645   // length of the BV and see if all the non-undef nodes are the same.
6646   ConstantSDNode *BottomHalf = nullptr;
6647   for (int i = 0; i < NumElems / 2; ++i) {
6648     if (Cond->getOperand(i)->isUndef())
6649       continue;
6650
6651     if (BottomHalf == nullptr)
6652       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6653     else if (Cond->getOperand(i).getNode() != BottomHalf)
6654       return SDValue();
6655   }
6656
6657   // Do the same for the second half of the BuildVector
6658   ConstantSDNode *TopHalf = nullptr;
6659   for (int i = NumElems / 2; i < NumElems; ++i) {
6660     if (Cond->getOperand(i)->isUndef())
6661       continue;
6662
6663     if (TopHalf == nullptr)
6664       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6665     else if (Cond->getOperand(i).getNode() != TopHalf)
6666       return SDValue();
6667   }
6668
6669   assert(TopHalf && BottomHalf &&
6670          "One half of the selector was all UNDEFs and the other was all the "
6671          "same value. This should have been addressed before this function.");
6672   return DAG.getNode(
6673       ISD::CONCAT_VECTORS, DL, VT,
6674       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6675       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6676 }
6677
6678 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6679   if (Level >= AfterLegalizeTypes)
6680     return SDValue();
6681
6682   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6683   SDValue Mask = MSC->getMask();
6684   SDValue Data  = MSC->getValue();
6685   SDLoc DL(N);
6686
6687   // If the MSCATTER data type requires splitting and the mask is provided by a
6688   // SETCC, then split both nodes and its operands before legalization. This
6689   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6690   // and enables future optimizations (e.g. min/max pattern matching on X86).
6691   if (Mask.getOpcode() != ISD::SETCC)
6692     return SDValue();
6693
6694   // Check if any splitting is required.
6695   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6696       TargetLowering::TypeSplitVector)
6697     return SDValue();
6698   SDValue MaskLo, MaskHi, Lo, Hi;
6699   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6700
6701   EVT LoVT, HiVT;
6702   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6703
6704   SDValue Chain = MSC->getChain();
6705
6706   EVT MemoryVT = MSC->getMemoryVT();
6707   unsigned Alignment = MSC->getOriginalAlignment();
6708
6709   EVT LoMemVT, HiMemVT;
6710   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6711
6712   SDValue DataLo, DataHi;
6713   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6714
6715   SDValue BasePtr = MSC->getBasePtr();
6716   SDValue IndexLo, IndexHi;
6717   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6718
6719   MachineMemOperand *MMO = DAG.getMachineFunction().
6720     getMachineMemOperand(MSC->getPointerInfo(),
6721                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6722                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6723
6724   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6725   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6726                             DL, OpsLo, MMO);
6727
6728   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6729   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6730                             DL, OpsHi, MMO);
6731
6732   AddToWorklist(Lo.getNode());
6733   AddToWorklist(Hi.getNode());
6734
6735   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6736 }
6737
6738 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6739   if (Level >= AfterLegalizeTypes)
6740     return SDValue();
6741
6742   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6743   SDValue Mask = MST->getMask();
6744   SDValue Data  = MST->getValue();
6745   EVT VT = Data.getValueType();
6746   SDLoc DL(N);
6747
6748   // If the MSTORE data type requires splitting and the mask is provided by a
6749   // SETCC, then split both nodes and its operands before legalization. This
6750   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6751   // and enables future optimizations (e.g. min/max pattern matching on X86).
6752   if (Mask.getOpcode() == ISD::SETCC) {
6753     // Check if any splitting is required.
6754     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6755         TargetLowering::TypeSplitVector)
6756       return SDValue();
6757
6758     SDValue MaskLo, MaskHi, Lo, Hi;
6759     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6760
6761     SDValue Chain = MST->getChain();
6762     SDValue Ptr   = MST->getBasePtr();
6763
6764     EVT MemoryVT = MST->getMemoryVT();
6765     unsigned Alignment = MST->getOriginalAlignment();
6766
6767     // if Alignment is equal to the vector size,
6768     // take the half of it for the second part
6769     unsigned SecondHalfAlignment =
6770       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6771
6772     EVT LoMemVT, HiMemVT;
6773     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6774
6775     SDValue DataLo, DataHi;
6776     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6777
6778     MachineMemOperand *MMO = DAG.getMachineFunction().
6779       getMachineMemOperand(MST->getPointerInfo(),
6780                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6781                            Alignment, MST->getAAInfo(), MST->getRanges());
6782
6783     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6784                             MST->isTruncatingStore(),
6785                             MST->isCompressingStore());
6786
6787     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6788                                      MST->isCompressingStore());
6789
6790     MMO = DAG.getMachineFunction().
6791       getMachineMemOperand(MST->getPointerInfo(),
6792                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6793                            SecondHalfAlignment, MST->getAAInfo(),
6794                            MST->getRanges());
6795
6796     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6797                             MST->isTruncatingStore(),
6798                             MST->isCompressingStore());
6799
6800     AddToWorklist(Lo.getNode());
6801     AddToWorklist(Hi.getNode());
6802
6803     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6804   }
6805   return SDValue();
6806 }
6807
6808 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6809   if (Level >= AfterLegalizeTypes)
6810     return SDValue();
6811
6812   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
6813   SDValue Mask = MGT->getMask();
6814   SDLoc DL(N);
6815
6816   // If the MGATHER result requires splitting and the mask is provided by a
6817   // SETCC, then split both nodes and its operands before legalization. This
6818   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6819   // and enables future optimizations (e.g. min/max pattern matching on X86).
6820
6821   if (Mask.getOpcode() != ISD::SETCC)
6822     return SDValue();
6823
6824   EVT VT = N->getValueType(0);
6825
6826   // Check if any splitting is required.
6827   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6828       TargetLowering::TypeSplitVector)
6829     return SDValue();
6830
6831   SDValue MaskLo, MaskHi, Lo, Hi;
6832   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6833
6834   SDValue Src0 = MGT->getValue();
6835   SDValue Src0Lo, Src0Hi;
6836   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6837
6838   EVT LoVT, HiVT;
6839   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6840
6841   SDValue Chain = MGT->getChain();
6842   EVT MemoryVT = MGT->getMemoryVT();
6843   unsigned Alignment = MGT->getOriginalAlignment();
6844
6845   EVT LoMemVT, HiMemVT;
6846   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6847
6848   SDValue BasePtr = MGT->getBasePtr();
6849   SDValue Index = MGT->getIndex();
6850   SDValue IndexLo, IndexHi;
6851   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6852
6853   MachineMemOperand *MMO = DAG.getMachineFunction().
6854     getMachineMemOperand(MGT->getPointerInfo(),
6855                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6856                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6857
6858   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6859   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6860                             MMO);
6861
6862   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6863   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6864                             MMO);
6865
6866   AddToWorklist(Lo.getNode());
6867   AddToWorklist(Hi.getNode());
6868
6869   // Build a factor node to remember that this load is independent of the
6870   // other one.
6871   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6872                       Hi.getValue(1));
6873
6874   // Legalized the chain result - switch anything that used the old chain to
6875   // use the new one.
6876   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6877
6878   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6879
6880   SDValue RetOps[] = { GatherRes, Chain };
6881   return DAG.getMergeValues(RetOps, DL);
6882 }
6883
6884 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6885   if (Level >= AfterLegalizeTypes)
6886     return SDValue();
6887
6888   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6889   SDValue Mask = MLD->getMask();
6890   SDLoc DL(N);
6891
6892   // If the MLOAD result requires splitting and the mask is provided by a
6893   // SETCC, then split both nodes and its operands before legalization. This
6894   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6895   // and enables future optimizations (e.g. min/max pattern matching on X86).
6896   if (Mask.getOpcode() == ISD::SETCC) {
6897     EVT VT = N->getValueType(0);
6898
6899     // Check if any splitting is required.
6900     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6901         TargetLowering::TypeSplitVector)
6902       return SDValue();
6903
6904     SDValue MaskLo, MaskHi, Lo, Hi;
6905     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6906
6907     SDValue Src0 = MLD->getSrc0();
6908     SDValue Src0Lo, Src0Hi;
6909     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6910
6911     EVT LoVT, HiVT;
6912     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6913
6914     SDValue Chain = MLD->getChain();
6915     SDValue Ptr   = MLD->getBasePtr();
6916     EVT MemoryVT = MLD->getMemoryVT();
6917     unsigned Alignment = MLD->getOriginalAlignment();
6918
6919     // if Alignment is equal to the vector size,
6920     // take the half of it for the second part
6921     unsigned SecondHalfAlignment =
6922       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6923          Alignment/2 : Alignment;
6924
6925     EVT LoMemVT, HiMemVT;
6926     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6927
6928     MachineMemOperand *MMO = DAG.getMachineFunction().
6929     getMachineMemOperand(MLD->getPointerInfo(),
6930                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6931                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6932
6933     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6934                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6935
6936     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6937                                      MLD->isExpandingLoad());
6938
6939     MMO = DAG.getMachineFunction().
6940     getMachineMemOperand(MLD->getPointerInfo(),
6941                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6942                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6943
6944     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6945                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6946
6947     AddToWorklist(Lo.getNode());
6948     AddToWorklist(Hi.getNode());
6949
6950     // Build a factor node to remember that this load is independent of the
6951     // other one.
6952     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6953                         Hi.getValue(1));
6954
6955     // Legalized the chain result - switch anything that used the old chain to
6956     // use the new one.
6957     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6958
6959     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6960
6961     SDValue RetOps[] = { LoadRes, Chain };
6962     return DAG.getMergeValues(RetOps, DL);
6963   }
6964   return SDValue();
6965 }
6966
6967 /// A vector select of 2 constant vectors can be simplified to math/logic to
6968 /// avoid a variable select instruction and possibly avoid constant loads.
6969 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
6970   SDValue Cond = N->getOperand(0);
6971   SDValue N1 = N->getOperand(1);
6972   SDValue N2 = N->getOperand(2);
6973   EVT VT = N->getValueType(0);
6974   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
6975       !TLI.convertSelectOfConstantsToMath(VT) ||
6976       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
6977       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
6978     return SDValue();
6979
6980   // Check if we can use the condition value to increment/decrement a single
6981   // constant value. This simplifies a select to an add and removes a constant
6982   // load/materialization from the general case.
6983   bool AllAddOne = true;
6984   bool AllSubOne = true;
6985   unsigned Elts = VT.getVectorNumElements();
6986   for (unsigned i = 0; i != Elts; ++i) {
6987     SDValue N1Elt = N1.getOperand(i);
6988     SDValue N2Elt = N2.getOperand(i);
6989     if (N1Elt.isUndef() || N2Elt.isUndef())
6990       continue;
6991
6992     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
6993     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
6994     if (C1 != C2 + 1)
6995       AllAddOne = false;
6996     if (C1 != C2 - 1)
6997       AllSubOne = false;
6998   }
6999
7000   // Further simplifications for the extra-special cases where the constants are
7001   // all 0 or all -1 should be implemented as folds of these patterns.
7002   SDLoc DL(N);
7003   if (AllAddOne || AllSubOne) {
7004     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7005     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7006     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7007     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7008     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7009   }
7010
7011   // The general case for select-of-constants:
7012   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7013   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7014   // leave that to a machine-specific pass.
7015   return SDValue();
7016 }
7017
7018 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7019   SDValue N0 = N->getOperand(0);
7020   SDValue N1 = N->getOperand(1);
7021   SDValue N2 = N->getOperand(2);
7022   SDLoc DL(N);
7023
7024   // fold (vselect C, X, X) -> X
7025   if (N1 == N2)
7026     return N1;
7027
7028   // Canonicalize integer abs.
7029   // vselect (setg[te] X,  0),  X, -X ->
7030   // vselect (setgt    X, -1),  X, -X ->
7031   // vselect (setl[te] X,  0), -X,  X ->
7032   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7033   if (N0.getOpcode() == ISD::SETCC) {
7034     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7035     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7036     bool isAbs = false;
7037     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7038
7039     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7040          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7041         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7042       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7043     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7044              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7045       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7046
7047     if (isAbs) {
7048       EVT VT = LHS.getValueType();
7049       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7050         return DAG.getNode(ISD::ABS, DL, VT, LHS);
7051
7052       SDValue Shift = DAG.getNode(
7053           ISD::SRA, DL, VT, LHS,
7054           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7055       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7056       AddToWorklist(Shift.getNode());
7057       AddToWorklist(Add.getNode());
7058       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7059     }
7060   }
7061
7062   if (SimplifySelectOps(N, N1, N2))
7063     return SDValue(N, 0);  // Don't revisit N.
7064
7065   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7066   if (ISD::isBuildVectorAllOnes(N0.getNode()))
7067     return N1;
7068   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7069   if (ISD::isBuildVectorAllZeros(N0.getNode()))
7070     return N2;
7071
7072   // The ConvertSelectToConcatVector function is assuming both the above
7073   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7074   // and addressed.
7075   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7076       N2.getOpcode() == ISD::CONCAT_VECTORS &&
7077       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7078     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7079       return CV;
7080   }
7081
7082   if (SDValue V = foldVSelectOfConstants(N))
7083     return V;
7084
7085   return SDValue();
7086 }
7087
7088 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7089   SDValue N0 = N->getOperand(0);
7090   SDValue N1 = N->getOperand(1);
7091   SDValue N2 = N->getOperand(2);
7092   SDValue N3 = N->getOperand(3);
7093   SDValue N4 = N->getOperand(4);
7094   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7095
7096   // fold select_cc lhs, rhs, x, x, cc -> x
7097   if (N2 == N3)
7098     return N2;
7099
7100   // Determine if the condition we're dealing with is constant
7101   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7102                                   CC, SDLoc(N), false)) {
7103     AddToWorklist(SCC.getNode());
7104
7105     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7106       if (!SCCC->isNullValue())
7107         return N2;    // cond always true -> true val
7108       else
7109         return N3;    // cond always false -> false val
7110     } else if (SCC->isUndef()) {
7111       // When the condition is UNDEF, just return the first operand. This is
7112       // coherent the DAG creation, no setcc node is created in this case
7113       return N2;
7114     } else if (SCC.getOpcode() == ISD::SETCC) {
7115       // Fold to a simpler select_cc
7116       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7117                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7118                          SCC.getOperand(2));
7119     }
7120   }
7121
7122   // If we can fold this based on the true/false value, do so.
7123   if (SimplifySelectOps(N, N2, N3))
7124     return SDValue(N, 0);  // Don't revisit N.
7125
7126   // fold select_cc into other things, such as min/max/abs
7127   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7128 }
7129
7130 SDValue DAGCombiner::visitSETCC(SDNode *N) {
7131   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
7132                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
7133                        SDLoc(N));
7134 }
7135
7136 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
7137   SDValue LHS = N->getOperand(0);
7138   SDValue RHS = N->getOperand(1);
7139   SDValue Carry = N->getOperand(2);
7140   SDValue Cond = N->getOperand(3);
7141
7142   // If Carry is false, fold to a regular SETCC.
7143   if (Carry.getOpcode() == ISD::CARRY_FALSE)
7144     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7145
7146   return SDValue();
7147 }
7148
7149 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7150   SDValue LHS = N->getOperand(0);
7151   SDValue RHS = N->getOperand(1);
7152   SDValue Carry = N->getOperand(2);
7153   SDValue Cond = N->getOperand(3);
7154
7155   // If Carry is false, fold to a regular SETCC.
7156   if (isNullConstant(Carry))
7157     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7158
7159   return SDValue();
7160 }
7161
7162 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7163 /// a build_vector of constants.
7164 /// This function is called by the DAGCombiner when visiting sext/zext/aext
7165 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7166 /// Vector extends are not folded if operations are legal; this is to
7167 /// avoid introducing illegal build_vector dag nodes.
7168 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7169                                          SelectionDAG &DAG, bool LegalTypes,
7170                                          bool LegalOperations) {
7171   unsigned Opcode = N->getOpcode();
7172   SDValue N0 = N->getOperand(0);
7173   EVT VT = N->getValueType(0);
7174
7175   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
7176          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7177          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7178          && "Expected EXTEND dag node in input!");
7179
7180   // fold (sext c1) -> c1
7181   // fold (zext c1) -> c1
7182   // fold (aext c1) -> c1
7183   if (isa<ConstantSDNode>(N0))
7184     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7185
7186   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7187   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7188   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7189   EVT SVT = VT.getScalarType();
7190   if (!(VT.isVector() &&
7191       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7192       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7193     return nullptr;
7194
7195   // We can fold this node into a build_vector.
7196   unsigned VTBits = SVT.getSizeInBits();
7197   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7198   SmallVector<SDValue, 8> Elts;
7199   unsigned NumElts = VT.getVectorNumElements();
7200   SDLoc DL(N);
7201
7202   for (unsigned i=0; i != NumElts; ++i) {
7203     SDValue Op = N0->getOperand(i);
7204     if (Op->isUndef()) {
7205       Elts.push_back(DAG.getUNDEF(SVT));
7206       continue;
7207     }
7208
7209     SDLoc DL(Op);
7210     // Get the constant value and if needed trunc it to the size of the type.
7211     // Nodes like build_vector might have constants wider than the scalar type.
7212     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7213     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7214       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7215     else
7216       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7217   }
7218
7219   return DAG.getBuildVector(VT, DL, Elts).getNode();
7220 }
7221
7222 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7223 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7224 // transformation. Returns true if extension are possible and the above
7225 // mentioned transformation is profitable.
7226 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
7227                                     unsigned ExtOpc,
7228                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7229                                     const TargetLowering &TLI) {
7230   bool HasCopyToRegUses = false;
7231   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
7232   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7233                             UE = N0.getNode()->use_end();
7234        UI != UE; ++UI) {
7235     SDNode *User = *UI;
7236     if (User == N)
7237       continue;
7238     if (UI.getUse().getResNo() != N0.getResNo())
7239       continue;
7240     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7241     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7242       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7243       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7244         // Sign bits will be lost after a zext.
7245         return false;
7246       bool Add = false;
7247       for (unsigned i = 0; i != 2; ++i) {
7248         SDValue UseOp = User->getOperand(i);
7249         if (UseOp == N0)
7250           continue;
7251         if (!isa<ConstantSDNode>(UseOp))
7252           return false;
7253         Add = true;
7254       }
7255       if (Add)
7256         ExtendNodes.push_back(User);
7257       continue;
7258     }
7259     // If truncates aren't free and there are users we can't
7260     // extend, it isn't worthwhile.
7261     if (!isTruncFree)
7262       return false;
7263     // Remember if this value is live-out.
7264     if (User->getOpcode() == ISD::CopyToReg)
7265       HasCopyToRegUses = true;
7266   }
7267
7268   if (HasCopyToRegUses) {
7269     bool BothLiveOut = false;
7270     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7271          UI != UE; ++UI) {
7272       SDUse &Use = UI.getUse();
7273       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7274         BothLiveOut = true;
7275         break;
7276       }
7277     }
7278     if (BothLiveOut)
7279       // Both unextended and extended values are live out. There had better be
7280       // a good reason for the transformation.
7281       return ExtendNodes.size();
7282   }
7283   return true;
7284 }
7285
7286 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7287                                   SDValue Trunc, SDValue ExtLoad,
7288                                   const SDLoc &DL, ISD::NodeType ExtType) {
7289   // Extend SetCC uses if necessary.
7290   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7291     SDNode *SetCC = SetCCs[i];
7292     SmallVector<SDValue, 4> Ops;
7293
7294     for (unsigned j = 0; j != 2; ++j) {
7295       SDValue SOp = SetCC->getOperand(j);
7296       if (SOp == Trunc)
7297         Ops.push_back(ExtLoad);
7298       else
7299         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7300     }
7301
7302     Ops.push_back(SetCC->getOperand(2));
7303     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7304   }
7305 }
7306
7307 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7308 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7309   SDValue N0 = N->getOperand(0);
7310   EVT DstVT = N->getValueType(0);
7311   EVT SrcVT = N0.getValueType();
7312
7313   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7314           N->getOpcode() == ISD::ZERO_EXTEND) &&
7315          "Unexpected node type (not an extend)!");
7316
7317   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7318   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7319   //   (v8i32 (sext (v8i16 (load x))))
7320   // into:
7321   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7322   //                          (v4i32 (sextload (x + 16)))))
7323   // Where uses of the original load, i.e.:
7324   //   (v8i16 (load x))
7325   // are replaced with:
7326   //   (v8i16 (truncate
7327   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7328   //                            (v4i32 (sextload (x + 16)))))))
7329   //
7330   // This combine is only applicable to illegal, but splittable, vectors.
7331   // All legal types, and illegal non-vector types, are handled elsewhere.
7332   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7333   //
7334   if (N0->getOpcode() != ISD::LOAD)
7335     return SDValue();
7336
7337   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7338
7339   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7340       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7341       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7342     return SDValue();
7343
7344   SmallVector<SDNode *, 4> SetCCs;
7345   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7346     return SDValue();
7347
7348   ISD::LoadExtType ExtType =
7349       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7350
7351   // Try to split the vector types to get down to legal types.
7352   EVT SplitSrcVT = SrcVT;
7353   EVT SplitDstVT = DstVT;
7354   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7355          SplitSrcVT.getVectorNumElements() > 1) {
7356     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7357     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7358   }
7359
7360   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7361     return SDValue();
7362
7363   SDLoc DL(N);
7364   const unsigned NumSplits =
7365       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7366   const unsigned Stride = SplitSrcVT.getStoreSize();
7367   SmallVector<SDValue, 4> Loads;
7368   SmallVector<SDValue, 4> Chains;
7369
7370   SDValue BasePtr = LN0->getBasePtr();
7371   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7372     const unsigned Offset = Idx * Stride;
7373     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7374
7375     SDValue SplitLoad = DAG.getExtLoad(
7376         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7377         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7378         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7379
7380     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7381                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7382
7383     Loads.push_back(SplitLoad.getValue(0));
7384     Chains.push_back(SplitLoad.getValue(1));
7385   }
7386
7387   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7388   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7389
7390   // Simplify TF.
7391   AddToWorklist(NewChain.getNode());
7392
7393   CombineTo(N, NewValue);
7394
7395   // Replace uses of the original load (before extension)
7396   // with a truncate of the concatenated sextloaded vectors.
7397   SDValue Trunc =
7398       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7399   CombineTo(N0.getNode(), Trunc, NewChain);
7400   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7401                   (ISD::NodeType)N->getOpcode());
7402   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7403 }
7404
7405 /// If we're narrowing or widening the result of a vector select and the final
7406 /// size is the same size as a setcc (compare) feeding the select, then try to
7407 /// apply the cast operation to the select's operands because matching vector
7408 /// sizes for a select condition and other operands should be more efficient.
7409 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7410   unsigned CastOpcode = Cast->getOpcode();
7411   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7412           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7413           CastOpcode == ISD::FP_ROUND) &&
7414          "Unexpected opcode for vector select narrowing/widening");
7415
7416   // We only do this transform before legal ops because the pattern may be
7417   // obfuscated by target-specific operations after legalization. Do not create
7418   // an illegal select op, however, because that may be difficult to lower.
7419   EVT VT = Cast->getValueType(0);
7420   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7421     return SDValue();
7422
7423   SDValue VSel = Cast->getOperand(0);
7424   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7425       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7426     return SDValue();
7427
7428   // Does the setcc have the same vector size as the casted select?
7429   SDValue SetCC = VSel.getOperand(0);
7430   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7431   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7432     return SDValue();
7433
7434   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7435   SDValue A = VSel.getOperand(1);
7436   SDValue B = VSel.getOperand(2);
7437   SDValue CastA, CastB;
7438   SDLoc DL(Cast);
7439   if (CastOpcode == ISD::FP_ROUND) {
7440     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7441     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7442     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7443   } else {
7444     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7445     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7446   }
7447   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7448 }
7449
7450 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7451   SDValue N0 = N->getOperand(0);
7452   EVT VT = N->getValueType(0);
7453   SDLoc DL(N);
7454
7455   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7456                                               LegalOperations))
7457     return SDValue(Res, 0);
7458
7459   // fold (sext (sext x)) -> (sext x)
7460   // fold (sext (aext x)) -> (sext x)
7461   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7462     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7463
7464   if (N0.getOpcode() == ISD::TRUNCATE) {
7465     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7466     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7467     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7468       SDNode *oye = N0.getOperand(0).getNode();
7469       if (NarrowLoad.getNode() != N0.getNode()) {
7470         CombineTo(N0.getNode(), NarrowLoad);
7471         // CombineTo deleted the truncate, if needed, but not what's under it.
7472         AddToWorklist(oye);
7473       }
7474       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7475     }
7476
7477     // See if the value being truncated is already sign extended.  If so, just
7478     // eliminate the trunc/sext pair.
7479     SDValue Op = N0.getOperand(0);
7480     unsigned OpBits   = Op.getScalarValueSizeInBits();
7481     unsigned MidBits  = N0.getScalarValueSizeInBits();
7482     unsigned DestBits = VT.getScalarSizeInBits();
7483     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7484
7485     if (OpBits == DestBits) {
7486       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7487       // bits, it is already ready.
7488       if (NumSignBits > DestBits-MidBits)
7489         return Op;
7490     } else if (OpBits < DestBits) {
7491       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7492       // bits, just sext from i32.
7493       if (NumSignBits > OpBits-MidBits)
7494         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7495     } else {
7496       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7497       // bits, just truncate to i32.
7498       if (NumSignBits > OpBits-MidBits)
7499         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7500     }
7501
7502     // fold (sext (truncate x)) -> (sextinreg x).
7503     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7504                                                  N0.getValueType())) {
7505       if (OpBits < DestBits)
7506         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7507       else if (OpBits > DestBits)
7508         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7509       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7510                          DAG.getValueType(N0.getValueType()));
7511     }
7512   }
7513
7514   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7515   // Only generate vector extloads when 1) they're legal, and 2) they are
7516   // deemed desirable by the target.
7517   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7518       ((!LegalOperations && !VT.isVector() &&
7519         !cast<LoadSDNode>(N0)->isVolatile()) ||
7520        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7521     bool DoXform = true;
7522     SmallVector<SDNode*, 4> SetCCs;
7523     if (!N0.hasOneUse())
7524       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7525     if (VT.isVector())
7526       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7527     if (DoXform) {
7528       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7529       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7530                                        LN0->getBasePtr(), N0.getValueType(),
7531                                        LN0->getMemOperand());
7532       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7533                                   N0.getValueType(), ExtLoad);
7534       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7535       // If the load value is used only by N, replace it via CombineTo N.
7536       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7537       CombineTo(N, ExtLoad);
7538       if (NoReplaceTrunc)
7539         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7540       else
7541         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7542       return SDValue(N, 0);
7543     }
7544   }
7545
7546   // fold (sext (load x)) to multiple smaller sextloads.
7547   // Only on illegal but splittable vectors.
7548   if (SDValue ExtLoad = CombineExtLoad(N))
7549     return ExtLoad;
7550
7551   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7552   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7553   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7554       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7555     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7556     EVT MemVT = LN0->getMemoryVT();
7557     if ((!LegalOperations && !LN0->isVolatile()) ||
7558         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7559       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7560                                        LN0->getBasePtr(), MemVT,
7561                                        LN0->getMemOperand());
7562       CombineTo(N, ExtLoad);
7563       CombineTo(N0.getNode(),
7564                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7565                             N0.getValueType(), ExtLoad),
7566                 ExtLoad.getValue(1));
7567       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7568     }
7569   }
7570
7571   // fold (sext (and/or/xor (load x), cst)) ->
7572   //      (and/or/xor (sextload x), (sext cst))
7573   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7574        N0.getOpcode() == ISD::XOR) &&
7575       isa<LoadSDNode>(N0.getOperand(0)) &&
7576       N0.getOperand(1).getOpcode() == ISD::Constant &&
7577       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7578       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7579     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7580     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7581       bool DoXform = true;
7582       SmallVector<SDNode*, 4> SetCCs;
7583       if (!N0.hasOneUse())
7584         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7585                                           SetCCs, TLI);
7586       if (DoXform) {
7587         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7588                                          LN0->getChain(), LN0->getBasePtr(),
7589                                          LN0->getMemoryVT(),
7590                                          LN0->getMemOperand());
7591         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7592         Mask = Mask.sext(VT.getSizeInBits());
7593         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7594                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7595         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7596                                     SDLoc(N0.getOperand(0)),
7597                                     N0.getOperand(0).getValueType(), ExtLoad);
7598         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7599         bool NoReplaceTruncAnd = !N0.hasOneUse();
7600         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7601         CombineTo(N, And);
7602         // If N0 has multiple uses, change other uses as well.
7603         if (NoReplaceTruncAnd) {
7604           SDValue TruncAnd =
7605               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7606           CombineTo(N0.getNode(), TruncAnd);
7607         }
7608         if (NoReplaceTrunc)
7609           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7610         else
7611           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7612         return SDValue(N,0); // Return N so it doesn't get rechecked!
7613       }
7614     }
7615   }
7616
7617   if (N0.getOpcode() == ISD::SETCC) {
7618     SDValue N00 = N0.getOperand(0);
7619     SDValue N01 = N0.getOperand(1);
7620     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7621     EVT N00VT = N0.getOperand(0).getValueType();
7622
7623     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7624     // Only do this before legalize for now.
7625     if (VT.isVector() && !LegalOperations &&
7626         TLI.getBooleanContents(N00VT) ==
7627             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7628       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7629       // of the same size as the compared operands. Only optimize sext(setcc())
7630       // if this is the case.
7631       EVT SVT = getSetCCResultType(N00VT);
7632
7633       // We know that the # elements of the results is the same as the
7634       // # elements of the compare (and the # elements of the compare result
7635       // for that matter).  Check to see that they are the same size.  If so,
7636       // we know that the element size of the sext'd result matches the
7637       // element size of the compare operands.
7638       if (VT.getSizeInBits() == SVT.getSizeInBits())
7639         return DAG.getSetCC(DL, VT, N00, N01, CC);
7640
7641       // If the desired elements are smaller or larger than the source
7642       // elements, we can use a matching integer vector type and then
7643       // truncate/sign extend.
7644       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7645       if (SVT == MatchingVecType) {
7646         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7647         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7648       }
7649     }
7650
7651     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7652     // Here, T can be 1 or -1, depending on the type of the setcc and
7653     // getBooleanContents().
7654     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7655
7656     // To determine the "true" side of the select, we need to know the high bit
7657     // of the value returned by the setcc if it evaluates to true.
7658     // If the type of the setcc is i1, then the true case of the select is just
7659     // sext(i1 1), that is, -1.
7660     // If the type of the setcc is larger (say, i8) then the value of the high
7661     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7662     // of the appropriate width.
7663     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7664                                            : TLI.getConstTrueVal(DAG, VT, DL);
7665     SDValue Zero = DAG.getConstant(0, DL, VT);
7666     if (SDValue SCC =
7667             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7668       return SCC;
7669
7670     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7671       EVT SetCCVT = getSetCCResultType(N00VT);
7672       // Don't do this transform for i1 because there's a select transform
7673       // that would reverse it.
7674       // TODO: We should not do this transform at all without a target hook
7675       // because a sext is likely cheaper than a select?
7676       if (SetCCVT.getScalarSizeInBits() != 1 &&
7677           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7678         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7679         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7680       }
7681     }
7682   }
7683
7684   // fold (sext x) -> (zext x) if the sign bit is known zero.
7685   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7686       DAG.SignBitIsZero(N0))
7687     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7688
7689   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7690     return NewVSel;
7691
7692   return SDValue();
7693 }
7694
7695 // isTruncateOf - If N is a truncate of some other value, return true, record
7696 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7697 // This function computes KnownBits to avoid a duplicated call to
7698 // computeKnownBits in the caller.
7699 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7700                          KnownBits &Known) {
7701   if (N->getOpcode() == ISD::TRUNCATE) {
7702     Op = N->getOperand(0);
7703     DAG.computeKnownBits(Op, Known);
7704     return true;
7705   }
7706
7707   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7708       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7709     return false;
7710
7711   SDValue Op0 = N->getOperand(0);
7712   SDValue Op1 = N->getOperand(1);
7713   assert(Op0.getValueType() == Op1.getValueType());
7714
7715   if (isNullConstant(Op0))
7716     Op = Op1;
7717   else if (isNullConstant(Op1))
7718     Op = Op0;
7719   else
7720     return false;
7721
7722   DAG.computeKnownBits(Op, Known);
7723
7724   if (!(Known.Zero | 1).isAllOnesValue())
7725     return false;
7726
7727   return true;
7728 }
7729
7730 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7731   SDValue N0 = N->getOperand(0);
7732   EVT VT = N->getValueType(0);
7733
7734   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7735                                               LegalOperations))
7736     return SDValue(Res, 0);
7737
7738   // fold (zext (zext x)) -> (zext x)
7739   // fold (zext (aext x)) -> (zext x)
7740   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7741     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7742                        N0.getOperand(0));
7743
7744   // fold (zext (truncate x)) -> (zext x) or
7745   //      (zext (truncate x)) -> (truncate x)
7746   // This is valid when the truncated bits of x are already zero.
7747   // FIXME: We should extend this to work for vectors too.
7748   SDValue Op;
7749   KnownBits Known;
7750   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7751     APInt TruncatedBits =
7752       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7753       APInt(Op.getValueSizeInBits(), 0) :
7754       APInt::getBitsSet(Op.getValueSizeInBits(),
7755                         N0.getValueSizeInBits(),
7756                         std::min(Op.getValueSizeInBits(),
7757                                  VT.getSizeInBits()));
7758     if (TruncatedBits.isSubsetOf(Known.Zero))
7759       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7760   }
7761
7762   // fold (zext (truncate x)) -> (and x, mask)
7763   if (N0.getOpcode() == ISD::TRUNCATE) {
7764     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7765     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7766     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7767       SDNode *oye = N0.getOperand(0).getNode();
7768       if (NarrowLoad.getNode() != N0.getNode()) {
7769         CombineTo(N0.getNode(), NarrowLoad);
7770         // CombineTo deleted the truncate, if needed, but not what's under it.
7771         AddToWorklist(oye);
7772       }
7773       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7774     }
7775
7776     EVT SrcVT = N0.getOperand(0).getValueType();
7777     EVT MinVT = N0.getValueType();
7778
7779     // Try to mask before the extension to avoid having to generate a larger mask,
7780     // possibly over several sub-vectors.
7781     if (SrcVT.bitsLT(VT)) {
7782       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7783                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7784         SDValue Op = N0.getOperand(0);
7785         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7786         AddToWorklist(Op.getNode());
7787         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7788       }
7789     }
7790
7791     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7792       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7793       AddToWorklist(Op.getNode());
7794       SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7795       // We may safely transfer the debug info describing the truncate node over
7796       // to the equivalent and operation.
7797       DAG.transferDbgValues(N0, And);
7798       return And;
7799     }
7800   }
7801
7802   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7803   // if either of the casts is not free.
7804   if (N0.getOpcode() == ISD::AND &&
7805       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7806       N0.getOperand(1).getOpcode() == ISD::Constant &&
7807       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7808                            N0.getValueType()) ||
7809        !TLI.isZExtFree(N0.getValueType(), VT))) {
7810     SDValue X = N0.getOperand(0).getOperand(0);
7811     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7812     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7813     Mask = Mask.zext(VT.getSizeInBits());
7814     SDLoc DL(N);
7815     return DAG.getNode(ISD::AND, DL, VT,
7816                        X, DAG.getConstant(Mask, DL, VT));
7817   }
7818
7819   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7820   // Only generate vector extloads when 1) they're legal, and 2) they are
7821   // deemed desirable by the target.
7822   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7823       ((!LegalOperations && !VT.isVector() &&
7824         !cast<LoadSDNode>(N0)->isVolatile()) ||
7825        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7826     bool DoXform = true;
7827     SmallVector<SDNode*, 4> SetCCs;
7828     if (!N0.hasOneUse())
7829       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7830     if (VT.isVector())
7831       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7832     if (DoXform) {
7833       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7834       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7835                                        LN0->getChain(),
7836                                        LN0->getBasePtr(), N0.getValueType(),
7837                                        LN0->getMemOperand());
7838
7839       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7840                                   N0.getValueType(), ExtLoad);
7841       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7842       // If the load value is used only by N, replace it via CombineTo N.
7843       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7844       CombineTo(N, ExtLoad);
7845       if (NoReplaceTrunc)
7846         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7847       else
7848         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7849       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7850     }
7851   }
7852
7853   // fold (zext (load x)) to multiple smaller zextloads.
7854   // Only on illegal but splittable vectors.
7855   if (SDValue ExtLoad = CombineExtLoad(N))
7856     return ExtLoad;
7857
7858   // fold (zext (and/or/xor (load x), cst)) ->
7859   //      (and/or/xor (zextload x), (zext cst))
7860   // Unless (and (load x) cst) will match as a zextload already and has
7861   // additional users.
7862   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7863        N0.getOpcode() == ISD::XOR) &&
7864       isa<LoadSDNode>(N0.getOperand(0)) &&
7865       N0.getOperand(1).getOpcode() == ISD::Constant &&
7866       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7867       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7868     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7869     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7870       bool DoXform = true;
7871       SmallVector<SDNode*, 4> SetCCs;
7872       if (!N0.hasOneUse()) {
7873         if (N0.getOpcode() == ISD::AND) {
7874           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7875           EVT LoadResultTy = AndC->getValueType(0);
7876           EVT ExtVT;
7877           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT))
7878             DoXform = false;
7879         }
7880         if (DoXform)
7881           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7882                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7883       }
7884       if (DoXform) {
7885         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7886                                          LN0->getChain(), LN0->getBasePtr(),
7887                                          LN0->getMemoryVT(),
7888                                          LN0->getMemOperand());
7889         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7890         Mask = Mask.zext(VT.getSizeInBits());
7891         SDLoc DL(N);
7892         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7893                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7894         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7895                                     SDLoc(N0.getOperand(0)),
7896                                     N0.getOperand(0).getValueType(), ExtLoad);
7897         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7898         bool NoReplaceTruncAnd = !N0.hasOneUse();
7899         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7900         CombineTo(N, And);
7901         // If N0 has multiple uses, change other uses as well.
7902         if (NoReplaceTruncAnd) {
7903           SDValue TruncAnd =
7904               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7905           CombineTo(N0.getNode(), TruncAnd);
7906         }
7907         if (NoReplaceTrunc)
7908           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7909         else
7910           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7911         return SDValue(N,0); // Return N so it doesn't get rechecked!
7912       }
7913     }
7914   }
7915
7916   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7917   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7918   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7919       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7920     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7921     EVT MemVT = LN0->getMemoryVT();
7922     if ((!LegalOperations && !LN0->isVolatile()) ||
7923         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7924       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7925                                        LN0->getChain(),
7926                                        LN0->getBasePtr(), MemVT,
7927                                        LN0->getMemOperand());
7928       CombineTo(N, ExtLoad);
7929       CombineTo(N0.getNode(),
7930                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7931                             ExtLoad),
7932                 ExtLoad.getValue(1));
7933       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7934     }
7935   }
7936
7937   if (N0.getOpcode() == ISD::SETCC) {
7938     // Only do this before legalize for now.
7939     if (!LegalOperations && VT.isVector() &&
7940         N0.getValueType().getVectorElementType() == MVT::i1) {
7941       EVT N00VT = N0.getOperand(0).getValueType();
7942       if (getSetCCResultType(N00VT) == N0.getValueType())
7943         return SDValue();
7944
7945       // We know that the # elements of the results is the same as the #
7946       // elements of the compare (and the # elements of the compare result for
7947       // that matter). Check to see that they are the same size. If so, we know
7948       // that the element size of the sext'd result matches the element size of
7949       // the compare operands.
7950       SDLoc DL(N);
7951       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7952       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7953         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7954         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7955                                      N0.getOperand(1), N0.getOperand(2));
7956         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7957       }
7958
7959       // If the desired elements are smaller or larger than the source
7960       // elements we can use a matching integer vector type and then
7961       // truncate/sign extend.
7962       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
7963       SDValue VsetCC =
7964           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7965                       N0.getOperand(1), N0.getOperand(2));
7966       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7967                          VecOnes);
7968     }
7969
7970     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7971     SDLoc DL(N);
7972     if (SDValue SCC = SimplifySelectCC(
7973             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7974             DAG.getConstant(0, DL, VT),
7975             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7976       return SCC;
7977   }
7978
7979   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7980   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7981       isa<ConstantSDNode>(N0.getOperand(1)) &&
7982       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7983       N0.hasOneUse()) {
7984     SDValue ShAmt = N0.getOperand(1);
7985     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7986     if (N0.getOpcode() == ISD::SHL) {
7987       SDValue InnerZExt = N0.getOperand(0);
7988       // If the original shl may be shifting out bits, do not perform this
7989       // transformation.
7990       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7991         InnerZExt.getOperand(0).getValueSizeInBits();
7992       if (ShAmtVal > KnownZeroBits)
7993         return SDValue();
7994     }
7995
7996     SDLoc DL(N);
7997
7998     // Ensure that the shift amount is wide enough for the shifted value.
7999     if (VT.getSizeInBits() >= 256)
8000       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8001
8002     return DAG.getNode(N0.getOpcode(), DL, VT,
8003                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8004                        ShAmt);
8005   }
8006
8007   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8008     return NewVSel;
8009
8010   return SDValue();
8011 }
8012
8013 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8014   SDValue N0 = N->getOperand(0);
8015   EVT VT = N->getValueType(0);
8016
8017   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8018                                               LegalOperations))
8019     return SDValue(Res, 0);
8020
8021   // fold (aext (aext x)) -> (aext x)
8022   // fold (aext (zext x)) -> (zext x)
8023   // fold (aext (sext x)) -> (sext x)
8024   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
8025       N0.getOpcode() == ISD::ZERO_EXTEND ||
8026       N0.getOpcode() == ISD::SIGN_EXTEND)
8027     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8028
8029   // fold (aext (truncate (load x))) -> (aext (smaller load x))
8030   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8031   if (N0.getOpcode() == ISD::TRUNCATE) {
8032     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8033       SDNode *oye = N0.getOperand(0).getNode();
8034       if (NarrowLoad.getNode() != N0.getNode()) {
8035         CombineTo(N0.getNode(), NarrowLoad);
8036         // CombineTo deleted the truncate, if needed, but not what's under it.
8037         AddToWorklist(oye);
8038       }
8039       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8040     }
8041   }
8042
8043   // fold (aext (truncate x))
8044   if (N0.getOpcode() == ISD::TRUNCATE)
8045     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8046
8047   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8048   // if the trunc is not free.
8049   if (N0.getOpcode() == ISD::AND &&
8050       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8051       N0.getOperand(1).getOpcode() == ISD::Constant &&
8052       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8053                           N0.getValueType())) {
8054     SDLoc DL(N);
8055     SDValue X = N0.getOperand(0).getOperand(0);
8056     X = DAG.getAnyExtOrTrunc(X, DL, VT);
8057     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8058     Mask = Mask.zext(VT.getSizeInBits());
8059     return DAG.getNode(ISD::AND, DL, VT,
8060                        X, DAG.getConstant(Mask, DL, VT));
8061   }
8062
8063   // fold (aext (load x)) -> (aext (truncate (extload x)))
8064   // None of the supported targets knows how to perform load and any_ext
8065   // on vectors in one instruction.  We only perform this transformation on
8066   // scalars.
8067   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8068       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8069       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8070     bool DoXform = true;
8071     SmallVector<SDNode*, 4> SetCCs;
8072     if (!N0.hasOneUse())
8073       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
8074     if (DoXform) {
8075       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8076       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8077                                        LN0->getChain(),
8078                                        LN0->getBasePtr(), N0.getValueType(),
8079                                        LN0->getMemOperand());
8080       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8081                                   N0.getValueType(), ExtLoad);
8082       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
8083                       ISD::ANY_EXTEND);
8084       // If the load value is used only by N, replace it via CombineTo N.
8085       bool NoReplaceTrunc = N0.hasOneUse();
8086       CombineTo(N, ExtLoad);
8087       if (NoReplaceTrunc)
8088         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8089       else
8090         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8091       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8092     }
8093   }
8094
8095   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8096   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8097   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
8098   if (N0.getOpcode() == ISD::LOAD &&
8099       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8100       N0.hasOneUse()) {
8101     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8102     ISD::LoadExtType ExtType = LN0->getExtensionType();
8103     EVT MemVT = LN0->getMemoryVT();
8104     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8105       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8106                                        VT, LN0->getChain(), LN0->getBasePtr(),
8107                                        MemVT, LN0->getMemOperand());
8108       CombineTo(N, ExtLoad);
8109       CombineTo(N0.getNode(),
8110                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8111                             N0.getValueType(), ExtLoad),
8112                 ExtLoad.getValue(1));
8113       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8114     }
8115   }
8116
8117   if (N0.getOpcode() == ISD::SETCC) {
8118     // For vectors:
8119     // aext(setcc) -> vsetcc
8120     // aext(setcc) -> truncate(vsetcc)
8121     // aext(setcc) -> aext(vsetcc)
8122     // Only do this before legalize for now.
8123     if (VT.isVector() && !LegalOperations) {
8124       EVT N00VT = N0.getOperand(0).getValueType();
8125       if (getSetCCResultType(N00VT) == N0.getValueType())
8126         return SDValue();
8127
8128       // We know that the # elements of the results is the same as the
8129       // # elements of the compare (and the # elements of the compare result
8130       // for that matter).  Check to see that they are the same size.  If so,
8131       // we know that the element size of the sext'd result matches the
8132       // element size of the compare operands.
8133       if (VT.getSizeInBits() == N00VT.getSizeInBits())
8134         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8135                              N0.getOperand(1),
8136                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
8137       // If the desired elements are smaller or larger than the source
8138       // elements we can use a matching integer vector type and then
8139       // truncate/any extend
8140       else {
8141         EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8142         SDValue VsetCC =
8143           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8144                         N0.getOperand(1),
8145                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
8146         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8147       }
8148     }
8149
8150     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8151     SDLoc DL(N);
8152     if (SDValue SCC = SimplifySelectCC(
8153             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8154             DAG.getConstant(0, DL, VT),
8155             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8156       return SCC;
8157   }
8158
8159   return SDValue();
8160 }
8161
8162 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8163   unsigned Opcode = N->getOpcode();
8164   SDValue N0 = N->getOperand(0);
8165   SDValue N1 = N->getOperand(1);
8166   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8167
8168   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8169   if (N0.getOpcode() == Opcode &&
8170       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8171     return N0;
8172
8173   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8174       N0.getOperand(0).getOpcode() == Opcode) {
8175     // We have an assert, truncate, assert sandwich. Make one stronger assert
8176     // by asserting on the smallest asserted type to the larger source type.
8177     // This eliminates the later assert:
8178     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8179     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8180     SDValue BigA = N0.getOperand(0);
8181     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8182     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8183            "Asserting zero/sign-extended bits to a type larger than the "
8184            "truncated destination does not provide information");
8185
8186     SDLoc DL(N);
8187     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8188     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8189     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8190                                     BigA.getOperand(0), MinAssertVTVal);
8191     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8192   }
8193
8194   return SDValue();
8195 }
8196
8197 /// If the result of a wider load is shifted to right of N  bits and then
8198 /// truncated to a narrower type and where N is a multiple of number of bits of
8199 /// the narrower type, transform it to a narrower load from address + N / num of
8200 /// bits of new type. Also narrow the load if the result is masked with an AND
8201 /// to effectively produce a smaller type. If the result is to be extended, also
8202 /// fold the extension to form a extending load.
8203 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8204   unsigned Opc = N->getOpcode();
8205
8206   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8207   SDValue N0 = N->getOperand(0);
8208   EVT VT = N->getValueType(0);
8209   EVT ExtVT = VT;
8210
8211   // This transformation isn't valid for vector loads.
8212   if (VT.isVector())
8213     return SDValue();
8214
8215   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8216   // extended to VT.
8217   if (Opc == ISD::SIGN_EXTEND_INREG) {
8218     ExtType = ISD::SEXTLOAD;
8219     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8220   } else if (Opc == ISD::SRL) {
8221     // Another special-case: SRL is basically zero-extending a narrower value,
8222     // or it maybe shifting a higher subword, half or byte into the lowest
8223     // bits.
8224     ExtType = ISD::ZEXTLOAD;
8225     N0 = SDValue(N, 0);
8226
8227     auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8228     auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8229     if (!N01 || !LN0)
8230       return SDValue();
8231
8232     uint64_t ShiftAmt = N01->getZExtValue();
8233     uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8234     if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8235       ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8236     else
8237       ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8238                                 VT.getSizeInBits() - ShiftAmt);
8239   } else if (Opc == ISD::AND) {
8240     // An AND with a constant mask is the same as a truncate + zero-extend.
8241     auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8242     if (!AndC || !AndC->getAPIntValue().isMask())
8243       return SDValue();
8244
8245     unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8246     ExtType = ISD::ZEXTLOAD;
8247     ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8248   }
8249
8250   unsigned ShAmt = 0;
8251   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8252     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8253       ShAmt = N01->getZExtValue();
8254       unsigned EVTBits = ExtVT.getSizeInBits();
8255       // Is the shift amount a multiple of size of VT?
8256       if ((ShAmt & (EVTBits-1)) == 0) {
8257         N0 = N0.getOperand(0);
8258         // Is the load width a multiple of size of VT?
8259         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8260           return SDValue();
8261       }
8262
8263       // At this point, we must have a load or else we can't do the transform.
8264       if (!isa<LoadSDNode>(N0)) return SDValue();
8265
8266       // Because a SRL must be assumed to *need* to zero-extend the high bits
8267       // (as opposed to anyext the high bits), we can't combine the zextload
8268       // lowering of SRL and an sextload.
8269       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
8270         return SDValue();
8271
8272       // If the shift amount is larger than the input type then we're not
8273       // accessing any of the loaded bytes.  If the load was a zextload/extload
8274       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8275       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
8276         return SDValue();
8277     }
8278   }
8279
8280   // If the load is shifted left (and the result isn't shifted back right),
8281   // we can fold the truncate through the shift.
8282   unsigned ShLeftAmt = 0;
8283   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8284       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8285     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8286       ShLeftAmt = N01->getZExtValue();
8287       N0 = N0.getOperand(0);
8288     }
8289   }
8290
8291   // If we haven't found a load, we can't narrow it.
8292   if (!isa<LoadSDNode>(N0))
8293     return SDValue();
8294
8295   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8296   if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt))
8297     return SDValue();
8298
8299   // For big endian targets, we need to adjust the offset to the pointer to
8300   // load the correct bytes.
8301   if (DAG.getDataLayout().isBigEndian()) {
8302     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8303     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8304     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8305   }
8306
8307   EVT PtrType = N0.getOperand(1).getValueType();
8308   uint64_t PtrOff = ShAmt / 8;
8309   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8310   SDLoc DL(LN0);
8311   // The original load itself didn't wrap, so an offset within it doesn't.
8312   SDNodeFlags Flags;
8313   Flags.setNoUnsignedWrap(true);
8314   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8315                                PtrType, LN0->getBasePtr(),
8316                                DAG.getConstant(PtrOff, DL, PtrType),
8317                                Flags);
8318   AddToWorklist(NewPtr.getNode());
8319
8320   SDValue Load;
8321   if (ExtType == ISD::NON_EXTLOAD)
8322     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8323                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8324                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8325   else
8326     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8327                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8328                           NewAlign, LN0->getMemOperand()->getFlags(),
8329                           LN0->getAAInfo());
8330
8331   // Replace the old load's chain with the new load's chain.
8332   WorklistRemover DeadNodes(*this);
8333   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8334
8335   // Shift the result left, if we've swallowed a left shift.
8336   SDValue Result = Load;
8337   if (ShLeftAmt != 0) {
8338     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8339     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8340       ShImmTy = VT;
8341     // If the shift amount is as large as the result size (but, presumably,
8342     // no larger than the source) then the useful bits of the result are
8343     // zero; we can't simply return the shortened shift, because the result
8344     // of that operation is undefined.
8345     SDLoc DL(N0);
8346     if (ShLeftAmt >= VT.getSizeInBits())
8347       Result = DAG.getConstant(0, DL, VT);
8348     else
8349       Result = DAG.getNode(ISD::SHL, DL, VT,
8350                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8351   }
8352
8353   // Return the new loaded value.
8354   return Result;
8355 }
8356
8357 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8358   SDValue N0 = N->getOperand(0);
8359   SDValue N1 = N->getOperand(1);
8360   EVT VT = N->getValueType(0);
8361   EVT EVT = cast<VTSDNode>(N1)->getVT();
8362   unsigned VTBits = VT.getScalarSizeInBits();
8363   unsigned EVTBits = EVT.getScalarSizeInBits();
8364
8365   if (N0.isUndef())
8366     return DAG.getUNDEF(VT);
8367
8368   // fold (sext_in_reg c1) -> c1
8369   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8370     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8371
8372   // If the input is already sign extended, just drop the extension.
8373   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8374     return N0;
8375
8376   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8377   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8378       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8379     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8380                        N0.getOperand(0), N1);
8381
8382   // fold (sext_in_reg (sext x)) -> (sext x)
8383   // fold (sext_in_reg (aext x)) -> (sext x)
8384   // if x is small enough.
8385   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8386     SDValue N00 = N0.getOperand(0);
8387     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8388         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8389       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8390   }
8391
8392   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8393   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8394        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8395        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8396       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8397     if (!LegalOperations ||
8398         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8399       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8400   }
8401
8402   // fold (sext_in_reg (zext x)) -> (sext x)
8403   // iff we are extending the source sign bit.
8404   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8405     SDValue N00 = N0.getOperand(0);
8406     if (N00.getScalarValueSizeInBits() == EVTBits &&
8407         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8408       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8409   }
8410
8411   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8412   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8413     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8414
8415   // fold operands of sext_in_reg based on knowledge that the top bits are not
8416   // demanded.
8417   if (SimplifyDemandedBits(SDValue(N, 0)))
8418     return SDValue(N, 0);
8419
8420   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8421   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8422   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8423     return NarrowLoad;
8424
8425   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8426   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8427   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8428   if (N0.getOpcode() == ISD::SRL) {
8429     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8430       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8431         // We can turn this into an SRA iff the input to the SRL is already sign
8432         // extended enough.
8433         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8434         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8435           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8436                              N0.getOperand(0), N0.getOperand(1));
8437       }
8438   }
8439
8440   // fold (sext_inreg (extload x)) -> (sextload x)
8441   // If sextload is not supported by target, we can only do the combine when
8442   // load has one use. Doing otherwise can block folding the extload with other
8443   // extends that the target does support.
8444   if (ISD::isEXTLoad(N0.getNode()) &&
8445       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8446       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8447       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
8448         N0.hasOneUse()) ||
8449        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8450     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8451     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8452                                      LN0->getChain(),
8453                                      LN0->getBasePtr(), EVT,
8454                                      LN0->getMemOperand());
8455     CombineTo(N, ExtLoad);
8456     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8457     AddToWorklist(ExtLoad.getNode());
8458     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8459   }
8460   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8461   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8462       N0.hasOneUse() &&
8463       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8464       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8465        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8466     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8467     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8468                                      LN0->getChain(),
8469                                      LN0->getBasePtr(), EVT,
8470                                      LN0->getMemOperand());
8471     CombineTo(N, ExtLoad);
8472     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8473     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8474   }
8475
8476   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8477   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8478     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8479                                            N0.getOperand(1), false))
8480       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8481                          BSwap, N1);
8482   }
8483
8484   return SDValue();
8485 }
8486
8487 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8488   SDValue N0 = N->getOperand(0);
8489   EVT VT = N->getValueType(0);
8490
8491   if (N0.isUndef())
8492     return DAG.getUNDEF(VT);
8493
8494   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8495                                               LegalOperations))
8496     return SDValue(Res, 0);
8497
8498   return SDValue();
8499 }
8500
8501 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8502   SDValue N0 = N->getOperand(0);
8503   EVT VT = N->getValueType(0);
8504
8505   if (N0.isUndef())
8506     return DAG.getUNDEF(VT);
8507
8508   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8509                                               LegalOperations))
8510     return SDValue(Res, 0);
8511
8512   return SDValue();
8513 }
8514
8515 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8516   SDValue N0 = N->getOperand(0);
8517   EVT VT = N->getValueType(0);
8518   bool isLE = DAG.getDataLayout().isLittleEndian();
8519
8520   // noop truncate
8521   if (N0.getValueType() == N->getValueType(0))
8522     return N0;
8523
8524   // fold (truncate (truncate x)) -> (truncate x)
8525   if (N0.getOpcode() == ISD::TRUNCATE)
8526     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8527
8528   // fold (truncate c1) -> c1
8529   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
8530     SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8531     if (C.getNode() != N)
8532       return C;
8533   }
8534
8535   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8536   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8537       N0.getOpcode() == ISD::SIGN_EXTEND ||
8538       N0.getOpcode() == ISD::ANY_EXTEND) {
8539     // if the source is smaller than the dest, we still need an extend.
8540     if (N0.getOperand(0).getValueType().bitsLT(VT))
8541       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8542     // if the source is larger than the dest, than we just need the truncate.
8543     if (N0.getOperand(0).getValueType().bitsGT(VT))
8544       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8545     // if the source and dest are the same type, we can drop both the extend
8546     // and the truncate.
8547     return N0.getOperand(0);
8548   }
8549
8550   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8551   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8552     return SDValue();
8553
8554   // Fold extract-and-trunc into a narrow extract. For example:
8555   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8556   //   i32 y = TRUNCATE(i64 x)
8557   //        -- becomes --
8558   //   v16i8 b = BITCAST (v2i64 val)
8559   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8560   //
8561   // Note: We only run this optimization after type legalization (which often
8562   // creates this pattern) and before operation legalization after which
8563   // we need to be more careful about the vector instructions that we generate.
8564   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8565       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8566     EVT VecTy = N0.getOperand(0).getValueType();
8567     EVT ExTy = N0.getValueType();
8568     EVT TrTy = N->getValueType(0);
8569
8570     unsigned NumElem = VecTy.getVectorNumElements();
8571     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8572
8573     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8574     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8575
8576     SDValue EltNo = N0->getOperand(1);
8577     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8578       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8579       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8580       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8581
8582       SDLoc DL(N);
8583       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8584                          DAG.getBitcast(NVT, N0.getOperand(0)),
8585                          DAG.getConstant(Index, DL, IndexTy));
8586     }
8587   }
8588
8589   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8590   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8591     EVT SrcVT = N0.getValueType();
8592     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8593         TLI.isTruncateFree(SrcVT, VT)) {
8594       SDLoc SL(N0);
8595       SDValue Cond = N0.getOperand(0);
8596       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8597       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8598       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8599     }
8600   }
8601
8602   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8603   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8604       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8605       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8606     SDValue Amt = N0.getOperand(1);
8607     KnownBits Known;
8608     DAG.computeKnownBits(Amt, Known);
8609     unsigned Size = VT.getScalarSizeInBits();
8610     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8611       SDLoc SL(N);
8612       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8613
8614       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8615       if (AmtVT != Amt.getValueType()) {
8616         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8617         AddToWorklist(Amt.getNode());
8618       }
8619       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8620     }
8621   }
8622
8623   // Fold a series of buildvector, bitcast, and truncate if possible.
8624   // For example fold
8625   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8626   //   (2xi32 (buildvector x, y)).
8627   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8628       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8629       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8630       N0.getOperand(0).hasOneUse()) {
8631     SDValue BuildVect = N0.getOperand(0);
8632     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8633     EVT TruncVecEltTy = VT.getVectorElementType();
8634
8635     // Check that the element types match.
8636     if (BuildVectEltTy == TruncVecEltTy) {
8637       // Now we only need to compute the offset of the truncated elements.
8638       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8639       unsigned TruncVecNumElts = VT.getVectorNumElements();
8640       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8641
8642       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8643              "Invalid number of elements");
8644
8645       SmallVector<SDValue, 8> Opnds;
8646       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8647         Opnds.push_back(BuildVect.getOperand(i));
8648
8649       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8650     }
8651   }
8652
8653   // See if we can simplify the input to this truncate through knowledge that
8654   // only the low bits are being used.
8655   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8656   // Currently we only perform this optimization on scalars because vectors
8657   // may have different active low bits.
8658   if (!VT.isVector()) {
8659     APInt Mask =
8660         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8661     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8662       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8663   }
8664
8665   // fold (truncate (load x)) -> (smaller load x)
8666   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8667   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8668     if (SDValue Reduced = ReduceLoadWidth(N))
8669       return Reduced;
8670
8671     // Handle the case where the load remains an extending load even
8672     // after truncation.
8673     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8674       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8675       if (!LN0->isVolatile() &&
8676           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8677         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8678                                          VT, LN0->getChain(), LN0->getBasePtr(),
8679                                          LN0->getMemoryVT(),
8680                                          LN0->getMemOperand());
8681         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8682         return NewLoad;
8683       }
8684     }
8685   }
8686
8687   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8688   // where ... are all 'undef'.
8689   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8690     SmallVector<EVT, 8> VTs;
8691     SDValue V;
8692     unsigned Idx = 0;
8693     unsigned NumDefs = 0;
8694
8695     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8696       SDValue X = N0.getOperand(i);
8697       if (!X.isUndef()) {
8698         V = X;
8699         Idx = i;
8700         NumDefs++;
8701       }
8702       // Stop if more than one members are non-undef.
8703       if (NumDefs > 1)
8704         break;
8705       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8706                                      VT.getVectorElementType(),
8707                                      X.getValueType().getVectorNumElements()));
8708     }
8709
8710     if (NumDefs == 0)
8711       return DAG.getUNDEF(VT);
8712
8713     if (NumDefs == 1) {
8714       assert(V.getNode() && "The single defined operand is empty!");
8715       SmallVector<SDValue, 8> Opnds;
8716       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8717         if (i != Idx) {
8718           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8719           continue;
8720         }
8721         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8722         AddToWorklist(NV.getNode());
8723         Opnds.push_back(NV);
8724       }
8725       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8726     }
8727   }
8728
8729   // Fold truncate of a bitcast of a vector to an extract of the low vector
8730   // element.
8731   //
8732   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8733   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8734     SDValue VecSrc = N0.getOperand(0);
8735     EVT SrcVT = VecSrc.getValueType();
8736     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8737         (!LegalOperations ||
8738          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8739       SDLoc SL(N);
8740
8741       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8742       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8743       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8744                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8745     }
8746   }
8747
8748   // Simplify the operands using demanded-bits information.
8749   if (!VT.isVector() &&
8750       SimplifyDemandedBits(SDValue(N, 0)))
8751     return SDValue(N, 0);
8752
8753   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8754   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8755   // When the adde's carry is not used.
8756   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8757       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8758       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8759     SDLoc SL(N);
8760     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8761     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8762     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8763     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8764   }
8765
8766   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8767     return NewVSel;
8768
8769   return SDValue();
8770 }
8771
8772 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8773   SDValue Elt = N->getOperand(i);
8774   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8775     return Elt.getNode();
8776   return Elt.getOperand(Elt.getResNo()).getNode();
8777 }
8778
8779 /// build_pair (load, load) -> load
8780 /// if load locations are consecutive.
8781 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8782   assert(N->getOpcode() == ISD::BUILD_PAIR);
8783
8784   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8785   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8786
8787   // A BUILD_PAIR is always having the least significant part in elt 0 and the
8788   // most significant part in elt 1. So when combining into one large load, we
8789   // need to consider the endianness.
8790   if (DAG.getDataLayout().isBigEndian())
8791     std::swap(LD1, LD2);
8792
8793   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8794       LD1->getAddressSpace() != LD2->getAddressSpace())
8795     return SDValue();
8796   EVT LD1VT = LD1->getValueType(0);
8797   unsigned LD1Bytes = LD1VT.getStoreSize();
8798   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8799       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8800     unsigned Align = LD1->getAlignment();
8801     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8802         VT.getTypeForEVT(*DAG.getContext()));
8803
8804     if (NewAlign <= Align &&
8805         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8806       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8807                          LD1->getPointerInfo(), Align);
8808   }
8809
8810   return SDValue();
8811 }
8812
8813 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8814   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8815   // and Lo parts; on big-endian machines it doesn't.
8816   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8817 }
8818
8819 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8820                                     const TargetLowering &TLI) {
8821   // If this is not a bitcast to an FP type or if the target doesn't have
8822   // IEEE754-compliant FP logic, we're done.
8823   EVT VT = N->getValueType(0);
8824   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8825     return SDValue();
8826
8827   // TODO: Use splat values for the constant-checking below and remove this
8828   // restriction.
8829   SDValue N0 = N->getOperand(0);
8830   EVT SourceVT = N0.getValueType();
8831   if (SourceVT.isVector())
8832     return SDValue();
8833
8834   unsigned FPOpcode;
8835   APInt SignMask;
8836   switch (N0.getOpcode()) {
8837   case ISD::AND:
8838     FPOpcode = ISD::FABS;
8839     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8840     break;
8841   case ISD::XOR:
8842     FPOpcode = ISD::FNEG;
8843     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8844     break;
8845   // TODO: ISD::OR --> ISD::FNABS?
8846   default:
8847     return SDValue();
8848   }
8849
8850   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8851   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8852   SDValue LogicOp0 = N0.getOperand(0);
8853   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8854   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8855       LogicOp0.getOpcode() == ISD::BITCAST &&
8856       LogicOp0->getOperand(0).getValueType() == VT)
8857     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8858
8859   return SDValue();
8860 }
8861
8862 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8863   SDValue N0 = N->getOperand(0);
8864   EVT VT = N->getValueType(0);
8865
8866   if (N0.isUndef())
8867     return DAG.getUNDEF(VT);
8868
8869   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8870   // Only do this before legalize, since afterward the target may be depending
8871   // on the bitconvert.
8872   // First check to see if this is all constant.
8873   if (!LegalTypes &&
8874       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8875       VT.isVector()) {
8876     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8877
8878     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8879     assert(!DestEltVT.isVector() &&
8880            "Element type of vector ValueType must not be vector!");
8881     if (isSimple)
8882       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8883   }
8884
8885   // If the input is a constant, let getNode fold it.
8886   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8887     // If we can't allow illegal operations, we need to check that this is just
8888     // a fp -> int or int -> conversion and that the resulting operation will
8889     // be legal.
8890     if (!LegalOperations ||
8891         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8892          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8893         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8894          TLI.isOperationLegal(ISD::Constant, VT)))
8895       return DAG.getBitcast(VT, N0);
8896   }
8897
8898   // (conv (conv x, t1), t2) -> (conv x, t2)
8899   if (N0.getOpcode() == ISD::BITCAST)
8900     return DAG.getBitcast(VT, N0.getOperand(0));
8901
8902   // fold (conv (load x)) -> (load (conv*)x)
8903   // If the resultant load doesn't need a higher alignment than the original!
8904   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8905       // Do not change the width of a volatile load.
8906       !cast<LoadSDNode>(N0)->isVolatile() &&
8907       // Do not remove the cast if the types differ in endian layout.
8908       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8909           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8910       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8911       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8912     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8913     unsigned OrigAlign = LN0->getAlignment();
8914
8915     bool Fast = false;
8916     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8917                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8918         Fast) {
8919       SDValue Load =
8920           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8921                       LN0->getPointerInfo(), OrigAlign,
8922                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8923       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8924       return Load;
8925     }
8926   }
8927
8928   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8929     return V;
8930
8931   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8932   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8933   //
8934   // For ppc_fp128:
8935   // fold (bitcast (fneg x)) ->
8936   //     flipbit = signbit
8937   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8938   //
8939   // fold (bitcast (fabs x)) ->
8940   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8941   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8942   // This often reduces constant pool loads.
8943   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8944        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8945       N0.getNode()->hasOneUse() && VT.isInteger() &&
8946       !VT.isVector() && !N0.getValueType().isVector()) {
8947     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8948     AddToWorklist(NewConv.getNode());
8949
8950     SDLoc DL(N);
8951     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8952       assert(VT.getSizeInBits() == 128);
8953       SDValue SignBit = DAG.getConstant(
8954           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8955       SDValue FlipBit;
8956       if (N0.getOpcode() == ISD::FNEG) {
8957         FlipBit = SignBit;
8958         AddToWorklist(FlipBit.getNode());
8959       } else {
8960         assert(N0.getOpcode() == ISD::FABS);
8961         SDValue Hi =
8962             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8963                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8964                                               SDLoc(NewConv)));
8965         AddToWorklist(Hi.getNode());
8966         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8967         AddToWorklist(FlipBit.getNode());
8968       }
8969       SDValue FlipBits =
8970           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8971       AddToWorklist(FlipBits.getNode());
8972       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8973     }
8974     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8975     if (N0.getOpcode() == ISD::FNEG)
8976       return DAG.getNode(ISD::XOR, DL, VT,
8977                          NewConv, DAG.getConstant(SignBit, DL, VT));
8978     assert(N0.getOpcode() == ISD::FABS);
8979     return DAG.getNode(ISD::AND, DL, VT,
8980                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8981   }
8982
8983   // fold (bitconvert (fcopysign cst, x)) ->
8984   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8985   // Note that we don't handle (copysign x, cst) because this can always be
8986   // folded to an fneg or fabs.
8987   //
8988   // For ppc_fp128:
8989   // fold (bitcast (fcopysign cst, x)) ->
8990   //     flipbit = (and (extract_element
8991   //                     (xor (bitcast cst), (bitcast x)), 0),
8992   //                    signbit)
8993   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8994   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8995       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8996       VT.isInteger() && !VT.isVector()) {
8997     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8998     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8999     if (isTypeLegal(IntXVT)) {
9000       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9001       AddToWorklist(X.getNode());
9002
9003       // If X has a different width than the result/lhs, sext it or truncate it.
9004       unsigned VTWidth = VT.getSizeInBits();
9005       if (OrigXWidth < VTWidth) {
9006         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9007         AddToWorklist(X.getNode());
9008       } else if (OrigXWidth > VTWidth) {
9009         // To get the sign bit in the right place, we have to shift it right
9010         // before truncating.
9011         SDLoc DL(X);
9012         X = DAG.getNode(ISD::SRL, DL,
9013                         X.getValueType(), X,
9014                         DAG.getConstant(OrigXWidth-VTWidth, DL,
9015                                         X.getValueType()));
9016         AddToWorklist(X.getNode());
9017         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9018         AddToWorklist(X.getNode());
9019       }
9020
9021       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9022         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9023         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9024         AddToWorklist(Cst.getNode());
9025         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9026         AddToWorklist(X.getNode());
9027         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9028         AddToWorklist(XorResult.getNode());
9029         SDValue XorResult64 = DAG.getNode(
9030             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9031             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9032                                   SDLoc(XorResult)));
9033         AddToWorklist(XorResult64.getNode());
9034         SDValue FlipBit =
9035             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9036                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9037         AddToWorklist(FlipBit.getNode());
9038         SDValue FlipBits =
9039             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9040         AddToWorklist(FlipBits.getNode());
9041         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9042       }
9043       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9044       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9045                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
9046       AddToWorklist(X.getNode());
9047
9048       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9049       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9050                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9051       AddToWorklist(Cst.getNode());
9052
9053       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9054     }
9055   }
9056
9057   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9058   if (N0.getOpcode() == ISD::BUILD_PAIR)
9059     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9060       return CombineLD;
9061
9062   // Remove double bitcasts from shuffles - this is often a legacy of
9063   // XformToShuffleWithZero being used to combine bitmaskings (of
9064   // float vectors bitcast to integer vectors) into shuffles.
9065   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9066   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9067       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9068       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9069       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9070     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9071
9072     // If operands are a bitcast, peek through if it casts the original VT.
9073     // If operands are a constant, just bitcast back to original VT.
9074     auto PeekThroughBitcast = [&](SDValue Op) {
9075       if (Op.getOpcode() == ISD::BITCAST &&
9076           Op.getOperand(0).getValueType() == VT)
9077         return SDValue(Op.getOperand(0));
9078       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9079           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9080         return DAG.getBitcast(VT, Op);
9081       return SDValue();
9082     };
9083
9084     // FIXME: If either input vector is bitcast, try to convert the shuffle to
9085     // the result type of this bitcast. This would eliminate at least one
9086     // bitcast. See the transform in InstCombine.
9087     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9088     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9089     if (!(SV0 && SV1))
9090       return SDValue();
9091
9092     int MaskScale =
9093         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9094     SmallVector<int, 8> NewMask;
9095     for (int M : SVN->getMask())
9096       for (int i = 0; i != MaskScale; ++i)
9097         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9098
9099     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9100     if (!LegalMask) {
9101       std::swap(SV0, SV1);
9102       ShuffleVectorSDNode::commuteMask(NewMask);
9103       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9104     }
9105
9106     if (LegalMask)
9107       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9108   }
9109
9110   return SDValue();
9111 }
9112
9113 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9114   EVT VT = N->getValueType(0);
9115   return CombineConsecutiveLoads(N, VT);
9116 }
9117
9118 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9119 /// operands. DstEltVT indicates the destination element value type.
9120 SDValue DAGCombiner::
9121 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9122   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9123
9124   // If this is already the right type, we're done.
9125   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9126
9127   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9128   unsigned DstBitSize = DstEltVT.getSizeInBits();
9129
9130   // If this is a conversion of N elements of one type to N elements of another
9131   // type, convert each element.  This handles FP<->INT cases.
9132   if (SrcBitSize == DstBitSize) {
9133     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9134                               BV->getValueType(0).getVectorNumElements());
9135
9136     // Due to the FP element handling below calling this routine recursively,
9137     // we can end up with a scalar-to-vector node here.
9138     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9139       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9140                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9141
9142     SmallVector<SDValue, 8> Ops;
9143     for (SDValue Op : BV->op_values()) {
9144       // If the vector element type is not legal, the BUILD_VECTOR operands
9145       // are promoted and implicitly truncated.  Make that explicit here.
9146       if (Op.getValueType() != SrcEltVT)
9147         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9148       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9149       AddToWorklist(Ops.back().getNode());
9150     }
9151     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9152   }
9153
9154   // Otherwise, we're growing or shrinking the elements.  To avoid having to
9155   // handle annoying details of growing/shrinking FP values, we convert them to
9156   // int first.
9157   if (SrcEltVT.isFloatingPoint()) {
9158     // Convert the input float vector to a int vector where the elements are the
9159     // same sizes.
9160     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9161     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9162     SrcEltVT = IntVT;
9163   }
9164
9165   // Now we know the input is an integer vector.  If the output is a FP type,
9166   // convert to integer first, then to FP of the right size.
9167   if (DstEltVT.isFloatingPoint()) {
9168     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9169     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9170
9171     // Next, convert to FP elements of the same size.
9172     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9173   }
9174
9175   SDLoc DL(BV);
9176
9177   // Okay, we know the src/dst types are both integers of differing types.
9178   // Handling growing first.
9179   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
9180   if (SrcBitSize < DstBitSize) {
9181     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9182
9183     SmallVector<SDValue, 8> Ops;
9184     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9185          i += NumInputsPerOutput) {
9186       bool isLE = DAG.getDataLayout().isLittleEndian();
9187       APInt NewBits = APInt(DstBitSize, 0);
9188       bool EltIsUndef = true;
9189       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9190         // Shift the previously computed bits over.
9191         NewBits <<= SrcBitSize;
9192         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9193         if (Op.isUndef()) continue;
9194         EltIsUndef = false;
9195
9196         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9197                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
9198       }
9199
9200       if (EltIsUndef)
9201         Ops.push_back(DAG.getUNDEF(DstEltVT));
9202       else
9203         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9204     }
9205
9206     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9207     return DAG.getBuildVector(VT, DL, Ops);
9208   }
9209
9210   // Finally, this must be the case where we are shrinking elements: each input
9211   // turns into multiple outputs.
9212   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9213   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9214                             NumOutputsPerInput*BV->getNumOperands());
9215   SmallVector<SDValue, 8> Ops;
9216
9217   for (const SDValue &Op : BV->op_values()) {
9218     if (Op.isUndef()) {
9219       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9220       continue;
9221     }
9222
9223     APInt OpVal = cast<ConstantSDNode>(Op)->
9224                   getAPIntValue().zextOrTrunc(SrcBitSize);
9225
9226     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9227       APInt ThisVal = OpVal.trunc(DstBitSize);
9228       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9229       OpVal.lshrInPlace(DstBitSize);
9230     }
9231
9232     // For big endian targets, swap the order of the pieces of each element.
9233     if (DAG.getDataLayout().isBigEndian())
9234       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9235   }
9236
9237   return DAG.getBuildVector(VT, DL, Ops);
9238 }
9239
9240 static bool isContractable(SDNode *N) {
9241   SDNodeFlags F = N->getFlags();
9242   return F.hasAllowContract() || F.hasUnsafeAlgebra();
9243 }
9244
9245 /// Try to perform FMA combining on a given FADD node.
9246 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9247   SDValue N0 = N->getOperand(0);
9248   SDValue N1 = N->getOperand(1);
9249   EVT VT = N->getValueType(0);
9250   SDLoc SL(N);
9251
9252   const TargetOptions &Options = DAG.getTarget().Options;
9253
9254   // Floating-point multiply-add with intermediate rounding.
9255   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9256
9257   // Floating-point multiply-add without intermediate rounding.
9258   bool HasFMA =
9259       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9260       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9261
9262   // No valid opcode, do not combine.
9263   if (!HasFMAD && !HasFMA)
9264     return SDValue();
9265
9266   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9267                               Options.UnsafeFPMath || HasFMAD);
9268   // If the addition is not contractable, do not combine.
9269   if (!AllowFusionGlobally && !isContractable(N))
9270     return SDValue();
9271
9272   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9273   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9274     return SDValue();
9275
9276   // Always prefer FMAD to FMA for precision.
9277   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9278   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9279
9280   // Is the node an FMUL and contractable either due to global flags or
9281   // SDNodeFlags.
9282   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9283     if (N.getOpcode() != ISD::FMUL)
9284       return false;
9285     return AllowFusionGlobally || isContractable(N.getNode());
9286   };
9287   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9288   // prefer to fold the multiply with fewer uses.
9289   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9290     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9291       std::swap(N0, N1);
9292   }
9293
9294   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9295   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9296     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9297                        N0.getOperand(0), N0.getOperand(1), N1);
9298   }
9299
9300   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9301   // Note: Commutes FADD operands.
9302   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9303     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9304                        N1.getOperand(0), N1.getOperand(1), N0);
9305   }
9306
9307   // Look through FP_EXTEND nodes to do more combining.
9308
9309   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9310   if (N0.getOpcode() == ISD::FP_EXTEND) {
9311     SDValue N00 = N0.getOperand(0);
9312     if (isContractableFMUL(N00) &&
9313         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9314       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9315                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9316                                      N00.getOperand(0)),
9317                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9318                                      N00.getOperand(1)), N1);
9319     }
9320   }
9321
9322   // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9323   // Note: Commutes FADD operands.
9324   if (N1.getOpcode() == ISD::FP_EXTEND) {
9325     SDValue N10 = N1.getOperand(0);
9326     if (isContractableFMUL(N10) &&
9327         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9328       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9329                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9330                                      N10.getOperand(0)),
9331                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9332                                      N10.getOperand(1)), N0);
9333     }
9334   }
9335
9336   // More folding opportunities when target permits.
9337   if (Aggressive) {
9338     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9339     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9340     // are currently only supported on binary nodes.
9341     if (Options.UnsafeFPMath &&
9342         N0.getOpcode() == PreferredFusedOpcode &&
9343         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9344         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9345       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9346                          N0.getOperand(0), N0.getOperand(1),
9347                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9348                                      N0.getOperand(2).getOperand(0),
9349                                      N0.getOperand(2).getOperand(1),
9350                                      N1));
9351     }
9352
9353     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9354     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9355     // are currently only supported on binary nodes.
9356     if (Options.UnsafeFPMath &&
9357         N1->getOpcode() == PreferredFusedOpcode &&
9358         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9359         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9360       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9361                          N1.getOperand(0), N1.getOperand(1),
9362                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9363                                      N1.getOperand(2).getOperand(0),
9364                                      N1.getOperand(2).getOperand(1),
9365                                      N0));
9366     }
9367
9368
9369     // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9370     //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9371     auto FoldFAddFMAFPExtFMul = [&] (
9372       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9373       return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9374                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9375                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9376                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9377                                      Z));
9378     };
9379     if (N0.getOpcode() == PreferredFusedOpcode) {
9380       SDValue N02 = N0.getOperand(2);
9381       if (N02.getOpcode() == ISD::FP_EXTEND) {
9382         SDValue N020 = N02.getOperand(0);
9383         if (isContractableFMUL(N020) &&
9384             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9385           return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9386                                       N020.getOperand(0), N020.getOperand(1),
9387                                       N1);
9388         }
9389       }
9390     }
9391
9392     // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9393     //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9394     // FIXME: This turns two single-precision and one double-precision
9395     // operation into two double-precision operations, which might not be
9396     // interesting for all targets, especially GPUs.
9397     auto FoldFAddFPExtFMAFMul = [&] (
9398       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9399       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9400                          DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9401                          DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9402                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9403                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9404                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9405                                      Z));
9406     };
9407     if (N0.getOpcode() == ISD::FP_EXTEND) {
9408       SDValue N00 = N0.getOperand(0);
9409       if (N00.getOpcode() == PreferredFusedOpcode) {
9410         SDValue N002 = N00.getOperand(2);
9411         if (isContractableFMUL(N002) &&
9412             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9413           return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9414                                       N002.getOperand(0), N002.getOperand(1),
9415                                       N1);
9416         }
9417       }
9418     }
9419
9420     // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9421     //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9422     if (N1.getOpcode() == PreferredFusedOpcode) {
9423       SDValue N12 = N1.getOperand(2);
9424       if (N12.getOpcode() == ISD::FP_EXTEND) {
9425         SDValue N120 = N12.getOperand(0);
9426         if (isContractableFMUL(N120) &&
9427             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9428           return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9429                                       N120.getOperand(0), N120.getOperand(1),
9430                                       N0);
9431         }
9432       }
9433     }
9434
9435     // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9436     //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9437     // FIXME: This turns two single-precision and one double-precision
9438     // operation into two double-precision operations, which might not be
9439     // interesting for all targets, especially GPUs.
9440     if (N1.getOpcode() == ISD::FP_EXTEND) {
9441       SDValue N10 = N1.getOperand(0);
9442       if (N10.getOpcode() == PreferredFusedOpcode) {
9443         SDValue N102 = N10.getOperand(2);
9444         if (isContractableFMUL(N102) &&
9445             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9446           return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9447                                       N102.getOperand(0), N102.getOperand(1),
9448                                       N0);
9449         }
9450       }
9451     }
9452   }
9453
9454   return SDValue();
9455 }
9456
9457 /// Try to perform FMA combining on a given FSUB node.
9458 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9459   SDValue N0 = N->getOperand(0);
9460   SDValue N1 = N->getOperand(1);
9461   EVT VT = N->getValueType(0);
9462   SDLoc SL(N);
9463
9464   const TargetOptions &Options = DAG.getTarget().Options;
9465   // Floating-point multiply-add with intermediate rounding.
9466   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9467
9468   // Floating-point multiply-add without intermediate rounding.
9469   bool HasFMA =
9470       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9471       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9472
9473   // No valid opcode, do not combine.
9474   if (!HasFMAD && !HasFMA)
9475     return SDValue();
9476
9477   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9478                               Options.UnsafeFPMath || HasFMAD);
9479   // If the subtraction is not contractable, do not combine.
9480   if (!AllowFusionGlobally && !isContractable(N))
9481     return SDValue();
9482
9483   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9484   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9485     return SDValue();
9486
9487   // Always prefer FMAD to FMA for precision.
9488   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9489   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9490
9491   // Is the node an FMUL and contractable either due to global flags or
9492   // SDNodeFlags.
9493   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9494     if (N.getOpcode() != ISD::FMUL)
9495       return false;
9496     return AllowFusionGlobally || isContractable(N.getNode());
9497   };
9498
9499   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9500   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9501     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9502                        N0.getOperand(0), N0.getOperand(1),
9503                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9504   }
9505
9506   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9507   // Note: Commutes FSUB operands.
9508   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9509     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9510                        DAG.getNode(ISD::FNEG, SL, VT,
9511                                    N1.getOperand(0)),
9512                        N1.getOperand(1), N0);
9513
9514   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9515   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9516       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9517     SDValue N00 = N0.getOperand(0).getOperand(0);
9518     SDValue N01 = N0.getOperand(0).getOperand(1);
9519     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9520                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9521                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9522   }
9523
9524   // Look through FP_EXTEND nodes to do more combining.
9525
9526   // fold (fsub (fpext (fmul x, y)), z)
9527   //   -> (fma (fpext x), (fpext y), (fneg z))
9528   if (N0.getOpcode() == ISD::FP_EXTEND) {
9529     SDValue N00 = N0.getOperand(0);
9530     if (isContractableFMUL(N00) &&
9531         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9532       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9533                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9534                                      N00.getOperand(0)),
9535                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9536                                      N00.getOperand(1)),
9537                          DAG.getNode(ISD::FNEG, SL, VT, N1));
9538     }
9539   }
9540
9541   // fold (fsub x, (fpext (fmul y, z)))
9542   //   -> (fma (fneg (fpext y)), (fpext z), x)
9543   // Note: Commutes FSUB operands.
9544   if (N1.getOpcode() == ISD::FP_EXTEND) {
9545     SDValue N10 = N1.getOperand(0);
9546     if (isContractableFMUL(N10) &&
9547         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9548       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9549                          DAG.getNode(ISD::FNEG, SL, VT,
9550                                      DAG.getNode(ISD::FP_EXTEND, SL, VT,
9551                                                  N10.getOperand(0))),
9552                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9553                                      N10.getOperand(1)),
9554                          N0);
9555     }
9556   }
9557
9558   // fold (fsub (fpext (fneg (fmul, x, y))), z)
9559   //   -> (fneg (fma (fpext x), (fpext y), z))
9560   // Note: This could be removed with appropriate canonicalization of the
9561   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9562   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9563   // from implementing the canonicalization in visitFSUB.
9564   if (N0.getOpcode() == ISD::FP_EXTEND) {
9565     SDValue N00 = N0.getOperand(0);
9566     if (N00.getOpcode() == ISD::FNEG) {
9567       SDValue N000 = N00.getOperand(0);
9568       if (isContractableFMUL(N000) &&
9569           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9570         return DAG.getNode(ISD::FNEG, SL, VT,
9571                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9572                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9573                                                    N000.getOperand(0)),
9574                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9575                                                    N000.getOperand(1)),
9576                                        N1));
9577       }
9578     }
9579   }
9580
9581   // fold (fsub (fneg (fpext (fmul, x, y))), z)
9582   //   -> (fneg (fma (fpext x)), (fpext y), z)
9583   // Note: This could be removed with appropriate canonicalization of the
9584   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9585   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9586   // from implementing the canonicalization in visitFSUB.
9587   if (N0.getOpcode() == ISD::FNEG) {
9588     SDValue N00 = N0.getOperand(0);
9589     if (N00.getOpcode() == ISD::FP_EXTEND) {
9590       SDValue N000 = N00.getOperand(0);
9591       if (isContractableFMUL(N000) &&
9592           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
9593         return DAG.getNode(ISD::FNEG, SL, VT,
9594                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9595                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9596                                                    N000.getOperand(0)),
9597                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9598                                                    N000.getOperand(1)),
9599                                        N1));
9600       }
9601     }
9602   }
9603
9604   // More folding opportunities when target permits.
9605   if (Aggressive) {
9606     // fold (fsub (fma x, y, (fmul u, v)), z)
9607     //   -> (fma x, y (fma u, v, (fneg z)))
9608     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9609     // are currently only supported on binary nodes.
9610     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9611         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9612         N0.getOperand(2)->hasOneUse()) {
9613       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9614                          N0.getOperand(0), N0.getOperand(1),
9615                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9616                                      N0.getOperand(2).getOperand(0),
9617                                      N0.getOperand(2).getOperand(1),
9618                                      DAG.getNode(ISD::FNEG, SL, VT,
9619                                                  N1)));
9620     }
9621
9622     // fold (fsub x, (fma y, z, (fmul u, v)))
9623     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9624     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9625     // are currently only supported on binary nodes.
9626     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9627         isContractableFMUL(N1.getOperand(2))) {
9628       SDValue N20 = N1.getOperand(2).getOperand(0);
9629       SDValue N21 = N1.getOperand(2).getOperand(1);
9630       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9631                          DAG.getNode(ISD::FNEG, SL, VT,
9632                                      N1.getOperand(0)),
9633                          N1.getOperand(1),
9634                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9635                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9636
9637                                      N21, N0));
9638     }
9639
9640
9641     // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9642     //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9643     if (N0.getOpcode() == PreferredFusedOpcode) {
9644       SDValue N02 = N0.getOperand(2);
9645       if (N02.getOpcode() == ISD::FP_EXTEND) {
9646         SDValue N020 = N02.getOperand(0);
9647         if (isContractableFMUL(N020) &&
9648             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9649           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9650                              N0.getOperand(0), N0.getOperand(1),
9651                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9652                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9653                                                      N020.getOperand(0)),
9654                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9655                                                      N020.getOperand(1)),
9656                                          DAG.getNode(ISD::FNEG, SL, VT,
9657                                                      N1)));
9658         }
9659       }
9660     }
9661
9662     // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9663     //   -> (fma (fpext x), (fpext y),
9664     //           (fma (fpext u), (fpext v), (fneg z)))
9665     // FIXME: This turns two single-precision and one double-precision
9666     // operation into two double-precision operations, which might not be
9667     // interesting for all targets, especially GPUs.
9668     if (N0.getOpcode() == ISD::FP_EXTEND) {
9669       SDValue N00 = N0.getOperand(0);
9670       if (N00.getOpcode() == PreferredFusedOpcode) {
9671         SDValue N002 = N00.getOperand(2);
9672         if (isContractableFMUL(N002) &&
9673             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9674           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9675                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9676                                          N00.getOperand(0)),
9677                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9678                                          N00.getOperand(1)),
9679                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9680                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9681                                                      N002.getOperand(0)),
9682                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9683                                                      N002.getOperand(1)),
9684                                          DAG.getNode(ISD::FNEG, SL, VT,
9685                                                      N1)));
9686         }
9687       }
9688     }
9689
9690     // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9691     //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9692     if (N1.getOpcode() == PreferredFusedOpcode &&
9693         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9694       SDValue N120 = N1.getOperand(2).getOperand(0);
9695       if (isContractableFMUL(N120) &&
9696           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9697         SDValue N1200 = N120.getOperand(0);
9698         SDValue N1201 = N120.getOperand(1);
9699         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9700                            DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9701                            N1.getOperand(1),
9702                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9703                                        DAG.getNode(ISD::FNEG, SL, VT,
9704                                                    DAG.getNode(ISD::FP_EXTEND, SL,
9705                                                                VT, N1200)),
9706                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9707                                                    N1201),
9708                                        N0));
9709       }
9710     }
9711
9712     // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9713     //   -> (fma (fneg (fpext y)), (fpext z),
9714     //           (fma (fneg (fpext u)), (fpext v), x))
9715     // FIXME: This turns two single-precision and one double-precision
9716     // operation into two double-precision operations, which might not be
9717     // interesting for all targets, especially GPUs.
9718     if (N1.getOpcode() == ISD::FP_EXTEND &&
9719         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9720       SDValue CvtSrc = N1.getOperand(0);
9721       SDValue N100 = CvtSrc.getOperand(0);
9722       SDValue N101 = CvtSrc.getOperand(1);
9723       SDValue N102 = CvtSrc.getOperand(2);
9724       if (isContractableFMUL(N102) &&
9725           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
9726         SDValue N1020 = N102.getOperand(0);
9727         SDValue N1021 = N102.getOperand(1);
9728         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9729                            DAG.getNode(ISD::FNEG, SL, VT,
9730                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9731                                                    N100)),
9732                            DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9733                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9734                                        DAG.getNode(ISD::FNEG, SL, VT,
9735                                                    DAG.getNode(ISD::FP_EXTEND, SL,
9736                                                                VT, N1020)),
9737                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9738                                                    N1021),
9739                                        N0));
9740       }
9741     }
9742   }
9743
9744   return SDValue();
9745 }
9746
9747 /// Try to perform FMA combining on a given FMUL node based on the distributive
9748 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9749 /// subtraction instead of addition).
9750 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9751   SDValue N0 = N->getOperand(0);
9752   SDValue N1 = N->getOperand(1);
9753   EVT VT = N->getValueType(0);
9754   SDLoc SL(N);
9755
9756   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9757
9758   const TargetOptions &Options = DAG.getTarget().Options;
9759
9760   // The transforms below are incorrect when x == 0 and y == inf, because the
9761   // intermediate multiplication produces a nan.
9762   if (!Options.NoInfsFPMath)
9763     return SDValue();
9764
9765   // Floating-point multiply-add without intermediate rounding.
9766   bool HasFMA =
9767       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9768       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9769       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9770
9771   // Floating-point multiply-add with intermediate rounding. This can result
9772   // in a less precise result due to the changed rounding order.
9773   bool HasFMAD = Options.UnsafeFPMath &&
9774                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9775
9776   // No valid opcode, do not combine.
9777   if (!HasFMAD && !HasFMA)
9778     return SDValue();
9779
9780   // Always prefer FMAD to FMA for precision.
9781   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9782   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9783
9784   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9785   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9786   auto FuseFADD = [&](SDValue X, SDValue Y) {
9787     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9788       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9789       if (XC1 && XC1->isExactlyValue(+1.0))
9790         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9791       if (XC1 && XC1->isExactlyValue(-1.0))
9792         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9793                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9794     }
9795     return SDValue();
9796   };
9797
9798   if (SDValue FMA = FuseFADD(N0, N1))
9799     return FMA;
9800   if (SDValue FMA = FuseFADD(N1, N0))
9801     return FMA;
9802
9803   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9804   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9805   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9806   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9807   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9808     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9809       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9810       if (XC0 && XC0->isExactlyValue(+1.0))
9811         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9812                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9813                            Y);
9814       if (XC0 && XC0->isExactlyValue(-1.0))
9815         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9816                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9817                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9818
9819       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9820       if (XC1 && XC1->isExactlyValue(+1.0))
9821         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9822                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9823       if (XC1 && XC1->isExactlyValue(-1.0))
9824         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9825     }
9826     return SDValue();
9827   };
9828
9829   if (SDValue FMA = FuseFSUB(N0, N1))
9830     return FMA;
9831   if (SDValue FMA = FuseFSUB(N1, N0))
9832     return FMA;
9833
9834   return SDValue();
9835 }
9836
9837 static bool isFMulNegTwo(SDValue &N) {
9838   if (N.getOpcode() != ISD::FMUL)
9839     return false;
9840   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9841     return CFP->isExactlyValue(-2.0);
9842   return false;
9843 }
9844
9845 SDValue DAGCombiner::visitFADD(SDNode *N) {
9846   SDValue N0 = N->getOperand(0);
9847   SDValue N1 = N->getOperand(1);
9848   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9849   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9850   EVT VT = N->getValueType(0);
9851   SDLoc DL(N);
9852   const TargetOptions &Options = DAG.getTarget().Options;
9853   const SDNodeFlags Flags = N->getFlags();
9854
9855   // fold vector ops
9856   if (VT.isVector())
9857     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9858       return FoldedVOp;
9859
9860   // fold (fadd c1, c2) -> c1 + c2
9861   if (N0CFP && N1CFP)
9862     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9863
9864   // canonicalize constant to RHS
9865   if (N0CFP && !N1CFP)
9866     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9867
9868   if (SDValue NewSel = foldBinOpIntoSelect(N))
9869     return NewSel;
9870
9871   // fold (fadd A, (fneg B)) -> (fsub A, B)
9872   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9873       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9874     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9875                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9876
9877   // fold (fadd (fneg A), B) -> (fsub B, A)
9878   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9879       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9880     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9881                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9882
9883   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9884   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9885   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9886       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9887     bool N1IsFMul = isFMulNegTwo(N1);
9888     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9889     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9890     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9891   }
9892
9893   // FIXME: Auto-upgrade the target/function-level option.
9894   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9895     // fold (fadd A, 0) -> A
9896     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9897       if (N1C->isZero())
9898         return N0;
9899   }
9900
9901   // If 'unsafe math' is enabled, fold lots of things.
9902   if (Options.UnsafeFPMath) {
9903     // No FP constant should be created after legalization as Instruction
9904     // Selection pass has a hard time dealing with FP constants.
9905     bool AllowNewConst = (Level < AfterLegalizeDAG);
9906
9907     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9908     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9909         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9910       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9911                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9912                                      Flags),
9913                          Flags);
9914
9915     // If allowed, fold (fadd (fneg x), x) -> 0.0
9916     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9917       return DAG.getConstantFP(0.0, DL, VT);
9918
9919     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9920     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9921       return DAG.getConstantFP(0.0, DL, VT);
9922
9923     // We can fold chains of FADD's of the same value into multiplications.
9924     // This transform is not safe in general because we are reducing the number
9925     // of rounding steps.
9926     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9927       if (N0.getOpcode() == ISD::FMUL) {
9928         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9929         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9930
9931         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9932         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9933           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9934                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9935           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9936         }
9937
9938         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9939         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9940             N1.getOperand(0) == N1.getOperand(1) &&
9941             N0.getOperand(0) == N1.getOperand(0)) {
9942           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9943                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9944           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9945         }
9946       }
9947
9948       if (N1.getOpcode() == ISD::FMUL) {
9949         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9950         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9951
9952         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9953         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9954           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9955                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9956           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9957         }
9958
9959         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9960         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9961             N0.getOperand(0) == N0.getOperand(1) &&
9962             N1.getOperand(0) == N0.getOperand(0)) {
9963           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9964                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9965           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9966         }
9967       }
9968
9969       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9970         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9971         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9972         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9973             (N0.getOperand(0) == N1)) {
9974           return DAG.getNode(ISD::FMUL, DL, VT,
9975                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9976         }
9977       }
9978
9979       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9980         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9981         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9982         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9983             N1.getOperand(0) == N0) {
9984           return DAG.getNode(ISD::FMUL, DL, VT,
9985                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9986         }
9987       }
9988
9989       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9990       if (AllowNewConst &&
9991           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9992           N0.getOperand(0) == N0.getOperand(1) &&
9993           N1.getOperand(0) == N1.getOperand(1) &&
9994           N0.getOperand(0) == N1.getOperand(0)) {
9995         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9996                            DAG.getConstantFP(4.0, DL, VT), Flags);
9997       }
9998     }
9999   } // enable-unsafe-fp-math
10000
10001   // FADD -> FMA combines:
10002   if (SDValue Fused = visitFADDForFMACombine(N)) {
10003     AddToWorklist(Fused.getNode());
10004     return Fused;
10005   }
10006   return SDValue();
10007 }
10008
10009 SDValue DAGCombiner::visitFSUB(SDNode *N) {
10010   SDValue N0 = N->getOperand(0);
10011   SDValue N1 = N->getOperand(1);
10012   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10013   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10014   EVT VT = N->getValueType(0);
10015   SDLoc DL(N);
10016   const TargetOptions &Options = DAG.getTarget().Options;
10017   const SDNodeFlags Flags = N->getFlags();
10018
10019   // fold vector ops
10020   if (VT.isVector())
10021     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10022       return FoldedVOp;
10023
10024   // fold (fsub c1, c2) -> c1-c2
10025   if (N0CFP && N1CFP)
10026     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10027
10028   if (SDValue NewSel = foldBinOpIntoSelect(N))
10029     return NewSel;
10030
10031   // fold (fsub A, (fneg B)) -> (fadd A, B)
10032   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10033     return DAG.getNode(ISD::FADD, DL, VT, N0,
10034                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10035
10036   // FIXME: Auto-upgrade the target/function-level option.
10037   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
10038     // (fsub 0, B) -> -B
10039     if (N0CFP && N0CFP->isZero()) {
10040       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10041         return GetNegatedExpression(N1, DAG, LegalOperations);
10042       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10043         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10044     }
10045   }
10046
10047   // If 'unsafe math' is enabled, fold lots of things.
10048   if (Options.UnsafeFPMath) {
10049     // (fsub A, 0) -> A
10050     if (N1CFP && N1CFP->isZero())
10051       return N0;
10052
10053     // (fsub x, x) -> 0.0
10054     if (N0 == N1)
10055       return DAG.getConstantFP(0.0f, DL, VT);
10056
10057     // (fsub x, (fadd x, y)) -> (fneg y)
10058     // (fsub x, (fadd y, x)) -> (fneg y)
10059     if (N1.getOpcode() == ISD::FADD) {
10060       SDValue N10 = N1->getOperand(0);
10061       SDValue N11 = N1->getOperand(1);
10062
10063       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10064         return GetNegatedExpression(N11, DAG, LegalOperations);
10065
10066       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10067         return GetNegatedExpression(N10, DAG, LegalOperations);
10068     }
10069   }
10070
10071   // FSUB -> FMA combines:
10072   if (SDValue Fused = visitFSUBForFMACombine(N)) {
10073     AddToWorklist(Fused.getNode());
10074     return Fused;
10075   }
10076
10077   return SDValue();
10078 }
10079
10080 SDValue DAGCombiner::visitFMUL(SDNode *N) {
10081   SDValue N0 = N->getOperand(0);
10082   SDValue N1 = N->getOperand(1);
10083   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10084   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10085   EVT VT = N->getValueType(0);
10086   SDLoc DL(N);
10087   const TargetOptions &Options = DAG.getTarget().Options;
10088   const SDNodeFlags Flags = N->getFlags();
10089
10090   // fold vector ops
10091   if (VT.isVector()) {
10092     // This just handles C1 * C2 for vectors. Other vector folds are below.
10093     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10094       return FoldedVOp;
10095   }
10096
10097   // fold (fmul c1, c2) -> c1*c2
10098   if (N0CFP && N1CFP)
10099     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10100
10101   // canonicalize constant to RHS
10102   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10103      !isConstantFPBuildVectorOrConstantFP(N1))
10104     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10105
10106   // fold (fmul A, 1.0) -> A
10107   if (N1CFP && N1CFP->isExactlyValue(1.0))
10108     return N0;
10109
10110   if (SDValue NewSel = foldBinOpIntoSelect(N))
10111     return NewSel;
10112
10113   if (Options.UnsafeFPMath) {
10114     // fold (fmul A, 0) -> 0
10115     if (N1CFP && N1CFP->isZero())
10116       return N1;
10117
10118     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
10119     if (N0.getOpcode() == ISD::FMUL) {
10120       // Fold scalars or any vector constants (not just splats).
10121       // This fold is done in general by InstCombine, but extra fmul insts
10122       // may have been generated during lowering.
10123       SDValue N00 = N0.getOperand(0);
10124       SDValue N01 = N0.getOperand(1);
10125       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10126       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10127       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10128
10129       // Check 1: Make sure that the first operand of the inner multiply is NOT
10130       // a constant. Otherwise, we may induce infinite looping.
10131       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10132         // Check 2: Make sure that the second operand of the inner multiply and
10133         // the second operand of the outer multiply are constants.
10134         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10135             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10136           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10137           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10138         }
10139       }
10140     }
10141
10142     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
10143     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
10144     // during an early run of DAGCombiner can prevent folding with fmuls
10145     // inserted during lowering.
10146     if (N0.getOpcode() == ISD::FADD &&
10147         (N0.getOperand(0) == N0.getOperand(1)) &&
10148         N0.hasOneUse()) {
10149       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10150       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10151       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10152     }
10153   }
10154
10155   // fold (fmul X, 2.0) -> (fadd X, X)
10156   if (N1CFP && N1CFP->isExactlyValue(+2.0))
10157     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10158
10159   // fold (fmul X, -1.0) -> (fneg X)
10160   if (N1CFP && N1CFP->isExactlyValue(-1.0))
10161     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10162       return DAG.getNode(ISD::FNEG, DL, VT, N0);
10163
10164   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10165   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10166     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10167       // Both can be negated for free, check to see if at least one is cheaper
10168       // negated.
10169       if (LHSNeg == 2 || RHSNeg == 2)
10170         return DAG.getNode(ISD::FMUL, DL, VT,
10171                            GetNegatedExpression(N0, DAG, LegalOperations),
10172                            GetNegatedExpression(N1, DAG, LegalOperations),
10173                            Flags);
10174     }
10175   }
10176
10177   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10178   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10179   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10180       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10181       TLI.isOperationLegal(ISD::FABS, VT)) {
10182     SDValue Select = N0, X = N1;
10183     if (Select.getOpcode() != ISD::SELECT)
10184       std::swap(Select, X);
10185
10186     SDValue Cond = Select.getOperand(0);
10187     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10188     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10189
10190     if (TrueOpnd && FalseOpnd &&
10191         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10192         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10193         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10194       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10195       switch (CC) {
10196       default: break;
10197       case ISD::SETOLT:
10198       case ISD::SETULT:
10199       case ISD::SETOLE:
10200       case ISD::SETULE:
10201       case ISD::SETLT:
10202       case ISD::SETLE:
10203         std::swap(TrueOpnd, FalseOpnd);
10204         // Fall through
10205       case ISD::SETOGT:
10206       case ISD::SETUGT:
10207       case ISD::SETOGE:
10208       case ISD::SETUGE:
10209       case ISD::SETGT:
10210       case ISD::SETGE:
10211         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10212             TLI.isOperationLegal(ISD::FNEG, VT))
10213           return DAG.getNode(ISD::FNEG, DL, VT,
10214                    DAG.getNode(ISD::FABS, DL, VT, X));
10215         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10216           return DAG.getNode(ISD::FABS, DL, VT, X);
10217
10218         break;
10219       }
10220     }
10221   }
10222
10223   // FMUL -> FMA combines:
10224   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10225     AddToWorklist(Fused.getNode());
10226     return Fused;
10227   }
10228
10229   return SDValue();
10230 }
10231
10232 SDValue DAGCombiner::visitFMA(SDNode *N) {
10233   SDValue N0 = N->getOperand(0);
10234   SDValue N1 = N->getOperand(1);
10235   SDValue N2 = N->getOperand(2);
10236   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10237   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10238   EVT VT = N->getValueType(0);
10239   SDLoc DL(N);
10240   const TargetOptions &Options = DAG.getTarget().Options;
10241
10242   // Constant fold FMA.
10243   if (isa<ConstantFPSDNode>(N0) &&
10244       isa<ConstantFPSDNode>(N1) &&
10245       isa<ConstantFPSDNode>(N2)) {
10246     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10247   }
10248
10249   if (Options.UnsafeFPMath) {
10250     if (N0CFP && N0CFP->isZero())
10251       return N2;
10252     if (N1CFP && N1CFP->isZero())
10253       return N2;
10254   }
10255   // TODO: The FMA node should have flags that propagate to these nodes.
10256   if (N0CFP && N0CFP->isExactlyValue(1.0))
10257     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10258   if (N1CFP && N1CFP->isExactlyValue(1.0))
10259     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10260
10261   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10262   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10263      !isConstantFPBuildVectorOrConstantFP(N1))
10264     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10265
10266   // TODO: FMA nodes should have flags that propagate to the created nodes.
10267   // For now, create a Flags object for use with all unsafe math transforms.
10268   SDNodeFlags Flags;
10269   Flags.setUnsafeAlgebra(true);
10270
10271   if (Options.UnsafeFPMath) {
10272     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10273     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10274         isConstantFPBuildVectorOrConstantFP(N1) &&
10275         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10276       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10277                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10278                                      Flags), Flags);
10279     }
10280
10281     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10282     if (N0.getOpcode() == ISD::FMUL &&
10283         isConstantFPBuildVectorOrConstantFP(N1) &&
10284         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10285       return DAG.getNode(ISD::FMA, DL, VT,
10286                          N0.getOperand(0),
10287                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10288                                      Flags),
10289                          N2);
10290     }
10291   }
10292
10293   // (fma x, 1, y) -> (fadd x, y)
10294   // (fma x, -1, y) -> (fadd (fneg x), y)
10295   if (N1CFP) {
10296     if (N1CFP->isExactlyValue(1.0))
10297       // TODO: The FMA node should have flags that propagate to this node.
10298       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10299
10300     if (N1CFP->isExactlyValue(-1.0) &&
10301         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10302       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10303       AddToWorklist(RHSNeg.getNode());
10304       // TODO: The FMA node should have flags that propagate to this node.
10305       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10306     }
10307
10308     // fma (fneg x), K, y -> fma x -K, y
10309     if (N0.getOpcode() == ISD::FNEG &&
10310         (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10311          (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10312       return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10313                          DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10314     }
10315   }
10316
10317   if (Options.UnsafeFPMath) {
10318     // (fma x, c, x) -> (fmul x, (c+1))
10319     if (N1CFP && N0 == N2) {
10320       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10321                          DAG.getNode(ISD::FADD, DL, VT, N1,
10322                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10323                          Flags);
10324     }
10325
10326     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10327     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10328       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10329                          DAG.getNode(ISD::FADD, DL, VT, N1,
10330                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10331                          Flags);
10332     }
10333   }
10334
10335   return SDValue();
10336 }
10337
10338 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10339 // reciprocal.
10340 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10341 // Notice that this is not always beneficial. One reason is different targets
10342 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10343 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10344 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10345 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10346   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10347   const SDNodeFlags Flags = N->getFlags();
10348   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10349     return SDValue();
10350
10351   // Skip if current node is a reciprocal.
10352   SDValue N0 = N->getOperand(0);
10353   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10354   if (N0CFP && N0CFP->isExactlyValue(1.0))
10355     return SDValue();
10356
10357   // Exit early if the target does not want this transform or if there can't
10358   // possibly be enough uses of the divisor to make the transform worthwhile.
10359   SDValue N1 = N->getOperand(1);
10360   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10361   if (!MinUses || N1->use_size() < MinUses)
10362     return SDValue();
10363
10364   // Find all FDIV users of the same divisor.
10365   // Use a set because duplicates may be present in the user list.
10366   SetVector<SDNode *> Users;
10367   for (auto *U : N1->uses()) {
10368     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10369       // This division is eligible for optimization only if global unsafe math
10370       // is enabled or if this division allows reciprocal formation.
10371       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10372         Users.insert(U);
10373     }
10374   }
10375
10376   // Now that we have the actual number of divisor uses, make sure it meets
10377   // the minimum threshold specified by the target.
10378   if (Users.size() < MinUses)
10379     return SDValue();
10380
10381   EVT VT = N->getValueType(0);
10382   SDLoc DL(N);
10383   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10384   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10385
10386   // Dividend / Divisor -> Dividend * Reciprocal
10387   for (auto *U : Users) {
10388     SDValue Dividend = U->getOperand(0);
10389     if (Dividend != FPOne) {
10390       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10391                                     Reciprocal, Flags);
10392       CombineTo(U, NewNode);
10393     } else if (U != Reciprocal.getNode()) {
10394       // In the absence of fast-math-flags, this user node is always the
10395       // same node as Reciprocal, but with FMF they may be different nodes.
10396       CombineTo(U, Reciprocal);
10397     }
10398   }
10399   return SDValue(N, 0);  // N was replaced.
10400 }
10401
10402 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10403   SDValue N0 = N->getOperand(0);
10404   SDValue N1 = N->getOperand(1);
10405   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10406   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10407   EVT VT = N->getValueType(0);
10408   SDLoc DL(N);
10409   const TargetOptions &Options = DAG.getTarget().Options;
10410   SDNodeFlags Flags = N->getFlags();
10411
10412   // fold vector ops
10413   if (VT.isVector())
10414     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10415       return FoldedVOp;
10416
10417   // fold (fdiv c1, c2) -> c1/c2
10418   if (N0CFP && N1CFP)
10419     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10420
10421   if (SDValue NewSel = foldBinOpIntoSelect(N))
10422     return NewSel;
10423
10424   if (Options.UnsafeFPMath) {
10425     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10426     if (N1CFP) {
10427       // Compute the reciprocal 1.0 / c2.
10428       const APFloat &N1APF = N1CFP->getValueAPF();
10429       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10430       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10431       // Only do the transform if the reciprocal is a legal fp immediate that
10432       // isn't too nasty (eg NaN, denormal, ...).
10433       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10434           (!LegalOperations ||
10435            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10436            // backend)... we should handle this gracefully after Legalize.
10437            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10438            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10439            TLI.isFPImmLegal(Recip, VT)))
10440         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10441                            DAG.getConstantFP(Recip, DL, VT), Flags);
10442     }
10443
10444     // If this FDIV is part of a reciprocal square root, it may be folded
10445     // into a target-specific square root estimate instruction.
10446     if (N1.getOpcode() == ISD::FSQRT) {
10447       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10448         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10449       }
10450     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10451                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10452       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10453                                           Flags)) {
10454         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10455         AddToWorklist(RV.getNode());
10456         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10457       }
10458     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10459                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10460       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10461                                           Flags)) {
10462         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10463         AddToWorklist(RV.getNode());
10464         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10465       }
10466     } else if (N1.getOpcode() == ISD::FMUL) {
10467       // Look through an FMUL. Even though this won't remove the FDIV directly,
10468       // it's still worthwhile to get rid of the FSQRT if possible.
10469       SDValue SqrtOp;
10470       SDValue OtherOp;
10471       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10472         SqrtOp = N1.getOperand(0);
10473         OtherOp = N1.getOperand(1);
10474       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10475         SqrtOp = N1.getOperand(1);
10476         OtherOp = N1.getOperand(0);
10477       }
10478       if (SqrtOp.getNode()) {
10479         // We found a FSQRT, so try to make this fold:
10480         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10481         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10482           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10483           AddToWorklist(RV.getNode());
10484           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10485         }
10486       }
10487     }
10488
10489     // Fold into a reciprocal estimate and multiply instead of a real divide.
10490     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10491       AddToWorklist(RV.getNode());
10492       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10493     }
10494   }
10495
10496   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10497   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10498     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10499       // Both can be negated for free, check to see if at least one is cheaper
10500       // negated.
10501       if (LHSNeg == 2 || RHSNeg == 2)
10502         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10503                            GetNegatedExpression(N0, DAG, LegalOperations),
10504                            GetNegatedExpression(N1, DAG, LegalOperations),
10505                            Flags);
10506     }
10507   }
10508
10509   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10510     return CombineRepeatedDivisors;
10511
10512   return SDValue();
10513 }
10514
10515 SDValue DAGCombiner::visitFREM(SDNode *N) {
10516   SDValue N0 = N->getOperand(0);
10517   SDValue N1 = N->getOperand(1);
10518   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10519   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10520   EVT VT = N->getValueType(0);
10521
10522   // fold (frem c1, c2) -> fmod(c1,c2)
10523   if (N0CFP && N1CFP)
10524     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10525
10526   if (SDValue NewSel = foldBinOpIntoSelect(N))
10527     return NewSel;
10528
10529   return SDValue();
10530 }
10531
10532 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10533   if (!DAG.getTarget().Options.UnsafeFPMath)
10534     return SDValue();
10535
10536   SDValue N0 = N->getOperand(0);
10537   if (TLI.isFsqrtCheap(N0, DAG))
10538     return SDValue();
10539
10540   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10541   // For now, create a Flags object for use with all unsafe math transforms.
10542   SDNodeFlags Flags;
10543   Flags.setUnsafeAlgebra(true);
10544   return buildSqrtEstimate(N0, Flags);
10545 }
10546
10547 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10548 /// copysign(x, fp_round(y)) -> copysign(x, y)
10549 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10550   SDValue N1 = N->getOperand(1);
10551   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10552        N1.getOpcode() == ISD::FP_ROUND)) {
10553     // Do not optimize out type conversion of f128 type yet.
10554     // For some targets like x86_64, configuration is changed to keep one f128
10555     // value in one SSE register, but instruction selection cannot handle
10556     // FCOPYSIGN on SSE registers yet.
10557     EVT N1VT = N1->getValueType(0);
10558     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10559     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10560   }
10561   return false;
10562 }
10563
10564 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10565   SDValue N0 = N->getOperand(0);
10566   SDValue N1 = N->getOperand(1);
10567   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10568   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10569   EVT VT = N->getValueType(0);
10570
10571   if (N0CFP && N1CFP) // Constant fold
10572     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10573
10574   if (N1CFP) {
10575     const APFloat &V = N1CFP->getValueAPF();
10576     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10577     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10578     if (!V.isNegative()) {
10579       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10580         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10581     } else {
10582       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10583         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10584                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10585     }
10586   }
10587
10588   // copysign(fabs(x), y) -> copysign(x, y)
10589   // copysign(fneg(x), y) -> copysign(x, y)
10590   // copysign(copysign(x,z), y) -> copysign(x, y)
10591   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10592       N0.getOpcode() == ISD::FCOPYSIGN)
10593     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10594
10595   // copysign(x, abs(y)) -> abs(x)
10596   if (N1.getOpcode() == ISD::FABS)
10597     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10598
10599   // copysign(x, copysign(y,z)) -> copysign(x, z)
10600   if (N1.getOpcode() == ISD::FCOPYSIGN)
10601     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10602
10603   // copysign(x, fp_extend(y)) -> copysign(x, y)
10604   // copysign(x, fp_round(y)) -> copysign(x, y)
10605   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10606     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10607
10608   return SDValue();
10609 }
10610
10611 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10612   SDValue N0 = N->getOperand(0);
10613   EVT VT = N->getValueType(0);
10614   EVT OpVT = N0.getValueType();
10615
10616   // fold (sint_to_fp c1) -> c1fp
10617   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10618       // ...but only if the target supports immediate floating-point values
10619       (!LegalOperations ||
10620        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10621     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10622
10623   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10624   // but UINT_TO_FP is legal on this target, try to convert.
10625   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10626       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10627     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10628     if (DAG.SignBitIsZero(N0))
10629       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10630   }
10631
10632   // The next optimizations are desirable only if SELECT_CC can be lowered.
10633   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10634     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10635     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10636         !VT.isVector() &&
10637         (!LegalOperations ||
10638          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10639       SDLoc DL(N);
10640       SDValue Ops[] =
10641         { N0.getOperand(0), N0.getOperand(1),
10642           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10643           N0.getOperand(2) };
10644       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10645     }
10646
10647     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10648     //      (select_cc x, y, 1.0, 0.0,, cc)
10649     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10650         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10651         (!LegalOperations ||
10652          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10653       SDLoc DL(N);
10654       SDValue Ops[] =
10655         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10656           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10657           N0.getOperand(0).getOperand(2) };
10658       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10659     }
10660   }
10661
10662   return SDValue();
10663 }
10664
10665 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10666   SDValue N0 = N->getOperand(0);
10667   EVT VT = N->getValueType(0);
10668   EVT OpVT = N0.getValueType();
10669
10670   // fold (uint_to_fp c1) -> c1fp
10671   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10672       // ...but only if the target supports immediate floating-point values
10673       (!LegalOperations ||
10674        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10675     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10676
10677   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10678   // but SINT_TO_FP is legal on this target, try to convert.
10679   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10680       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10681     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10682     if (DAG.SignBitIsZero(N0))
10683       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10684   }
10685
10686   // The next optimizations are desirable only if SELECT_CC can be lowered.
10687   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10688     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10689     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10690         (!LegalOperations ||
10691          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10692       SDLoc DL(N);
10693       SDValue Ops[] =
10694         { N0.getOperand(0), N0.getOperand(1),
10695           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10696           N0.getOperand(2) };
10697       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10698     }
10699   }
10700
10701   return SDValue();
10702 }
10703
10704 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10705 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10706   SDValue N0 = N->getOperand(0);
10707   EVT VT = N->getValueType(0);
10708
10709   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10710     return SDValue();
10711
10712   SDValue Src = N0.getOperand(0);
10713   EVT SrcVT = Src.getValueType();
10714   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10715   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10716
10717   // We can safely assume the conversion won't overflow the output range,
10718   // because (for example) (uint8_t)18293.f is undefined behavior.
10719
10720   // Since we can assume the conversion won't overflow, our decision as to
10721   // whether the input will fit in the float should depend on the minimum
10722   // of the input range and output range.
10723
10724   // This means this is also safe for a signed input and unsigned output, since
10725   // a negative input would lead to undefined behavior.
10726   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10727   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10728   unsigned ActualSize = std::min(InputSize, OutputSize);
10729   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10730
10731   // We can only fold away the float conversion if the input range can be
10732   // represented exactly in the float range.
10733   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10734     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10735       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10736                                                        : ISD::ZERO_EXTEND;
10737       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10738     }
10739     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10740       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10741     return DAG.getBitcast(VT, Src);
10742   }
10743   return SDValue();
10744 }
10745
10746 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10747   SDValue N0 = N->getOperand(0);
10748   EVT VT = N->getValueType(0);
10749
10750   // fold (fp_to_sint c1fp) -> c1
10751   if (isConstantFPBuildVectorOrConstantFP(N0))
10752     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10753
10754   return FoldIntToFPToInt(N, DAG);
10755 }
10756
10757 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10758   SDValue N0 = N->getOperand(0);
10759   EVT VT = N->getValueType(0);
10760
10761   // fold (fp_to_uint c1fp) -> c1
10762   if (isConstantFPBuildVectorOrConstantFP(N0))
10763     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10764
10765   return FoldIntToFPToInt(N, DAG);
10766 }
10767
10768 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10769   SDValue N0 = N->getOperand(0);
10770   SDValue N1 = N->getOperand(1);
10771   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10772   EVT VT = N->getValueType(0);
10773
10774   // fold (fp_round c1fp) -> c1fp
10775   if (N0CFP)
10776     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10777
10778   // fold (fp_round (fp_extend x)) -> x
10779   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10780     return N0.getOperand(0);
10781
10782   // fold (fp_round (fp_round x)) -> (fp_round x)
10783   if (N0.getOpcode() == ISD::FP_ROUND) {
10784     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10785     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10786
10787     // Skip this folding if it results in an fp_round from f80 to f16.
10788     //
10789     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10790     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10791     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10792     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10793     // x86.
10794     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10795       return SDValue();
10796
10797     // If the first fp_round isn't a value preserving truncation, it might
10798     // introduce a tie in the second fp_round, that wouldn't occur in the
10799     // single-step fp_round we want to fold to.
10800     // In other words, double rounding isn't the same as rounding.
10801     // Also, this is a value preserving truncation iff both fp_round's are.
10802     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10803       SDLoc DL(N);
10804       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10805                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10806     }
10807   }
10808
10809   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10810   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10811     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10812                               N0.getOperand(0), N1);
10813     AddToWorklist(Tmp.getNode());
10814     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10815                        Tmp, N0.getOperand(1));
10816   }
10817
10818   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10819     return NewVSel;
10820
10821   return SDValue();
10822 }
10823
10824 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10825   SDValue N0 = N->getOperand(0);
10826   EVT VT = N->getValueType(0);
10827   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10828   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10829
10830   // fold (fp_round_inreg c1fp) -> c1fp
10831   if (N0CFP && isTypeLegal(EVT)) {
10832     SDLoc DL(N);
10833     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10834     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10835   }
10836
10837   return SDValue();
10838 }
10839
10840 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10841   SDValue N0 = N->getOperand(0);
10842   EVT VT = N->getValueType(0);
10843
10844   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10845   if (N->hasOneUse() &&
10846       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10847     return SDValue();
10848
10849   // fold (fp_extend c1fp) -> c1fp
10850   if (isConstantFPBuildVectorOrConstantFP(N0))
10851     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10852
10853   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10854   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10855       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10856     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10857
10858   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10859   // value of X.
10860   if (N0.getOpcode() == ISD::FP_ROUND
10861       && N0.getConstantOperandVal(1) == 1) {
10862     SDValue In = N0.getOperand(0);
10863     if (In.getValueType() == VT) return In;
10864     if (VT.bitsLT(In.getValueType()))
10865       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10866                          In, N0.getOperand(1));
10867     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10868   }
10869
10870   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10871   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10872        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10873     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10874     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10875                                      LN0->getChain(),
10876                                      LN0->getBasePtr(), N0.getValueType(),
10877                                      LN0->getMemOperand());
10878     CombineTo(N, ExtLoad);
10879     CombineTo(N0.getNode(),
10880               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10881                           N0.getValueType(), ExtLoad,
10882                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10883               ExtLoad.getValue(1));
10884     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10885   }
10886
10887   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10888     return NewVSel;
10889
10890   return SDValue();
10891 }
10892
10893 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10894   SDValue N0 = N->getOperand(0);
10895   EVT VT = N->getValueType(0);
10896
10897   // fold (fceil c1) -> fceil(c1)
10898   if (isConstantFPBuildVectorOrConstantFP(N0))
10899     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10900
10901   return SDValue();
10902 }
10903
10904 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10905   SDValue N0 = N->getOperand(0);
10906   EVT VT = N->getValueType(0);
10907
10908   // fold (ftrunc c1) -> ftrunc(c1)
10909   if (isConstantFPBuildVectorOrConstantFP(N0))
10910     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10911
10912   // fold ftrunc (known rounded int x) -> x
10913   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
10914   // likely to be generated to extract integer from a rounded floating value.
10915   switch (N0.getOpcode()) {
10916   default: break;
10917   case ISD::FRINT:
10918   case ISD::FTRUNC:
10919   case ISD::FNEARBYINT:
10920   case ISD::FFLOOR:
10921   case ISD::FCEIL:
10922     return N0;
10923   }
10924
10925   return SDValue();
10926 }
10927
10928 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10929   SDValue N0 = N->getOperand(0);
10930   EVT VT = N->getValueType(0);
10931
10932   // fold (ffloor c1) -> ffloor(c1)
10933   if (isConstantFPBuildVectorOrConstantFP(N0))
10934     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10935
10936   return SDValue();
10937 }
10938
10939 // FIXME: FNEG and FABS have a lot in common; refactor.
10940 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10941   SDValue N0 = N->getOperand(0);
10942   EVT VT = N->getValueType(0);
10943
10944   // Constant fold FNEG.
10945   if (isConstantFPBuildVectorOrConstantFP(N0))
10946     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10947
10948   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10949                          &DAG.getTarget().Options))
10950     return GetNegatedExpression(N0, DAG, LegalOperations);
10951
10952   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10953   // constant pool values.
10954   if (!TLI.isFNegFree(VT) &&
10955       N0.getOpcode() == ISD::BITCAST &&
10956       N0.getNode()->hasOneUse()) {
10957     SDValue Int = N0.getOperand(0);
10958     EVT IntVT = Int.getValueType();
10959     if (IntVT.isInteger() && !IntVT.isVector()) {
10960       APInt SignMask;
10961       if (N0.getValueType().isVector()) {
10962         // For a vector, get a mask such as 0x80... per scalar element
10963         // and splat it.
10964         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10965         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10966       } else {
10967         // For a scalar, just generate 0x80...
10968         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10969       }
10970       SDLoc DL0(N0);
10971       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10972                         DAG.getConstant(SignMask, DL0, IntVT));
10973       AddToWorklist(Int.getNode());
10974       return DAG.getBitcast(VT, Int);
10975     }
10976   }
10977
10978   // (fneg (fmul c, x)) -> (fmul -c, x)
10979   if (N0.getOpcode() == ISD::FMUL &&
10980       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10981     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10982     if (CFP1) {
10983       APFloat CVal = CFP1->getValueAPF();
10984       CVal.changeSign();
10985       if (Level >= AfterLegalizeDAG &&
10986           (TLI.isFPImmLegal(CVal, VT) ||
10987            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10988         return DAG.getNode(
10989             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10990             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10991             N0->getFlags());
10992     }
10993   }
10994
10995   return SDValue();
10996 }
10997
10998 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10999   SDValue N0 = N->getOperand(0);
11000   SDValue N1 = N->getOperand(1);
11001   EVT VT = N->getValueType(0);
11002   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11003   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11004
11005   if (N0CFP && N1CFP) {
11006     const APFloat &C0 = N0CFP->getValueAPF();
11007     const APFloat &C1 = N1CFP->getValueAPF();
11008     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11009   }
11010
11011   // Canonicalize to constant on RHS.
11012   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11013      !isConstantFPBuildVectorOrConstantFP(N1))
11014     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11015
11016   return SDValue();
11017 }
11018
11019 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11020   SDValue N0 = N->getOperand(0);
11021   SDValue N1 = N->getOperand(1);
11022   EVT VT = N->getValueType(0);
11023   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11024   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11025
11026   if (N0CFP && N1CFP) {
11027     const APFloat &C0 = N0CFP->getValueAPF();
11028     const APFloat &C1 = N1CFP->getValueAPF();
11029     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11030   }
11031
11032   // Canonicalize to constant on RHS.
11033   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11034      !isConstantFPBuildVectorOrConstantFP(N1))
11035     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11036
11037   return SDValue();
11038 }
11039
11040 SDValue DAGCombiner::visitFABS(SDNode *N) {
11041   SDValue N0 = N->getOperand(0);
11042   EVT VT = N->getValueType(0);
11043
11044   // fold (fabs c1) -> fabs(c1)
11045   if (isConstantFPBuildVectorOrConstantFP(N0))
11046     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11047
11048   // fold (fabs (fabs x)) -> (fabs x)
11049   if (N0.getOpcode() == ISD::FABS)
11050     return N->getOperand(0);
11051
11052   // fold (fabs (fneg x)) -> (fabs x)
11053   // fold (fabs (fcopysign x, y)) -> (fabs x)
11054   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11055     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11056
11057   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11058   // constant pool values.
11059   if (!TLI.isFAbsFree(VT) &&
11060       N0.getOpcode() == ISD::BITCAST &&
11061       N0.getNode()->hasOneUse()) {
11062     SDValue Int = N0.getOperand(0);
11063     EVT IntVT = Int.getValueType();
11064     if (IntVT.isInteger() && !IntVT.isVector()) {
11065       APInt SignMask;
11066       if (N0.getValueType().isVector()) {
11067         // For a vector, get a mask such as 0x7f... per scalar element
11068         // and splat it.
11069         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11070         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11071       } else {
11072         // For a scalar, just generate 0x7f...
11073         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11074       }
11075       SDLoc DL(N0);
11076       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11077                         DAG.getConstant(SignMask, DL, IntVT));
11078       AddToWorklist(Int.getNode());
11079       return DAG.getBitcast(N->getValueType(0), Int);
11080     }
11081   }
11082
11083   return SDValue();
11084 }
11085
11086 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11087   SDValue Chain = N->getOperand(0);
11088   SDValue N1 = N->getOperand(1);
11089   SDValue N2 = N->getOperand(2);
11090
11091   // If N is a constant we could fold this into a fallthrough or unconditional
11092   // branch. However that doesn't happen very often in normal code, because
11093   // Instcombine/SimplifyCFG should have handled the available opportunities.
11094   // If we did this folding here, it would be necessary to update the
11095   // MachineBasicBlock CFG, which is awkward.
11096
11097   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11098   // on the target.
11099   if (N1.getOpcode() == ISD::SETCC &&
11100       TLI.isOperationLegalOrCustom(ISD::BR_CC,
11101                                    N1.getOperand(0).getValueType())) {
11102     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11103                        Chain, N1.getOperand(2),
11104                        N1.getOperand(0), N1.getOperand(1), N2);
11105   }
11106
11107   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
11108       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
11109        (N1.getOperand(0).hasOneUse() &&
11110         N1.getOperand(0).getOpcode() == ISD::SRL))) {
11111     SDNode *Trunc = nullptr;
11112     if (N1.getOpcode() == ISD::TRUNCATE) {
11113       // Look pass the truncate.
11114       Trunc = N1.getNode();
11115       N1 = N1.getOperand(0);
11116     }
11117
11118     // Match this pattern so that we can generate simpler code:
11119     //
11120     //   %a = ...
11121     //   %b = and i32 %a, 2
11122     //   %c = srl i32 %b, 1
11123     //   brcond i32 %c ...
11124     //
11125     // into
11126     //
11127     //   %a = ...
11128     //   %b = and i32 %a, 2
11129     //   %c = setcc eq %b, 0
11130     //   brcond %c ...
11131     //
11132     // This applies only when the AND constant value has one bit set and the
11133     // SRL constant is equal to the log2 of the AND constant. The back-end is
11134     // smart enough to convert the result into a TEST/JMP sequence.
11135     SDValue Op0 = N1.getOperand(0);
11136     SDValue Op1 = N1.getOperand(1);
11137
11138     if (Op0.getOpcode() == ISD::AND &&
11139         Op1.getOpcode() == ISD::Constant) {
11140       SDValue AndOp1 = Op0.getOperand(1);
11141
11142       if (AndOp1.getOpcode() == ISD::Constant) {
11143         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11144
11145         if (AndConst.isPowerOf2() &&
11146             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
11147           SDLoc DL(N);
11148           SDValue SetCC =
11149             DAG.getSetCC(DL,
11150                          getSetCCResultType(Op0.getValueType()),
11151                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11152                          ISD::SETNE);
11153
11154           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
11155                                           MVT::Other, Chain, SetCC, N2);
11156           // Don't add the new BRCond into the worklist or else SimplifySelectCC
11157           // will convert it back to (X & C1) >> C2.
11158           CombineTo(N, NewBRCond, false);
11159           // Truncate is dead.
11160           if (Trunc)
11161             deleteAndRecombine(Trunc);
11162           // Replace the uses of SRL with SETCC
11163           WorklistRemover DeadNodes(*this);
11164           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11165           deleteAndRecombine(N1.getNode());
11166           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11167         }
11168       }
11169     }
11170
11171     if (Trunc)
11172       // Restore N1 if the above transformation doesn't match.
11173       N1 = N->getOperand(1);
11174   }
11175
11176   // Transform br(xor(x, y)) -> br(x != y)
11177   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11178   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
11179     SDNode *TheXor = N1.getNode();
11180     SDValue Op0 = TheXor->getOperand(0);
11181     SDValue Op1 = TheXor->getOperand(1);
11182     if (Op0.getOpcode() == Op1.getOpcode()) {
11183       // Avoid missing important xor optimizations.
11184       if (SDValue Tmp = visitXOR(TheXor)) {
11185         if (Tmp.getNode() != TheXor) {
11186           DEBUG(dbgs() << "\nReplacing.8 ";
11187                 TheXor->dump(&DAG);
11188                 dbgs() << "\nWith: ";
11189                 Tmp.getNode()->dump(&DAG);
11190                 dbgs() << '\n');
11191           WorklistRemover DeadNodes(*this);
11192           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
11193           deleteAndRecombine(TheXor);
11194           return DAG.getNode(ISD::BRCOND, SDLoc(N),
11195                              MVT::Other, Chain, Tmp, N2);
11196         }
11197
11198         // visitXOR has changed XOR's operands or replaced the XOR completely,
11199         // bail out.
11200         return SDValue(N, 0);
11201       }
11202     }
11203
11204     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11205       bool Equal = false;
11206       if (isOneConstant(Op0) && Op0.hasOneUse() &&
11207           Op0.getOpcode() == ISD::XOR) {
11208         TheXor = Op0.getNode();
11209         Equal = true;
11210       }
11211
11212       EVT SetCCVT = N1.getValueType();
11213       if (LegalTypes)
11214         SetCCVT = getSetCCResultType(SetCCVT);
11215       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
11216                                    SetCCVT,
11217                                    Op0, Op1,
11218                                    Equal ? ISD::SETEQ : ISD::SETNE);
11219       // Replace the uses of XOR with SETCC
11220       WorklistRemover DeadNodes(*this);
11221       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11222       deleteAndRecombine(N1.getNode());
11223       return DAG.getNode(ISD::BRCOND, SDLoc(N),
11224                          MVT::Other, Chain, SetCC, N2);
11225     }
11226   }
11227
11228   return SDValue();
11229 }
11230
11231 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11232 //
11233 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11234   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11235   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11236
11237   // If N is a constant we could fold this into a fallthrough or unconditional
11238   // branch. However that doesn't happen very often in normal code, because
11239   // Instcombine/SimplifyCFG should have handled the available opportunities.
11240   // If we did this folding here, it would be necessary to update the
11241   // MachineBasicBlock CFG, which is awkward.
11242
11243   // Use SimplifySetCC to simplify SETCC's.
11244   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11245                                CondLHS, CondRHS, CC->get(), SDLoc(N),
11246                                false);
11247   if (Simp.getNode()) AddToWorklist(Simp.getNode());
11248
11249   // fold to a simpler setcc
11250   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11251     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11252                        N->getOperand(0), Simp.getOperand(2),
11253                        Simp.getOperand(0), Simp.getOperand(1),
11254                        N->getOperand(4));
11255
11256   return SDValue();
11257 }
11258
11259 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11260 /// and that N may be folded in the load / store addressing mode.
11261 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11262                                     SelectionDAG &DAG,
11263                                     const TargetLowering &TLI) {
11264   EVT VT;
11265   unsigned AS;
11266
11267   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11268     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11269       return false;
11270     VT = LD->getMemoryVT();
11271     AS = LD->getAddressSpace();
11272   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11273     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11274       return false;
11275     VT = ST->getMemoryVT();
11276     AS = ST->getAddressSpace();
11277   } else
11278     return false;
11279
11280   TargetLowering::AddrMode AM;
11281   if (N->getOpcode() == ISD::ADD) {
11282     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11283     if (Offset)
11284       // [reg +/- imm]
11285       AM.BaseOffs = Offset->getSExtValue();
11286     else
11287       // [reg +/- reg]
11288       AM.Scale = 1;
11289   } else if (N->getOpcode() == ISD::SUB) {
11290     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11291     if (Offset)
11292       // [reg +/- imm]
11293       AM.BaseOffs = -Offset->getSExtValue();
11294     else
11295       // [reg +/- reg]
11296       AM.Scale = 1;
11297   } else
11298     return false;
11299
11300   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11301                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11302 }
11303
11304 /// Try turning a load/store into a pre-indexed load/store when the base
11305 /// pointer is an add or subtract and it has other uses besides the load/store.
11306 /// After the transformation, the new indexed load/store has effectively folded
11307 /// the add/subtract in and all of its other uses are redirected to the
11308 /// new load/store.
11309 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11310   if (Level < AfterLegalizeDAG)
11311     return false;
11312
11313   bool isLoad = true;
11314   SDValue Ptr;
11315   EVT VT;
11316   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11317     if (LD->isIndexed())
11318       return false;
11319     VT = LD->getMemoryVT();
11320     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11321         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11322       return false;
11323     Ptr = LD->getBasePtr();
11324   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11325     if (ST->isIndexed())
11326       return false;
11327     VT = ST->getMemoryVT();
11328     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11329         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11330       return false;
11331     Ptr = ST->getBasePtr();
11332     isLoad = false;
11333   } else {
11334     return false;
11335   }
11336
11337   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11338   // out.  There is no reason to make this a preinc/predec.
11339   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11340       Ptr.getNode()->hasOneUse())
11341     return false;
11342
11343   // Ask the target to do addressing mode selection.
11344   SDValue BasePtr;
11345   SDValue Offset;
11346   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11347   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11348     return false;
11349
11350   // Backends without true r+i pre-indexed forms may need to pass a
11351   // constant base with a variable offset so that constant coercion
11352   // will work with the patterns in canonical form.
11353   bool Swapped = false;
11354   if (isa<ConstantSDNode>(BasePtr)) {
11355     std::swap(BasePtr, Offset);
11356     Swapped = true;
11357   }
11358
11359   // Don't create a indexed load / store with zero offset.
11360   if (isNullConstant(Offset))
11361     return false;
11362
11363   // Try turning it into a pre-indexed load / store except when:
11364   // 1) The new base ptr is a frame index.
11365   // 2) If N is a store and the new base ptr is either the same as or is a
11366   //    predecessor of the value being stored.
11367   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11368   //    that would create a cycle.
11369   // 4) All uses are load / store ops that use it as old base ptr.
11370
11371   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11372   // (plus the implicit offset) to a register to preinc anyway.
11373   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11374     return false;
11375
11376   // Check #2.
11377   if (!isLoad) {
11378     SDValue Val = cast<StoreSDNode>(N)->getValue();
11379     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11380       return false;
11381   }
11382
11383   // Caches for hasPredecessorHelper.
11384   SmallPtrSet<const SDNode *, 32> Visited;
11385   SmallVector<const SDNode *, 16> Worklist;
11386   Worklist.push_back(N);
11387
11388   // If the offset is a constant, there may be other adds of constants that
11389   // can be folded with this one. We should do this to avoid having to keep
11390   // a copy of the original base pointer.
11391   SmallVector<SDNode *, 16> OtherUses;
11392   if (isa<ConstantSDNode>(Offset))
11393     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11394                               UE = BasePtr.getNode()->use_end();
11395          UI != UE; ++UI) {
11396       SDUse &Use = UI.getUse();
11397       // Skip the use that is Ptr and uses of other results from BasePtr's
11398       // node (important for nodes that return multiple results).
11399       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11400         continue;
11401
11402       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11403         continue;
11404
11405       if (Use.getUser()->getOpcode() != ISD::ADD &&
11406           Use.getUser()->getOpcode() != ISD::SUB) {
11407         OtherUses.clear();
11408         break;
11409       }
11410
11411       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11412       if (!isa<ConstantSDNode>(Op1)) {
11413         OtherUses.clear();
11414         break;
11415       }
11416
11417       // FIXME: In some cases, we can be smarter about this.
11418       if (Op1.getValueType() != Offset.getValueType()) {
11419         OtherUses.clear();
11420         break;
11421       }
11422
11423       OtherUses.push_back(Use.getUser());
11424     }
11425
11426   if (Swapped)
11427     std::swap(BasePtr, Offset);
11428
11429   // Now check for #3 and #4.
11430   bool RealUse = false;
11431
11432   for (SDNode *Use : Ptr.getNode()->uses()) {
11433     if (Use == N)
11434       continue;
11435     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11436       return false;
11437
11438     // If Ptr may be folded in addressing mode of other use, then it's
11439     // not profitable to do this transformation.
11440     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11441       RealUse = true;
11442   }
11443
11444   if (!RealUse)
11445     return false;
11446
11447   SDValue Result;
11448   if (isLoad)
11449     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11450                                 BasePtr, Offset, AM);
11451   else
11452     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11453                                  BasePtr, Offset, AM);
11454   ++PreIndexedNodes;
11455   ++NodesCombined;
11456   DEBUG(dbgs() << "\nReplacing.4 ";
11457         N->dump(&DAG);
11458         dbgs() << "\nWith: ";
11459         Result.getNode()->dump(&DAG);
11460         dbgs() << '\n');
11461   WorklistRemover DeadNodes(*this);
11462   if (isLoad) {
11463     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11464     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11465   } else {
11466     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11467   }
11468
11469   // Finally, since the node is now dead, remove it from the graph.
11470   deleteAndRecombine(N);
11471
11472   if (Swapped)
11473     std::swap(BasePtr, Offset);
11474
11475   // Replace other uses of BasePtr that can be updated to use Ptr
11476   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11477     unsigned OffsetIdx = 1;
11478     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11479       OffsetIdx = 0;
11480     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11481            BasePtr.getNode() && "Expected BasePtr operand");
11482
11483     // We need to replace ptr0 in the following expression:
11484     //   x0 * offset0 + y0 * ptr0 = t0
11485     // knowing that
11486     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11487     //
11488     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11489     // indexed load/store and the expression that needs to be re-written.
11490     //
11491     // Therefore, we have:
11492     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11493
11494     ConstantSDNode *CN =
11495       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11496     int X0, X1, Y0, Y1;
11497     const APInt &Offset0 = CN->getAPIntValue();
11498     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11499
11500     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11501     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11502     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11503     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11504
11505     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11506
11507     APInt CNV = Offset0;
11508     if (X0 < 0) CNV = -CNV;
11509     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11510     else CNV = CNV - Offset1;
11511
11512     SDLoc DL(OtherUses[i]);
11513
11514     // We can now generate the new expression.
11515     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11516     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11517
11518     SDValue NewUse = DAG.getNode(Opcode,
11519                                  DL,
11520                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11521     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11522     deleteAndRecombine(OtherUses[i]);
11523   }
11524
11525   // Replace the uses of Ptr with uses of the updated base value.
11526   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11527   deleteAndRecombine(Ptr.getNode());
11528   AddToWorklist(Result.getNode());
11529
11530   return true;
11531 }
11532
11533 /// Try to combine a load/store with a add/sub of the base pointer node into a
11534 /// post-indexed load/store. The transformation folded the add/subtract into the
11535 /// new indexed load/store effectively and all of its uses are redirected to the
11536 /// new load/store.
11537 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11538   if (Level < AfterLegalizeDAG)
11539     return false;
11540
11541   bool isLoad = true;
11542   SDValue Ptr;
11543   EVT VT;
11544   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11545     if (LD->isIndexed())
11546       return false;
11547     VT = LD->getMemoryVT();
11548     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11549         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11550       return false;
11551     Ptr = LD->getBasePtr();
11552   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11553     if (ST->isIndexed())
11554       return false;
11555     VT = ST->getMemoryVT();
11556     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11557         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11558       return false;
11559     Ptr = ST->getBasePtr();
11560     isLoad = false;
11561   } else {
11562     return false;
11563   }
11564
11565   if (Ptr.getNode()->hasOneUse())
11566     return false;
11567
11568   for (SDNode *Op : Ptr.getNode()->uses()) {
11569     if (Op == N ||
11570         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11571       continue;
11572
11573     SDValue BasePtr;
11574     SDValue Offset;
11575     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11576     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11577       // Don't create a indexed load / store with zero offset.
11578       if (isNullConstant(Offset))
11579         continue;
11580
11581       // Try turning it into a post-indexed load / store except when
11582       // 1) All uses are load / store ops that use it as base ptr (and
11583       //    it may be folded as addressing mmode).
11584       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11585       //    nor a successor of N. Otherwise, if Op is folded that would
11586       //    create a cycle.
11587
11588       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11589         continue;
11590
11591       // Check for #1.
11592       bool TryNext = false;
11593       for (SDNode *Use : BasePtr.getNode()->uses()) {
11594         if (Use == Ptr.getNode())
11595           continue;
11596
11597         // If all the uses are load / store addresses, then don't do the
11598         // transformation.
11599         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11600           bool RealUse = false;
11601           for (SDNode *UseUse : Use->uses()) {
11602             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11603               RealUse = true;
11604           }
11605
11606           if (!RealUse) {
11607             TryNext = true;
11608             break;
11609           }
11610         }
11611       }
11612
11613       if (TryNext)
11614         continue;
11615
11616       // Check for #2
11617       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11618         SDValue Result = isLoad
11619           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11620                                BasePtr, Offset, AM)
11621           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11622                                 BasePtr, Offset, AM);
11623         ++PostIndexedNodes;
11624         ++NodesCombined;
11625         DEBUG(dbgs() << "\nReplacing.5 ";
11626               N->dump(&DAG);
11627               dbgs() << "\nWith: ";
11628               Result.getNode()->dump(&DAG);
11629               dbgs() << '\n');
11630         WorklistRemover DeadNodes(*this);
11631         if (isLoad) {
11632           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11633           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11634         } else {
11635           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11636         }
11637
11638         // Finally, since the node is now dead, remove it from the graph.
11639         deleteAndRecombine(N);
11640
11641         // Replace the uses of Use with uses of the updated base value.
11642         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11643                                       Result.getValue(isLoad ? 1 : 0));
11644         deleteAndRecombine(Op);
11645         return true;
11646       }
11647     }
11648   }
11649
11650   return false;
11651 }
11652
11653 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11654 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11655   ISD::MemIndexedMode AM = LD->getAddressingMode();
11656   assert(AM != ISD::UNINDEXED);
11657   SDValue BP = LD->getOperand(1);
11658   SDValue Inc = LD->getOperand(2);
11659
11660   // Some backends use TargetConstants for load offsets, but don't expect
11661   // TargetConstants in general ADD nodes. We can convert these constants into
11662   // regular Constants (if the constant is not opaque).
11663   assert((Inc.getOpcode() != ISD::TargetConstant ||
11664           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11665          "Cannot split out indexing using opaque target constants");
11666   if (Inc.getOpcode() == ISD::TargetConstant) {
11667     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11668     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11669                           ConstInc->getValueType(0));
11670   }
11671
11672   unsigned Opc =
11673       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11674   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11675 }
11676
11677 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11678   LoadSDNode *LD  = cast<LoadSDNode>(N);
11679   SDValue Chain = LD->getChain();
11680   SDValue Ptr   = LD->getBasePtr();
11681
11682   // If load is not volatile and there are no uses of the loaded value (and
11683   // the updated indexed value in case of indexed loads), change uses of the
11684   // chain value into uses of the chain input (i.e. delete the dead load).
11685   if (!LD->isVolatile()) {
11686     if (N->getValueType(1) == MVT::Other) {
11687       // Unindexed loads.
11688       if (!N->hasAnyUseOfValue(0)) {
11689         // It's not safe to use the two value CombineTo variant here. e.g.
11690         // v1, chain2 = load chain1, loc
11691         // v2, chain3 = load chain2, loc
11692         // v3         = add v2, c
11693         // Now we replace use of chain2 with chain1.  This makes the second load
11694         // isomorphic to the one we are deleting, and thus makes this load live.
11695         DEBUG(dbgs() << "\nReplacing.6 ";
11696               N->dump(&DAG);
11697               dbgs() << "\nWith chain: ";
11698               Chain.getNode()->dump(&DAG);
11699               dbgs() << "\n");
11700         WorklistRemover DeadNodes(*this);
11701         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11702         AddUsersToWorklist(Chain.getNode());
11703         if (N->use_empty())
11704           deleteAndRecombine(N);
11705
11706         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11707       }
11708     } else {
11709       // Indexed loads.
11710       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11711
11712       // If this load has an opaque TargetConstant offset, then we cannot split
11713       // the indexing into an add/sub directly (that TargetConstant may not be
11714       // valid for a different type of node, and we cannot convert an opaque
11715       // target constant into a regular constant).
11716       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11717                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11718
11719       if (!N->hasAnyUseOfValue(0) &&
11720           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11721         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11722         SDValue Index;
11723         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11724           Index = SplitIndexingFromLoad(LD);
11725           // Try to fold the base pointer arithmetic into subsequent loads and
11726           // stores.
11727           AddUsersToWorklist(N);
11728         } else
11729           Index = DAG.getUNDEF(N->getValueType(1));
11730         DEBUG(dbgs() << "\nReplacing.7 ";
11731               N->dump(&DAG);
11732               dbgs() << "\nWith: ";
11733               Undef.getNode()->dump(&DAG);
11734               dbgs() << " and 2 other values\n");
11735         WorklistRemover DeadNodes(*this);
11736         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11737         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11738         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11739         deleteAndRecombine(N);
11740         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11741       }
11742     }
11743   }
11744
11745   // If this load is directly stored, replace the load value with the stored
11746   // value.
11747   // TODO: Handle store large -> read small portion.
11748   // TODO: Handle TRUNCSTORE/LOADEXT
11749   if (OptLevel != CodeGenOpt::None &&
11750       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11751     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11752       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11753       if (PrevST->getBasePtr() == Ptr &&
11754           PrevST->getValue().getValueType() == N->getValueType(0))
11755         return CombineTo(N, PrevST->getOperand(1), Chain);
11756     }
11757   }
11758
11759   // Try to infer better alignment information than the load already has.
11760   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11761     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11762       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11763         SDValue NewLoad = DAG.getExtLoad(
11764             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11765             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11766             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11767         if (NewLoad.getNode() != N)
11768           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11769       }
11770     }
11771   }
11772
11773   if (LD->isUnindexed()) {
11774     // Walk up chain skipping non-aliasing memory nodes.
11775     SDValue BetterChain = FindBetterChain(N, Chain);
11776
11777     // If there is a better chain.
11778     if (Chain != BetterChain) {
11779       SDValue ReplLoad;
11780
11781       // Replace the chain to void dependency.
11782       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11783         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11784                                BetterChain, Ptr, LD->getMemOperand());
11785       } else {
11786         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11787                                   LD->getValueType(0),
11788                                   BetterChain, Ptr, LD->getMemoryVT(),
11789                                   LD->getMemOperand());
11790       }
11791
11792       // Create token factor to keep old chain connected.
11793       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11794                                   MVT::Other, Chain, ReplLoad.getValue(1));
11795
11796       // Replace uses with load result and token factor
11797       return CombineTo(N, ReplLoad.getValue(0), Token);
11798     }
11799   }
11800
11801   // Try transforming N to an indexed load.
11802   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11803     return SDValue(N, 0);
11804
11805   // Try to slice up N to more direct loads if the slices are mapped to
11806   // different register banks or pairing can take place.
11807   if (SliceUpLoad(N))
11808     return SDValue(N, 0);
11809
11810   return SDValue();
11811 }
11812
11813 namespace {
11814
11815 /// \brief Helper structure used to slice a load in smaller loads.
11816 /// Basically a slice is obtained from the following sequence:
11817 /// Origin = load Ty1, Base
11818 /// Shift = srl Ty1 Origin, CstTy Amount
11819 /// Inst = trunc Shift to Ty2
11820 ///
11821 /// Then, it will be rewritten into:
11822 /// Slice = load SliceTy, Base + SliceOffset
11823 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11824 ///
11825 /// SliceTy is deduced from the number of bits that are actually used to
11826 /// build Inst.
11827 struct LoadedSlice {
11828   /// \brief Helper structure used to compute the cost of a slice.
11829   struct Cost {
11830     /// Are we optimizing for code size.
11831     bool ForCodeSize;
11832
11833     /// Various cost.
11834     unsigned Loads = 0;
11835     unsigned Truncates = 0;
11836     unsigned CrossRegisterBanksCopies = 0;
11837     unsigned ZExts = 0;
11838     unsigned Shift = 0;
11839
11840     Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
11841
11842     /// \brief Get the cost of one isolated slice.
11843     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11844         : ForCodeSize(ForCodeSize), Loads(1) {
11845       EVT TruncType = LS.Inst->getValueType(0);
11846       EVT LoadedType = LS.getLoadedType();
11847       if (TruncType != LoadedType &&
11848           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11849         ZExts = 1;
11850     }
11851
11852     /// \brief Account for slicing gain in the current cost.
11853     /// Slicing provide a few gains like removing a shift or a
11854     /// truncate. This method allows to grow the cost of the original
11855     /// load with the gain from this slice.
11856     void addSliceGain(const LoadedSlice &LS) {
11857       // Each slice saves a truncate.
11858       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11859       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11860                               LS.Inst->getValueType(0)))
11861         ++Truncates;
11862       // If there is a shift amount, this slice gets rid of it.
11863       if (LS.Shift)
11864         ++Shift;
11865       // If this slice can merge a cross register bank copy, account for it.
11866       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11867         ++CrossRegisterBanksCopies;
11868     }
11869
11870     Cost &operator+=(const Cost &RHS) {
11871       Loads += RHS.Loads;
11872       Truncates += RHS.Truncates;
11873       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11874       ZExts += RHS.ZExts;
11875       Shift += RHS.Shift;
11876       return *this;
11877     }
11878
11879     bool operator==(const Cost &RHS) const {
11880       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11881              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11882              ZExts == RHS.ZExts && Shift == RHS.Shift;
11883     }
11884
11885     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11886
11887     bool operator<(const Cost &RHS) const {
11888       // Assume cross register banks copies are as expensive as loads.
11889       // FIXME: Do we want some more target hooks?
11890       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11891       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11892       // Unless we are optimizing for code size, consider the
11893       // expensive operation first.
11894       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11895         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11896       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11897              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11898     }
11899
11900     bool operator>(const Cost &RHS) const { return RHS < *this; }
11901
11902     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11903
11904     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11905   };
11906
11907   // The last instruction that represent the slice. This should be a
11908   // truncate instruction.
11909   SDNode *Inst;
11910
11911   // The original load instruction.
11912   LoadSDNode *Origin;
11913
11914   // The right shift amount in bits from the original load.
11915   unsigned Shift;
11916
11917   // The DAG from which Origin came from.
11918   // This is used to get some contextual information about legal types, etc.
11919   SelectionDAG *DAG;
11920
11921   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11922               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11923       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11924
11925   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11926   /// \return Result is \p BitWidth and has used bits set to 1 and
11927   ///         not used bits set to 0.
11928   APInt getUsedBits() const {
11929     // Reproduce the trunc(lshr) sequence:
11930     // - Start from the truncated value.
11931     // - Zero extend to the desired bit width.
11932     // - Shift left.
11933     assert(Origin && "No original load to compare against.");
11934     unsigned BitWidth = Origin->getValueSizeInBits(0);
11935     assert(Inst && "This slice is not bound to an instruction");
11936     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11937            "Extracted slice is bigger than the whole type!");
11938     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11939     UsedBits.setAllBits();
11940     UsedBits = UsedBits.zext(BitWidth);
11941     UsedBits <<= Shift;
11942     return UsedBits;
11943   }
11944
11945   /// \brief Get the size of the slice to be loaded in bytes.
11946   unsigned getLoadedSize() const {
11947     unsigned SliceSize = getUsedBits().countPopulation();
11948     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11949     return SliceSize / 8;
11950   }
11951
11952   /// \brief Get the type that will be loaded for this slice.
11953   /// Note: This may not be the final type for the slice.
11954   EVT getLoadedType() const {
11955     assert(DAG && "Missing context");
11956     LLVMContext &Ctxt = *DAG->getContext();
11957     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11958   }
11959
11960   /// \brief Get the alignment of the load used for this slice.
11961   unsigned getAlignment() const {
11962     unsigned Alignment = Origin->getAlignment();
11963     unsigned Offset = getOffsetFromBase();
11964     if (Offset != 0)
11965       Alignment = MinAlign(Alignment, Alignment + Offset);
11966     return Alignment;
11967   }
11968
11969   /// \brief Check if this slice can be rewritten with legal operations.
11970   bool isLegal() const {
11971     // An invalid slice is not legal.
11972     if (!Origin || !Inst || !DAG)
11973       return false;
11974
11975     // Offsets are for indexed load only, we do not handle that.
11976     if (!Origin->getOffset().isUndef())
11977       return false;
11978
11979     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11980
11981     // Check that the type is legal.
11982     EVT SliceType = getLoadedType();
11983     if (!TLI.isTypeLegal(SliceType))
11984       return false;
11985
11986     // Check that the load is legal for this type.
11987     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11988       return false;
11989
11990     // Check that the offset can be computed.
11991     // 1. Check its type.
11992     EVT PtrType = Origin->getBasePtr().getValueType();
11993     if (PtrType == MVT::Untyped || PtrType.isExtended())
11994       return false;
11995
11996     // 2. Check that it fits in the immediate.
11997     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11998       return false;
11999
12000     // 3. Check that the computation is legal.
12001     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12002       return false;
12003
12004     // Check that the zext is legal if it needs one.
12005     EVT TruncateType = Inst->getValueType(0);
12006     if (TruncateType != SliceType &&
12007         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12008       return false;
12009
12010     return true;
12011   }
12012
12013   /// \brief Get the offset in bytes of this slice in the original chunk of
12014   /// bits.
12015   /// \pre DAG != nullptr.
12016   uint64_t getOffsetFromBase() const {
12017     assert(DAG && "Missing context.");
12018     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12019     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
12020     uint64_t Offset = Shift / 8;
12021     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12022     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
12023            "The size of the original loaded type is not a multiple of a"
12024            " byte.");
12025     // If Offset is bigger than TySizeInBytes, it means we are loading all
12026     // zeros. This should have been optimized before in the process.
12027     assert(TySizeInBytes > Offset &&
12028            "Invalid shift amount for given loaded size");
12029     if (IsBigEndian)
12030       Offset = TySizeInBytes - Offset - getLoadedSize();
12031     return Offset;
12032   }
12033
12034   /// \brief Generate the sequence of instructions to load the slice
12035   /// represented by this object and redirect the uses of this slice to
12036   /// this new sequence of instructions.
12037   /// \pre this->Inst && this->Origin are valid Instructions and this
12038   /// object passed the legal check: LoadedSlice::isLegal returned true.
12039   /// \return The last instruction of the sequence used to load the slice.
12040   SDValue loadSlice() const {
12041     assert(Inst && Origin && "Unable to replace a non-existing slice.");
12042     const SDValue &OldBaseAddr = Origin->getBasePtr();
12043     SDValue BaseAddr = OldBaseAddr;
12044     // Get the offset in that chunk of bytes w.r.t. the endianness.
12045     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12046     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
12047     if (Offset) {
12048       // BaseAddr = BaseAddr + Offset.
12049       EVT ArithType = BaseAddr.getValueType();
12050       SDLoc DL(Origin);
12051       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12052                               DAG->getConstant(Offset, DL, ArithType));
12053     }
12054
12055     // Create the type of the loaded slice according to its size.
12056     EVT SliceType = getLoadedType();
12057
12058     // Create the load for the slice.
12059     SDValue LastInst =
12060         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12061                      Origin->getPointerInfo().getWithOffset(Offset),
12062                      getAlignment(), Origin->getMemOperand()->getFlags());
12063     // If the final type is not the same as the loaded type, this means that
12064     // we have to pad with zero. Create a zero extend for that.
12065     EVT FinalType = Inst->getValueType(0);
12066     if (SliceType != FinalType)
12067       LastInst =
12068           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12069     return LastInst;
12070   }
12071
12072   /// \brief Check if this slice can be merged with an expensive cross register
12073   /// bank copy. E.g.,
12074   /// i = load i32
12075   /// f = bitcast i32 i to float
12076   bool canMergeExpensiveCrossRegisterBankCopy() const {
12077     if (!Inst || !Inst->hasOneUse())
12078       return false;
12079     SDNode *Use = *Inst->use_begin();
12080     if (Use->getOpcode() != ISD::BITCAST)
12081       return false;
12082     assert(DAG && "Missing context");
12083     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12084     EVT ResVT = Use->getValueType(0);
12085     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12086     const TargetRegisterClass *ArgRC =
12087         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12088     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12089       return false;
12090
12091     // At this point, we know that we perform a cross-register-bank copy.
12092     // Check if it is expensive.
12093     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12094     // Assume bitcasts are cheap, unless both register classes do not
12095     // explicitly share a common sub class.
12096     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12097       return false;
12098
12099     // Check if it will be merged with the load.
12100     // 1. Check the alignment constraint.
12101     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12102         ResVT.getTypeForEVT(*DAG->getContext()));
12103
12104     if (RequiredAlignment > getAlignment())
12105       return false;
12106
12107     // 2. Check that the load is a legal operation for that type.
12108     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12109       return false;
12110
12111     // 3. Check that we do not have a zext in the way.
12112     if (Inst->getValueType(0) != getLoadedType())
12113       return false;
12114
12115     return true;
12116   }
12117 };
12118
12119 } // end anonymous namespace
12120
12121 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
12122 /// \p UsedBits looks like 0..0 1..1 0..0.
12123 static bool areUsedBitsDense(const APInt &UsedBits) {
12124   // If all the bits are one, this is dense!
12125   if (UsedBits.isAllOnesValue())
12126     return true;
12127
12128   // Get rid of the unused bits on the right.
12129   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12130   // Get rid of the unused bits on the left.
12131   if (NarrowedUsedBits.countLeadingZeros())
12132     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12133   // Check that the chunk of bits is completely used.
12134   return NarrowedUsedBits.isAllOnesValue();
12135 }
12136
12137 /// \brief Check whether or not \p First and \p Second are next to each other
12138 /// in memory. This means that there is no hole between the bits loaded
12139 /// by \p First and the bits loaded by \p Second.
12140 static bool areSlicesNextToEachOther(const LoadedSlice &First,
12141                                      const LoadedSlice &Second) {
12142   assert(First.Origin == Second.Origin && First.Origin &&
12143          "Unable to match different memory origins.");
12144   APInt UsedBits = First.getUsedBits();
12145   assert((UsedBits & Second.getUsedBits()) == 0 &&
12146          "Slices are not supposed to overlap.");
12147   UsedBits |= Second.getUsedBits();
12148   return areUsedBitsDense(UsedBits);
12149 }
12150
12151 /// \brief Adjust the \p GlobalLSCost according to the target
12152 /// paring capabilities and the layout of the slices.
12153 /// \pre \p GlobalLSCost should account for at least as many loads as
12154 /// there is in the slices in \p LoadedSlices.
12155 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12156                                  LoadedSlice::Cost &GlobalLSCost) {
12157   unsigned NumberOfSlices = LoadedSlices.size();
12158   // If there is less than 2 elements, no pairing is possible.
12159   if (NumberOfSlices < 2)
12160     return;
12161
12162   // Sort the slices so that elements that are likely to be next to each
12163   // other in memory are next to each other in the list.
12164   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
12165             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12166     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
12167     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12168   });
12169   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12170   // First (resp. Second) is the first (resp. Second) potentially candidate
12171   // to be placed in a paired load.
12172   const LoadedSlice *First = nullptr;
12173   const LoadedSlice *Second = nullptr;
12174   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12175                 // Set the beginning of the pair.
12176                                                            First = Second) {
12177     Second = &LoadedSlices[CurrSlice];
12178
12179     // If First is NULL, it means we start a new pair.
12180     // Get to the next slice.
12181     if (!First)
12182       continue;
12183
12184     EVT LoadedType = First->getLoadedType();
12185
12186     // If the types of the slices are different, we cannot pair them.
12187     if (LoadedType != Second->getLoadedType())
12188       continue;
12189
12190     // Check if the target supplies paired loads for this type.
12191     unsigned RequiredAlignment = 0;
12192     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12193       // move to the next pair, this type is hopeless.
12194       Second = nullptr;
12195       continue;
12196     }
12197     // Check if we meet the alignment requirement.
12198     if (RequiredAlignment > First->getAlignment())
12199       continue;
12200
12201     // Check that both loads are next to each other in memory.
12202     if (!areSlicesNextToEachOther(*First, *Second))
12203       continue;
12204
12205     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
12206     --GlobalLSCost.Loads;
12207     // Move to the next pair.
12208     Second = nullptr;
12209   }
12210 }
12211
12212 /// \brief Check the profitability of all involved LoadedSlice.
12213 /// Currently, it is considered profitable if there is exactly two
12214 /// involved slices (1) which are (2) next to each other in memory, and
12215 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12216 ///
12217 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12218 /// the elements themselves.
12219 ///
12220 /// FIXME: When the cost model will be mature enough, we can relax
12221 /// constraints (1) and (2).
12222 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12223                                 const APInt &UsedBits, bool ForCodeSize) {
12224   unsigned NumberOfSlices = LoadedSlices.size();
12225   if (StressLoadSlicing)
12226     return NumberOfSlices > 1;
12227
12228   // Check (1).
12229   if (NumberOfSlices != 2)
12230     return false;
12231
12232   // Check (2).
12233   if (!areUsedBitsDense(UsedBits))
12234     return false;
12235
12236   // Check (3).
12237   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12238   // The original code has one big load.
12239   OrigCost.Loads = 1;
12240   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12241     const LoadedSlice &LS = LoadedSlices[CurrSlice];
12242     // Accumulate the cost of all the slices.
12243     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12244     GlobalSlicingCost += SliceCost;
12245
12246     // Account as cost in the original configuration the gain obtained
12247     // with the current slices.
12248     OrigCost.addSliceGain(LS);
12249   }
12250
12251   // If the target supports paired load, adjust the cost accordingly.
12252   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12253   return OrigCost > GlobalSlicingCost;
12254 }
12255
12256 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12257 /// operations, split it in the various pieces being extracted.
12258 ///
12259 /// This sort of thing is introduced by SROA.
12260 /// This slicing takes care not to insert overlapping loads.
12261 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12262 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12263   if (Level < AfterLegalizeDAG)
12264     return false;
12265
12266   LoadSDNode *LD = cast<LoadSDNode>(N);
12267   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12268       !LD->getValueType(0).isInteger())
12269     return false;
12270
12271   // Keep track of already used bits to detect overlapping values.
12272   // In that case, we will just abort the transformation.
12273   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12274
12275   SmallVector<LoadedSlice, 4> LoadedSlices;
12276
12277   // Check if this load is used as several smaller chunks of bits.
12278   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12279   // of computation for each trunc.
12280   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12281        UI != UIEnd; ++UI) {
12282     // Skip the uses of the chain.
12283     if (UI.getUse().getResNo() != 0)
12284       continue;
12285
12286     SDNode *User = *UI;
12287     unsigned Shift = 0;
12288
12289     // Check if this is a trunc(lshr).
12290     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12291         isa<ConstantSDNode>(User->getOperand(1))) {
12292       Shift = User->getConstantOperandVal(1);
12293       User = *User->use_begin();
12294     }
12295
12296     // At this point, User is a Truncate, iff we encountered, trunc or
12297     // trunc(lshr).
12298     if (User->getOpcode() != ISD::TRUNCATE)
12299       return false;
12300
12301     // The width of the type must be a power of 2 and greater than 8-bits.
12302     // Otherwise the load cannot be represented in LLVM IR.
12303     // Moreover, if we shifted with a non-8-bits multiple, the slice
12304     // will be across several bytes. We do not support that.
12305     unsigned Width = User->getValueSizeInBits(0);
12306     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12307       return false;
12308
12309     // Build the slice for this chain of computations.
12310     LoadedSlice LS(User, LD, Shift, &DAG);
12311     APInt CurrentUsedBits = LS.getUsedBits();
12312
12313     // Check if this slice overlaps with another.
12314     if ((CurrentUsedBits & UsedBits) != 0)
12315       return false;
12316     // Update the bits used globally.
12317     UsedBits |= CurrentUsedBits;
12318
12319     // Check if the new slice would be legal.
12320     if (!LS.isLegal())
12321       return false;
12322
12323     // Record the slice.
12324     LoadedSlices.push_back(LS);
12325   }
12326
12327   // Abort slicing if it does not seem to be profitable.
12328   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12329     return false;
12330
12331   ++SlicedLoads;
12332
12333   // Rewrite each chain to use an independent load.
12334   // By construction, each chain can be represented by a unique load.
12335
12336   // Prepare the argument for the new token factor for all the slices.
12337   SmallVector<SDValue, 8> ArgChains;
12338   for (SmallVectorImpl<LoadedSlice>::const_iterator
12339            LSIt = LoadedSlices.begin(),
12340            LSItEnd = LoadedSlices.end();
12341        LSIt != LSItEnd; ++LSIt) {
12342     SDValue SliceInst = LSIt->loadSlice();
12343     CombineTo(LSIt->Inst, SliceInst, true);
12344     if (SliceInst.getOpcode() != ISD::LOAD)
12345       SliceInst = SliceInst.getOperand(0);
12346     assert(SliceInst->getOpcode() == ISD::LOAD &&
12347            "It takes more than a zext to get to the loaded slice!!");
12348     ArgChains.push_back(SliceInst.getValue(1));
12349   }
12350
12351   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12352                               ArgChains);
12353   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12354   AddToWorklist(Chain.getNode());
12355   return true;
12356 }
12357
12358 /// Check to see if V is (and load (ptr), imm), where the load is having
12359 /// specific bytes cleared out.  If so, return the byte size being masked out
12360 /// and the shift amount.
12361 static std::pair<unsigned, unsigned>
12362 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12363   std::pair<unsigned, unsigned> Result(0, 0);
12364
12365   // Check for the structure we're looking for.
12366   if (V->getOpcode() != ISD::AND ||
12367       !isa<ConstantSDNode>(V->getOperand(1)) ||
12368       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12369     return Result;
12370
12371   // Check the chain and pointer.
12372   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12373   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12374
12375   // The store should be chained directly to the load or be an operand of a
12376   // tokenfactor.
12377   if (LD == Chain.getNode())
12378     ; // ok.
12379   else if (Chain->getOpcode() != ISD::TokenFactor)
12380     return Result; // Fail.
12381   else {
12382     bool isOk = false;
12383     for (const SDValue &ChainOp : Chain->op_values())
12384       if (ChainOp.getNode() == LD) {
12385         isOk = true;
12386         break;
12387       }
12388     if (!isOk) return Result;
12389   }
12390
12391   // This only handles simple types.
12392   if (V.getValueType() != MVT::i16 &&
12393       V.getValueType() != MVT::i32 &&
12394       V.getValueType() != MVT::i64)
12395     return Result;
12396
12397   // Check the constant mask.  Invert it so that the bits being masked out are
12398   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12399   // follow the sign bit for uniformity.
12400   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12401   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12402   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12403   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12404   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12405   if (NotMaskLZ == 64) return Result;  // All zero mask.
12406
12407   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12408   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12409     return Result;
12410
12411   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12412   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12413     NotMaskLZ -= 64-V.getValueSizeInBits();
12414
12415   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12416   switch (MaskedBytes) {
12417   case 1:
12418   case 2:
12419   case 4: break;
12420   default: return Result; // All one mask, or 5-byte mask.
12421   }
12422
12423   // Verify that the first bit starts at a multiple of mask so that the access
12424   // is aligned the same as the access width.
12425   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12426
12427   Result.first = MaskedBytes;
12428   Result.second = NotMaskTZ/8;
12429   return Result;
12430 }
12431
12432 /// Check to see if IVal is something that provides a value as specified by
12433 /// MaskInfo. If so, replace the specified store with a narrower store of
12434 /// truncated IVal.
12435 static SDNode *
12436 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12437                                 SDValue IVal, StoreSDNode *St,
12438                                 DAGCombiner *DC) {
12439   unsigned NumBytes = MaskInfo.first;
12440   unsigned ByteShift = MaskInfo.second;
12441   SelectionDAG &DAG = DC->getDAG();
12442
12443   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12444   // that uses this.  If not, this is not a replacement.
12445   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12446                                   ByteShift*8, (ByteShift+NumBytes)*8);
12447   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12448
12449   // Check that it is legal on the target to do this.  It is legal if the new
12450   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12451   // legalization.
12452   MVT VT = MVT::getIntegerVT(NumBytes*8);
12453   if (!DC->isTypeLegal(VT))
12454     return nullptr;
12455
12456   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12457   // shifted by ByteShift and truncated down to NumBytes.
12458   if (ByteShift) {
12459     SDLoc DL(IVal);
12460     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12461                        DAG.getConstant(ByteShift*8, DL,
12462                                     DC->getShiftAmountTy(IVal.getValueType())));
12463   }
12464
12465   // Figure out the offset for the store and the alignment of the access.
12466   unsigned StOffset;
12467   unsigned NewAlign = St->getAlignment();
12468
12469   if (DAG.getDataLayout().isLittleEndian())
12470     StOffset = ByteShift;
12471   else
12472     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12473
12474   SDValue Ptr = St->getBasePtr();
12475   if (StOffset) {
12476     SDLoc DL(IVal);
12477     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12478                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12479     NewAlign = MinAlign(NewAlign, StOffset);
12480   }
12481
12482   // Truncate down to the new size.
12483   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12484
12485   ++OpsNarrowed;
12486   return DAG
12487       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12488                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12489       .getNode();
12490 }
12491
12492 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12493 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12494 /// narrowing the load and store if it would end up being a win for performance
12495 /// or code size.
12496 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12497   StoreSDNode *ST  = cast<StoreSDNode>(N);
12498   if (ST->isVolatile())
12499     return SDValue();
12500
12501   SDValue Chain = ST->getChain();
12502   SDValue Value = ST->getValue();
12503   SDValue Ptr   = ST->getBasePtr();
12504   EVT VT = Value.getValueType();
12505
12506   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12507     return SDValue();
12508
12509   unsigned Opc = Value.getOpcode();
12510
12511   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12512   // is a byte mask indicating a consecutive number of bytes, check to see if
12513   // Y is known to provide just those bytes.  If so, we try to replace the
12514   // load + replace + store sequence with a single (narrower) store, which makes
12515   // the load dead.
12516   if (Opc == ISD::OR) {
12517     std::pair<unsigned, unsigned> MaskedLoad;
12518     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12519     if (MaskedLoad.first)
12520       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12521                                                   Value.getOperand(1), ST,this))
12522         return SDValue(NewST, 0);
12523
12524     // Or is commutative, so try swapping X and Y.
12525     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12526     if (MaskedLoad.first)
12527       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12528                                                   Value.getOperand(0), ST,this))
12529         return SDValue(NewST, 0);
12530   }
12531
12532   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12533       Value.getOperand(1).getOpcode() != ISD::Constant)
12534     return SDValue();
12535
12536   SDValue N0 = Value.getOperand(0);
12537   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12538       Chain == SDValue(N0.getNode(), 1)) {
12539     LoadSDNode *LD = cast<LoadSDNode>(N0);
12540     if (LD->getBasePtr() != Ptr ||
12541         LD->getPointerInfo().getAddrSpace() !=
12542         ST->getPointerInfo().getAddrSpace())
12543       return SDValue();
12544
12545     // Find the type to narrow it the load / op / store to.
12546     SDValue N1 = Value.getOperand(1);
12547     unsigned BitWidth = N1.getValueSizeInBits();
12548     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12549     if (Opc == ISD::AND)
12550       Imm ^= APInt::getAllOnesValue(BitWidth);
12551     if (Imm == 0 || Imm.isAllOnesValue())
12552       return SDValue();
12553     unsigned ShAmt = Imm.countTrailingZeros();
12554     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12555     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12556     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12557     // The narrowing should be profitable, the load/store operation should be
12558     // legal (or custom) and the store size should be equal to the NewVT width.
12559     while (NewBW < BitWidth &&
12560            (NewVT.getStoreSizeInBits() != NewBW ||
12561             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12562             !TLI.isNarrowingProfitable(VT, NewVT))) {
12563       NewBW = NextPowerOf2(NewBW);
12564       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12565     }
12566     if (NewBW >= BitWidth)
12567       return SDValue();
12568
12569     // If the lsb changed does not start at the type bitwidth boundary,
12570     // start at the previous one.
12571     if (ShAmt % NewBW)
12572       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12573     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12574                                    std::min(BitWidth, ShAmt + NewBW));
12575     if ((Imm & Mask) == Imm) {
12576       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12577       if (Opc == ISD::AND)
12578         NewImm ^= APInt::getAllOnesValue(NewBW);
12579       uint64_t PtrOff = ShAmt / 8;
12580       // For big endian targets, we need to adjust the offset to the pointer to
12581       // load the correct bytes.
12582       if (DAG.getDataLayout().isBigEndian())
12583         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12584
12585       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12586       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12587       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12588         return SDValue();
12589
12590       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12591                                    Ptr.getValueType(), Ptr,
12592                                    DAG.getConstant(PtrOff, SDLoc(LD),
12593                                                    Ptr.getValueType()));
12594       SDValue NewLD =
12595           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12596                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12597                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12598       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12599                                    DAG.getConstant(NewImm, SDLoc(Value),
12600                                                    NewVT));
12601       SDValue NewST =
12602           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12603                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12604
12605       AddToWorklist(NewPtr.getNode());
12606       AddToWorklist(NewLD.getNode());
12607       AddToWorklist(NewVal.getNode());
12608       WorklistRemover DeadNodes(*this);
12609       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12610       ++OpsNarrowed;
12611       return NewST;
12612     }
12613   }
12614
12615   return SDValue();
12616 }
12617
12618 /// For a given floating point load / store pair, if the load value isn't used
12619 /// by any other operations, then consider transforming the pair to integer
12620 /// load / store operations if the target deems the transformation profitable.
12621 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12622   StoreSDNode *ST  = cast<StoreSDNode>(N);
12623   SDValue Chain = ST->getChain();
12624   SDValue Value = ST->getValue();
12625   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12626       Value.hasOneUse() &&
12627       Chain == SDValue(Value.getNode(), 1)) {
12628     LoadSDNode *LD = cast<LoadSDNode>(Value);
12629     EVT VT = LD->getMemoryVT();
12630     if (!VT.isFloatingPoint() ||
12631         VT != ST->getMemoryVT() ||
12632         LD->isNonTemporal() ||
12633         ST->isNonTemporal() ||
12634         LD->getPointerInfo().getAddrSpace() != 0 ||
12635         ST->getPointerInfo().getAddrSpace() != 0)
12636       return SDValue();
12637
12638     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12639     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12640         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12641         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12642         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12643       return SDValue();
12644
12645     unsigned LDAlign = LD->getAlignment();
12646     unsigned STAlign = ST->getAlignment();
12647     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12648     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12649     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12650       return SDValue();
12651
12652     SDValue NewLD =
12653         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12654                     LD->getPointerInfo(), LDAlign);
12655
12656     SDValue NewST =
12657         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12658                      ST->getPointerInfo(), STAlign);
12659
12660     AddToWorklist(NewLD.getNode());
12661     AddToWorklist(NewST.getNode());
12662     WorklistRemover DeadNodes(*this);
12663     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12664     ++LdStFP2Int;
12665     return NewST;
12666   }
12667
12668   return SDValue();
12669 }
12670
12671 // This is a helper function for visitMUL to check the profitability
12672 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12673 // MulNode is the original multiply, AddNode is (add x, c1),
12674 // and ConstNode is c2.
12675 //
12676 // If the (add x, c1) has multiple uses, we could increase
12677 // the number of adds if we make this transformation.
12678 // It would only be worth doing this if we can remove a
12679 // multiply in the process. Check for that here.
12680 // To illustrate:
12681 //     (A + c1) * c3
12682 //     (A + c2) * c3
12683 // We're checking for cases where we have common "c3 * A" expressions.
12684 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12685                                               SDValue &AddNode,
12686                                               SDValue &ConstNode) {
12687   APInt Val;
12688
12689   // If the add only has one use, this would be OK to do.
12690   if (AddNode.getNode()->hasOneUse())
12691     return true;
12692
12693   // Walk all the users of the constant with which we're multiplying.
12694   for (SDNode *Use : ConstNode->uses()) {
12695     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12696       continue;
12697
12698     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12699       SDNode *OtherOp;
12700       SDNode *MulVar = AddNode.getOperand(0).getNode();
12701
12702       // OtherOp is what we're multiplying against the constant.
12703       if (Use->getOperand(0) == ConstNode)
12704         OtherOp = Use->getOperand(1).getNode();
12705       else
12706         OtherOp = Use->getOperand(0).getNode();
12707
12708       // Check to see if multiply is with the same operand of our "add".
12709       //
12710       //     ConstNode  = CONST
12711       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12712       //     ...
12713       //     AddNode  = (A + c1)  <-- MulVar is A.
12714       //         = AddNode * ConstNode   <-- current visiting instruction.
12715       //
12716       // If we make this transformation, we will have a common
12717       // multiply (ConstNode * A) that we can save.
12718       if (OtherOp == MulVar)
12719         return true;
12720
12721       // Now check to see if a future expansion will give us a common
12722       // multiply.
12723       //
12724       //     ConstNode  = CONST
12725       //     AddNode    = (A + c1)
12726       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12727       //     ...
12728       //     OtherOp = (A + c2)
12729       //     Use     = OtherOp * ConstNode <-- visiting Use.
12730       //
12731       // If we make this transformation, we will have a common
12732       // multiply (CONST * A) after we also do the same transformation
12733       // to the "t2" instruction.
12734       if (OtherOp->getOpcode() == ISD::ADD &&
12735           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12736           OtherOp->getOperand(0).getNode() == MulVar)
12737         return true;
12738     }
12739   }
12740
12741   // Didn't find a case where this would be profitable.
12742   return false;
12743 }
12744
12745 static SDValue peekThroughBitcast(SDValue V) {
12746   while (V.getOpcode() == ISD::BITCAST)
12747     V = V.getOperand(0);
12748   return V;
12749 }
12750
12751 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12752                                          unsigned NumStores) {
12753   SmallVector<SDValue, 8> Chains;
12754   SmallPtrSet<const SDNode *, 8> Visited;
12755   SDLoc StoreDL(StoreNodes[0].MemNode);
12756
12757   for (unsigned i = 0; i < NumStores; ++i) {
12758     Visited.insert(StoreNodes[i].MemNode);
12759   }
12760
12761   // don't include nodes that are children
12762   for (unsigned i = 0; i < NumStores; ++i) {
12763     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12764       Chains.push_back(StoreNodes[i].MemNode->getChain());
12765   }
12766
12767   assert(Chains.size() > 0 && "Chain should have generated a chain");
12768   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12769 }
12770
12771 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12772     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12773     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12774   // Make sure we have something to merge.
12775   if (NumStores < 2)
12776     return false;
12777
12778   // The latest Node in the DAG.
12779   SDLoc DL(StoreNodes[0].MemNode);
12780
12781   int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
12782   unsigned SizeInBits = NumStores * ElementSizeBits;
12783   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12784
12785   EVT StoreTy;
12786   if (UseVector) {
12787     unsigned Elts = NumStores * NumMemElts;
12788     // Get the type for the merged vector store.
12789     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12790   } else
12791     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12792
12793   SDValue StoredVal;
12794   if (UseVector) {
12795     if (IsConstantSrc) {
12796       SmallVector<SDValue, 8> BuildVector;
12797       for (unsigned I = 0; I != NumStores; ++I) {
12798         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12799         SDValue Val = St->getValue();
12800         // If constant is of the wrong type, convert it now.
12801         if (MemVT != Val.getValueType()) {
12802           Val = peekThroughBitcast(Val);
12803           // Deal with constants of wrong size.
12804           if (ElementSizeBits != Val.getValueSizeInBits()) {
12805             EVT IntMemVT =
12806                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12807             if (isa<ConstantFPSDNode>(Val)) {
12808               // Not clear how to truncate FP values.
12809               return false;
12810             } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12811               Val = DAG.getConstant(C->getAPIntValue()
12812                                         .zextOrTrunc(Val.getValueSizeInBits())
12813                                         .zextOrTrunc(ElementSizeBits),
12814                                     SDLoc(C), IntMemVT);
12815           }
12816           // Make sure correctly size type is the correct type.
12817           Val = DAG.getBitcast(MemVT, Val);
12818         }
12819         BuildVector.push_back(Val);
12820       }
12821       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12822                                                : ISD::BUILD_VECTOR,
12823                               DL, StoreTy, BuildVector);
12824     } else {
12825       SmallVector<SDValue, 8> Ops;
12826       for (unsigned i = 0; i < NumStores; ++i) {
12827         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12828         SDValue Val = peekThroughBitcast(St->getValue());
12829         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12830         // type MemVT. If the underlying value is not the correct
12831         // type, but it is an extraction of an appropriate vector we
12832         // can recast Val to be of the correct type. This may require
12833         // converting between EXTRACT_VECTOR_ELT and
12834         // EXTRACT_SUBVECTOR.
12835         if ((MemVT != Val.getValueType()) &&
12836             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12837              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12838           SDValue Vec = Val.getOperand(0);
12839           EVT MemVTScalarTy = MemVT.getScalarType();
12840           // We may need to add a bitcast here to get types to line up.
12841           if (MemVTScalarTy != Vec.getValueType()) {
12842             unsigned Elts = Vec.getValueType().getSizeInBits() /
12843                             MemVTScalarTy.getSizeInBits();
12844             EVT NewVecTy =
12845                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12846             Vec = DAG.getBitcast(NewVecTy, Vec);
12847           }
12848           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12849                                         : ISD::EXTRACT_VECTOR_ELT;
12850           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12851         }
12852         Ops.push_back(Val);
12853       }
12854
12855       // Build the extracted vector elements back into a vector.
12856       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12857                                                : ISD::BUILD_VECTOR,
12858                               DL, StoreTy, Ops);
12859     }
12860   } else {
12861     // We should always use a vector store when merging extracted vector
12862     // elements, so this path implies a store of constants.
12863     assert(IsConstantSrc && "Merged vector elements should use vector store");
12864
12865     APInt StoreInt(SizeInBits, 0);
12866
12867     // Construct a single integer constant which is made of the smaller
12868     // constant inputs.
12869     bool IsLE = DAG.getDataLayout().isLittleEndian();
12870     for (unsigned i = 0; i < NumStores; ++i) {
12871       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12872       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12873
12874       SDValue Val = St->getValue();
12875       StoreInt <<= ElementSizeBits;
12876       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12877         StoreInt |= C->getAPIntValue()
12878                         .zextOrTrunc(ElementSizeBits)
12879                         .zextOrTrunc(SizeInBits);
12880       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12881         StoreInt |= C->getValueAPF()
12882                         .bitcastToAPInt()
12883                         .zextOrTrunc(ElementSizeBits)
12884                         .zextOrTrunc(SizeInBits);
12885         // If fp truncation is necessary give up for now.
12886         if (MemVT.getSizeInBits() != ElementSizeBits)
12887           return false;
12888       } else {
12889         llvm_unreachable("Invalid constant element type");
12890       }
12891     }
12892
12893     // Create the new Load and Store operations.
12894     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12895   }
12896
12897   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12898   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12899
12900   // make sure we use trunc store if it's necessary to be legal.
12901   SDValue NewStore;
12902   if (!UseTrunc) {
12903     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12904                             FirstInChain->getPointerInfo(),
12905                             FirstInChain->getAlignment());
12906   } else { // Must be realized as a trunc store
12907     EVT LegalizedStoredValueTy =
12908         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12909     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12910     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12911     SDValue ExtendedStoreVal =
12912         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12913                         LegalizedStoredValueTy);
12914     NewStore = DAG.getTruncStore(
12915         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12916         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12917         FirstInChain->getAlignment(),
12918         FirstInChain->getMemOperand()->getFlags());
12919   }
12920
12921   // Replace all merged stores with the new store.
12922   for (unsigned i = 0; i < NumStores; ++i)
12923     CombineTo(StoreNodes[i].MemNode, NewStore);
12924
12925   AddToWorklist(NewChain.getNode());
12926   return true;
12927 }
12928
12929 void DAGCombiner::getStoreMergeCandidates(
12930     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12931   // This holds the base pointer, index, and the offset in bytes from the base
12932   // pointer.
12933   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12934   EVT MemVT = St->getMemoryVT();
12935
12936   SDValue Val = peekThroughBitcast(St->getValue());
12937   // We must have a base and an offset.
12938   if (!BasePtr.getBase().getNode())
12939     return;
12940
12941   // Do not handle stores to undef base pointers.
12942   if (BasePtr.getBase().isUndef())
12943     return;
12944
12945   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
12946   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12947                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12948   bool IsLoadSrc = isa<LoadSDNode>(Val);
12949   BaseIndexOffset LBasePtr;
12950   // Match on loadbaseptr if relevant.
12951   EVT LoadVT;
12952   if (IsLoadSrc) {
12953     auto *Ld = cast<LoadSDNode>(Val);
12954     LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12955     LoadVT = Ld->getMemoryVT();
12956     // Load and store should be the same type.
12957     if (MemVT != LoadVT)
12958       return;
12959   }
12960   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12961                             int64_t &Offset) -> bool {
12962     if (Other->isVolatile() || Other->isIndexed())
12963       return false;
12964     SDValue Val = peekThroughBitcast(Other->getValue());
12965     // Allow merging constants of different types as integers.
12966     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
12967                                            : Other->getMemoryVT() != MemVT;
12968     if (IsLoadSrc) {
12969       if (NoTypeMatch)
12970         return false;
12971       // The Load's Base Ptr must also match
12972       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
12973         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12974         if (LoadVT != OtherLd->getMemoryVT())
12975           return false;
12976         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12977           return false;
12978       } else
12979         return false;
12980     }
12981     if (IsConstantSrc) {
12982       if (NoTypeMatch)
12983         return false;
12984       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
12985         return false;
12986     }
12987     if (IsExtractVecSrc) {
12988       // Do not merge truncated stores here.
12989       if (Other->isTruncatingStore())
12990         return false;
12991       if (!MemVT.bitsEq(Val.getValueType()))
12992         return false;
12993       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
12994           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12995         return false;
12996     }
12997     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12998     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12999   };
13000
13001   // We looking for a root node which is an ancestor to all mergable
13002   // stores. We search up through a load, to our root and then down
13003   // through all children. For instance we will find Store{1,2,3} if
13004   // St is Store1, Store2. or Store3 where the root is not a load
13005   // which always true for nonvolatile ops. TODO: Expand
13006   // the search to find all valid candidates through multiple layers of loads.
13007   //
13008   // Root
13009   // |-------|-------|
13010   // Load    Load    Store3
13011   // |       |
13012   // Store1   Store2
13013   //
13014   // FIXME: We should be able to climb and
13015   // descend TokenFactors to find candidates as well.
13016
13017   SDNode *RootNode = (St->getChain()).getNode();
13018
13019   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13020     RootNode = Ldn->getChain().getNode();
13021     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13022       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13023         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13024           if (I2.getOperandNo() == 0)
13025             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13026               BaseIndexOffset Ptr;
13027               int64_t PtrDiff;
13028               if (CandidateMatch(OtherST, Ptr, PtrDiff))
13029                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13030             }
13031   } else
13032     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13033       if (I.getOperandNo() == 0)
13034         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13035           BaseIndexOffset Ptr;
13036           int64_t PtrDiff;
13037           if (CandidateMatch(OtherST, Ptr, PtrDiff))
13038             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13039         }
13040 }
13041
13042 // We need to check that merging these stores does not cause a loop in
13043 // the DAG. Any store candidate may depend on another candidate
13044 // indirectly through its operand (we already consider dependencies
13045 // through the chain). Check in parallel by searching up from
13046 // non-chain operands of candidates.
13047 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13048     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
13049   // FIXME: We should be able to truncate a full search of
13050   // predecessors by doing a BFS and keeping tabs the originating
13051   // stores from which worklist nodes come from in a similar way to
13052   // TokenFactor simplfication.
13053
13054   SmallPtrSet<const SDNode *, 16> Visited;
13055   SmallVector<const SDNode *, 8> Worklist;
13056   unsigned int Max = 8192;
13057   // Search Ops of store candidates.
13058   for (unsigned i = 0; i < NumStores; ++i) {
13059     SDNode *n = StoreNodes[i].MemNode;
13060     // Potential loops may happen only through non-chain operands
13061     for (unsigned j = 1; j < n->getNumOperands(); ++j)
13062       Worklist.push_back(n->getOperand(j).getNode());
13063   }
13064   // Search through DAG. We can stop early if we find a store node.
13065   for (unsigned i = 0; i < NumStores; ++i) {
13066     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13067                                      Max))
13068       return false;
13069     // Check if we ended early, failing conservatively if so.
13070     if (Visited.size() >= Max)
13071       return false;
13072   }
13073   return true;
13074 }
13075
13076 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13077   if (OptLevel == CodeGenOpt::None)
13078     return false;
13079
13080   EVT MemVT = St->getMemoryVT();
13081   int64_t ElementSizeBytes = MemVT.getStoreSize();
13082   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13083
13084   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13085     return false;
13086
13087   bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13088       Attribute::NoImplicitFloat);
13089
13090   // This function cannot currently deal with non-byte-sized memory sizes.
13091   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13092     return false;
13093
13094   if (!MemVT.isSimple())
13095     return false;
13096
13097   // Perform an early exit check. Do not bother looking at stored values that
13098   // are not constants, loads, or extracted vector elements.
13099   SDValue StoredVal = peekThroughBitcast(St->getValue());
13100   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13101   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13102                        isa<ConstantFPSDNode>(StoredVal);
13103   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13104                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13105
13106   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13107     return false;
13108
13109   SmallVector<MemOpLink, 8> StoreNodes;
13110   // Find potential store merge candidates by searching through chain sub-DAG
13111   getStoreMergeCandidates(St, StoreNodes);
13112
13113   // Check if there is anything to merge.
13114   if (StoreNodes.size() < 2)
13115     return false;
13116
13117   // Sort the memory operands according to their distance from the
13118   // base pointer.
13119   std::sort(StoreNodes.begin(), StoreNodes.end(),
13120             [](MemOpLink LHS, MemOpLink RHS) {
13121               return LHS.OffsetFromBase < RHS.OffsetFromBase;
13122             });
13123
13124   // Store Merge attempts to merge the lowest stores. This generally
13125   // works out as if successful, as the remaining stores are checked
13126   // after the first collection of stores is merged. However, in the
13127   // case that a non-mergeable store is found first, e.g., {p[-2],
13128   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13129   // mergeable cases. To prevent this, we prune such stores from the
13130   // front of StoreNodes here.
13131
13132   bool RV = false;
13133   while (StoreNodes.size() > 1) {
13134     unsigned StartIdx = 0;
13135     while ((StartIdx + 1 < StoreNodes.size()) &&
13136            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13137                StoreNodes[StartIdx + 1].OffsetFromBase)
13138       ++StartIdx;
13139
13140     // Bail if we don't have enough candidates to merge.
13141     if (StartIdx + 1 >= StoreNodes.size())
13142       return RV;
13143
13144     if (StartIdx)
13145       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13146
13147     // Scan the memory operations on the chain and find the first
13148     // non-consecutive store memory address.
13149     unsigned NumConsecutiveStores = 1;
13150     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13151     // Check that the addresses are consecutive starting from the second
13152     // element in the list of stores.
13153     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13154       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13155       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13156         break;
13157       NumConsecutiveStores = i + 1;
13158     }
13159
13160     if (NumConsecutiveStores < 2) {
13161       StoreNodes.erase(StoreNodes.begin(),
13162                        StoreNodes.begin() + NumConsecutiveStores);
13163       continue;
13164     }
13165
13166     // Check that we can merge these candidates without causing a cycle
13167     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
13168                                                   NumConsecutiveStores)) {
13169       StoreNodes.erase(StoreNodes.begin(),
13170                        StoreNodes.begin() + NumConsecutiveStores);
13171       continue;
13172     }
13173
13174     // The node with the lowest store address.
13175     LLVMContext &Context = *DAG.getContext();
13176     const DataLayout &DL = DAG.getDataLayout();
13177
13178     // Store the constants into memory as one consecutive store.
13179     if (IsConstantSrc) {
13180       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13181       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13182       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13183       unsigned LastLegalType = 1;
13184       unsigned LastLegalVectorType = 1;
13185       bool LastIntegerTrunc = false;
13186       bool NonZero = false;
13187       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13188       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13189         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13190         SDValue StoredVal = ST->getValue();
13191         bool IsElementZero = false;
13192         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13193           IsElementZero = C->isNullValue();
13194         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13195           IsElementZero = C->getConstantFPValue()->isNullValue();
13196         if (IsElementZero) {
13197           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13198             FirstZeroAfterNonZero = i;
13199         }
13200         NonZero |= !IsElementZero;
13201
13202         // Find a legal type for the constant store.
13203         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13204         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13205         bool IsFast = false;
13206         if (TLI.isTypeLegal(StoreTy) &&
13207             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13208             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13209                                    FirstStoreAlign, &IsFast) &&
13210             IsFast) {
13211           LastIntegerTrunc = false;
13212           LastLegalType = i + 1;
13213           // Or check whether a truncstore is legal.
13214         } else if (TLI.getTypeAction(Context, StoreTy) ==
13215                    TargetLowering::TypePromoteInteger) {
13216           EVT LegalizedStoredValueTy =
13217               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13218           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13219               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13220               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13221                                      FirstStoreAlign, &IsFast) &&
13222               IsFast) {
13223             LastIntegerTrunc = true;
13224             LastLegalType = i + 1;
13225           }
13226         }
13227
13228         // We only use vectors if the constant is known to be zero or the target
13229         // allows it and the function is not marked with the noimplicitfloat
13230         // attribute.
13231         if ((!NonZero ||
13232              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13233             !NoVectors) {
13234           // Find a legal type for the vector store.
13235           unsigned Elts = (i + 1) * NumMemElts;
13236           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13237           if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13238               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13239               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13240                                      FirstStoreAlign, &IsFast) &&
13241               IsFast)
13242             LastLegalVectorType = i + 1;
13243         }
13244       }
13245
13246       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13247       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13248
13249       // Check if we found a legal integer type that creates a meaningful merge.
13250       if (NumElem < 2) {
13251         // We know that candidate stores are in order and of correct
13252         // shape. While there is no mergeable sequence from the
13253         // beginning one may start later in the sequence. The only
13254         // reason a merge of size N could have failed where another of
13255         // the same size would not have, is if the alignment has
13256         // improved or we've dropped a non-zero value. Drop as many
13257         // candidates as we can here.
13258         unsigned NumSkip = 1;
13259         while (
13260             (NumSkip < NumConsecutiveStores) &&
13261             (NumSkip < FirstZeroAfterNonZero) &&
13262             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13263           NumSkip++;
13264         }
13265         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13266         continue;
13267       }
13268
13269       bool Merged = MergeStoresOfConstantsOrVecElts(
13270           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13271       RV |= Merged;
13272
13273       // Remove merged stores for next iteration.
13274       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13275       continue;
13276     }
13277
13278     // When extracting multiple vector elements, try to store them
13279     // in one vector store rather than a sequence of scalar stores.
13280     if (IsExtractVecSrc) {
13281       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13282       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13283       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13284       unsigned NumStoresToMerge = 1;
13285       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13286         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13287         SDValue StVal = peekThroughBitcast(St->getValue());
13288         // This restriction could be loosened.
13289         // Bail out if any stored values are not elements extracted from a
13290         // vector. It should be possible to handle mixed sources, but load
13291         // sources need more careful handling (see the block of code below that
13292         // handles consecutive loads).
13293         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13294             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13295           return RV;
13296
13297         // Find a legal type for the vector store.
13298         unsigned Elts = (i + 1) * NumMemElts;
13299         EVT Ty =
13300             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13301         bool IsFast;
13302         if (TLI.isTypeLegal(Ty) &&
13303             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13304             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13305                                    FirstStoreAlign, &IsFast) &&
13306             IsFast)
13307           NumStoresToMerge = i + 1;
13308       }
13309
13310       // Check if we found a legal integer type that creates a meaningful merge.
13311       if (NumStoresToMerge < 2) {
13312         // We know that candidate stores are in order and of correct
13313         // shape. While there is no mergeable sequence from the
13314         // beginning one may start later in the sequence. The only
13315         // reason a merge of size N could have failed where another of
13316         // the same size would not have, is if the alignment has
13317         // improved. Drop as many candidates as we can here.
13318         unsigned NumSkip = 1;
13319         while ((NumSkip < NumConsecutiveStores) &&
13320                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13321           NumSkip++;
13322
13323         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13324         continue;
13325       }
13326
13327       bool Merged = MergeStoresOfConstantsOrVecElts(
13328           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13329       if (!Merged) {
13330         StoreNodes.erase(StoreNodes.begin(),
13331                          StoreNodes.begin() + NumStoresToMerge);
13332         continue;
13333       }
13334       // Remove merged stores for next iteration.
13335       StoreNodes.erase(StoreNodes.begin(),
13336                        StoreNodes.begin() + NumStoresToMerge);
13337       RV = true;
13338       continue;
13339     }
13340
13341     // Below we handle the case of multiple consecutive stores that
13342     // come from multiple consecutive loads. We merge them into a single
13343     // wide load and a single wide store.
13344
13345     // Look for load nodes which are used by the stored values.
13346     SmallVector<MemOpLink, 8> LoadNodes;
13347
13348     // Find acceptable loads. Loads need to have the same chain (token factor),
13349     // must not be zext, volatile, indexed, and they must be consecutive.
13350     BaseIndexOffset LdBasePtr;
13351     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13352       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13353       SDValue Val = peekThroughBitcast(St->getValue());
13354       LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13355       if (!Ld)
13356         break;
13357
13358       // Loads must only have one use.
13359       if (!Ld->hasNUsesOfValue(1, 0))
13360         break;
13361
13362       // The memory operands must not be volatile.
13363       if (Ld->isVolatile() || Ld->isIndexed())
13364         break;
13365
13366       // The stored memory type must be the same.
13367       if (Ld->getMemoryVT() != MemVT)
13368         break;
13369
13370       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
13371       // If this is not the first ptr that we check.
13372       int64_t LdOffset = 0;
13373       if (LdBasePtr.getBase().getNode()) {
13374         // The base ptr must be the same.
13375         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13376           break;
13377       } else {
13378         // Check that all other base pointers are the same as this one.
13379         LdBasePtr = LdPtr;
13380       }
13381
13382       // We found a potential memory operand to merge.
13383       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13384     }
13385
13386     if (LoadNodes.size() < 2) {
13387       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13388       continue;
13389     }
13390
13391     // If we have load/store pair instructions and we only have two values,
13392     // don't bother merging.
13393     unsigned RequiredAlignment;
13394     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13395         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13396       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13397       continue;
13398     }
13399     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13400     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13401     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13402     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13403     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13404     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13405
13406     // Scan the memory operations on the chain and find the first
13407     // non-consecutive load memory address. These variables hold the index in
13408     // the store node array.
13409     unsigned LastConsecutiveLoad = 1;
13410     // This variable refers to the size and not index in the array.
13411     unsigned LastLegalVectorType = 1;
13412     unsigned LastLegalIntegerType = 1;
13413     bool isDereferenceable = true;
13414     bool DoIntegerTruncate = false;
13415     StartAddress = LoadNodes[0].OffsetFromBase;
13416     SDValue FirstChain = FirstLoad->getChain();
13417     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13418       // All loads must share the same chain.
13419       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13420         break;
13421
13422       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13423       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13424         break;
13425       LastConsecutiveLoad = i;
13426
13427       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13428         isDereferenceable = false;
13429
13430       // Find a legal type for the vector store.
13431       unsigned Elts = (i + 1) * NumMemElts;
13432       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13433
13434       bool IsFastSt, IsFastLd;
13435       if (TLI.isTypeLegal(StoreTy) &&
13436           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13437           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13438                                  FirstStoreAlign, &IsFastSt) &&
13439           IsFastSt &&
13440           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13441                                  FirstLoadAlign, &IsFastLd) &&
13442           IsFastLd) {
13443         LastLegalVectorType = i + 1;
13444       }
13445
13446       // Find a legal type for the integer store.
13447       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13448       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13449       if (TLI.isTypeLegal(StoreTy) &&
13450           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13451           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13452                                  FirstStoreAlign, &IsFastSt) &&
13453           IsFastSt &&
13454           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13455                                  FirstLoadAlign, &IsFastLd) &&
13456           IsFastLd) {
13457         LastLegalIntegerType = i + 1;
13458         DoIntegerTruncate = false;
13459         // Or check whether a truncstore and extload is legal.
13460       } else if (TLI.getTypeAction(Context, StoreTy) ==
13461                  TargetLowering::TypePromoteInteger) {
13462         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13463         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13464             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13465             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13466                                StoreTy) &&
13467             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13468                                StoreTy) &&
13469             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13470             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13471                                    FirstStoreAlign, &IsFastSt) &&
13472             IsFastSt &&
13473             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13474                                    FirstLoadAlign, &IsFastLd) &&
13475             IsFastLd) {
13476           LastLegalIntegerType = i + 1;
13477           DoIntegerTruncate = true;
13478         }
13479       }
13480     }
13481
13482     // Only use vector types if the vector type is larger than the integer type.
13483     // If they are the same, use integers.
13484     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13485     unsigned LastLegalType =
13486         std::max(LastLegalVectorType, LastLegalIntegerType);
13487
13488     // We add +1 here because the LastXXX variables refer to location while
13489     // the NumElem refers to array/index size.
13490     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13491     NumElem = std::min(LastLegalType, NumElem);
13492
13493     if (NumElem < 2) {
13494       // We know that candidate stores are in order and of correct
13495       // shape. While there is no mergeable sequence from the
13496       // beginning one may start later in the sequence. The only
13497       // reason a merge of size N could have failed where another of
13498       // the same size would not have is if the alignment or either
13499       // the load or store has improved. Drop as many candidates as we
13500       // can here.
13501       unsigned NumSkip = 1;
13502       while ((NumSkip < LoadNodes.size()) &&
13503              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13504              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13505         NumSkip++;
13506       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13507       continue;
13508     }
13509
13510     // Find if it is better to use vectors or integers to load and store
13511     // to memory.
13512     EVT JointMemOpVT;
13513     if (UseVectorTy) {
13514       // Find a legal type for the vector store.
13515       unsigned Elts = NumElem * NumMemElts;
13516       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13517     } else {
13518       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13519       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13520     }
13521
13522     SDLoc LoadDL(LoadNodes[0].MemNode);
13523     SDLoc StoreDL(StoreNodes[0].MemNode);
13524
13525     // The merged loads are required to have the same incoming chain, so
13526     // using the first's chain is acceptable.
13527
13528     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13529     AddToWorklist(NewStoreChain.getNode());
13530
13531     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13532                                           MachineMemOperand::MODereferenceable:
13533                                           MachineMemOperand::MONone;
13534
13535     SDValue NewLoad, NewStore;
13536     if (UseVectorTy || !DoIntegerTruncate) {
13537       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13538                             FirstLoad->getBasePtr(),
13539                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13540                             MMOFlags);
13541       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13542                               FirstInChain->getBasePtr(),
13543                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13544     } else { // This must be the truncstore/extload case
13545       EVT ExtendedTy =
13546           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13547       NewLoad =
13548           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13549                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13550                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13551       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13552                                    FirstInChain->getBasePtr(),
13553                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13554                                    FirstInChain->getAlignment(),
13555                                    FirstInChain->getMemOperand()->getFlags());
13556     }
13557
13558     // Transfer chain users from old loads to the new load.
13559     for (unsigned i = 0; i < NumElem; ++i) {
13560       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13561       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13562                                     SDValue(NewLoad.getNode(), 1));
13563     }
13564
13565     // Replace the all stores with the new store. Recursively remove
13566     // corresponding value if its no longer used.
13567     for (unsigned i = 0; i < NumElem; ++i) {
13568       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13569       CombineTo(StoreNodes[i].MemNode, NewStore);
13570       if (Val.getNode()->use_empty())
13571         recursivelyDeleteUnusedNodes(Val.getNode());
13572     }
13573
13574     RV = true;
13575     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13576   }
13577   return RV;
13578 }
13579
13580 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13581   SDLoc SL(ST);
13582   SDValue ReplStore;
13583
13584   // Replace the chain to avoid dependency.
13585   if (ST->isTruncatingStore()) {
13586     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13587                                   ST->getBasePtr(), ST->getMemoryVT(),
13588                                   ST->getMemOperand());
13589   } else {
13590     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13591                              ST->getMemOperand());
13592   }
13593
13594   // Create token to keep both nodes around.
13595   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13596                               MVT::Other, ST->getChain(), ReplStore);
13597
13598   // Make sure the new and old chains are cleaned up.
13599   AddToWorklist(Token.getNode());
13600
13601   // Don't add users to work list.
13602   return CombineTo(ST, Token, false);
13603 }
13604
13605 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13606   SDValue Value = ST->getValue();
13607   if (Value.getOpcode() == ISD::TargetConstantFP)
13608     return SDValue();
13609
13610   SDLoc DL(ST);
13611
13612   SDValue Chain = ST->getChain();
13613   SDValue Ptr = ST->getBasePtr();
13614
13615   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13616
13617   // NOTE: If the original store is volatile, this transform must not increase
13618   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13619   // processor operation but an i64 (which is not legal) requires two.  So the
13620   // transform should not be done in this case.
13621
13622   SDValue Tmp;
13623   switch (CFP->getSimpleValueType(0).SimpleTy) {
13624   default:
13625     llvm_unreachable("Unknown FP type");
13626   case MVT::f16:    // We don't do this for these yet.
13627   case MVT::f80:
13628   case MVT::f128:
13629   case MVT::ppcf128:
13630     return SDValue();
13631   case MVT::f32:
13632     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13633         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13634       ;
13635       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13636                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13637                             MVT::i32);
13638       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13639     }
13640
13641     return SDValue();
13642   case MVT::f64:
13643     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13644          !ST->isVolatile()) ||
13645         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13646       ;
13647       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13648                             getZExtValue(), SDLoc(CFP), MVT::i64);
13649       return DAG.getStore(Chain, DL, Tmp,
13650                           Ptr, ST->getMemOperand());
13651     }
13652
13653     if (!ST->isVolatile() &&
13654         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13655       // Many FP stores are not made apparent until after legalize, e.g. for
13656       // argument passing.  Since this is so common, custom legalize the
13657       // 64-bit integer store into two 32-bit stores.
13658       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13659       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13660       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13661       if (DAG.getDataLayout().isBigEndian())
13662         std::swap(Lo, Hi);
13663
13664       unsigned Alignment = ST->getAlignment();
13665       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13666       AAMDNodes AAInfo = ST->getAAInfo();
13667
13668       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13669                                  ST->getAlignment(), MMOFlags, AAInfo);
13670       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13671                         DAG.getConstant(4, DL, Ptr.getValueType()));
13672       Alignment = MinAlign(Alignment, 4U);
13673       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13674                                  ST->getPointerInfo().getWithOffset(4),
13675                                  Alignment, MMOFlags, AAInfo);
13676       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13677                          St0, St1);
13678     }
13679
13680     return SDValue();
13681   }
13682 }
13683
13684 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13685   StoreSDNode *ST  = cast<StoreSDNode>(N);
13686   SDValue Chain = ST->getChain();
13687   SDValue Value = ST->getValue();
13688   SDValue Ptr   = ST->getBasePtr();
13689
13690   // If this is a store of a bit convert, store the input value if the
13691   // resultant store does not need a higher alignment than the original.
13692   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13693       ST->isUnindexed()) {
13694     EVT SVT = Value.getOperand(0).getValueType();
13695     if (((!LegalOperations && !ST->isVolatile()) ||
13696          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13697         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13698       unsigned OrigAlign = ST->getAlignment();
13699       bool Fast = false;
13700       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13701                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13702           Fast) {
13703         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13704                             ST->getPointerInfo(), OrigAlign,
13705                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13706       }
13707     }
13708   }
13709
13710   // Turn 'store undef, Ptr' -> nothing.
13711   if (Value.isUndef() && ST->isUnindexed())
13712     return Chain;
13713
13714   // Try to infer better alignment information than the store already has.
13715   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13716     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13717       if (Align > ST->getAlignment()) {
13718         SDValue NewStore =
13719             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13720                               ST->getMemoryVT(), Align,
13721                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13722         if (NewStore.getNode() != N)
13723           return CombineTo(ST, NewStore, true);
13724       }
13725     }
13726   }
13727
13728   // Try transforming a pair floating point load / store ops to integer
13729   // load / store ops.
13730   if (SDValue NewST = TransformFPLoadStorePair(N))
13731     return NewST;
13732
13733   if (ST->isUnindexed()) {
13734     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13735     // adjacent stores.
13736     if (findBetterNeighborChains(ST)) {
13737       // replaceStoreChain uses CombineTo, which handled all of the worklist
13738       // manipulation. Return the original node to not do anything else.
13739       return SDValue(ST, 0);
13740     }
13741     Chain = ST->getChain();
13742   }
13743
13744   // FIXME: is there such a thing as a truncating indexed store?
13745   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13746       Value.getValueType().isInteger()) {
13747     // See if we can simplify the input to this truncstore with knowledge that
13748     // only the low bits are being used.  For example:
13749     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13750     SDValue Shorter = DAG.GetDemandedBits(
13751         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13752                                     ST->getMemoryVT().getScalarSizeInBits()));
13753     AddToWorklist(Value.getNode());
13754     if (Shorter.getNode())
13755       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13756                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13757
13758     // Otherwise, see if we can simplify the operation with
13759     // SimplifyDemandedBits, which only works if the value has a single use.
13760     if (SimplifyDemandedBits(
13761             Value,
13762             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13763                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13764       // Re-visit the store if anything changed and the store hasn't been merged
13765       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13766       // node back to the worklist if necessary, but we also need to re-visit
13767       // the Store node itself.
13768       if (N->getOpcode() != ISD::DELETED_NODE)
13769         AddToWorklist(N);
13770       return SDValue(N, 0);
13771     }
13772   }
13773
13774   // If this is a load followed by a store to the same location, then the store
13775   // is dead/noop.
13776   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13777     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13778         ST->isUnindexed() && !ST->isVolatile() &&
13779         // There can't be any side effects between the load and store, such as
13780         // a call or store.
13781         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13782       // The store is dead, remove it.
13783       return Chain;
13784     }
13785   }
13786
13787   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13788     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13789         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13790         ST->getMemoryVT() == ST1->getMemoryVT()) {
13791       // If this is a store followed by a store with the same value to the same
13792       // location, then the store is dead/noop.
13793       if (ST1->getValue() == Value) {
13794         // The store is dead, remove it.
13795         return Chain;
13796       }
13797
13798       // If this is a store who's preceeding store to the same location
13799       // and no one other node is chained to that store we can effectively
13800       // drop the store. Do not remove stores to undef as they may be used as
13801       // data sinks.
13802       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13803           !ST1->getBasePtr().isUndef()) {
13804         // ST1 is fully overwritten and can be elided. Combine with it's chain
13805         // value.
13806         CombineTo(ST1, ST1->getChain());
13807         return SDValue();
13808       }
13809     }
13810   }
13811
13812   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13813   // truncating store.  We can do this even if this is already a truncstore.
13814   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13815       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13816       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13817                             ST->getMemoryVT())) {
13818     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13819                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13820   }
13821
13822   // Always perform this optimization before types are legal. If the target
13823   // prefers, also try this after legalization to catch stores that were created
13824   // by intrinsics or other nodes.
13825   if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
13826     while (true) {
13827       // There can be multiple store sequences on the same chain.
13828       // Keep trying to merge store sequences until we are unable to do so
13829       // or until we merge the last store on the chain.
13830       bool Changed = MergeConsecutiveStores(ST);
13831       if (!Changed) break;
13832       // Return N as merge only uses CombineTo and no worklist clean
13833       // up is necessary.
13834       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13835         return SDValue(N, 0);
13836     }
13837   }
13838
13839   // Try transforming N to an indexed store.
13840   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13841     return SDValue(N, 0);
13842
13843   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13844   //
13845   // Make sure to do this only after attempting to merge stores in order to
13846   //  avoid changing the types of some subset of stores due to visit order,
13847   //  preventing their merging.
13848   if (isa<ConstantFPSDNode>(ST->getValue())) {
13849     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13850       return NewSt;
13851   }
13852
13853   if (SDValue NewSt = splitMergedValStore(ST))
13854     return NewSt;
13855
13856   return ReduceLoadOpStoreWidth(N);
13857 }
13858
13859 /// For the instruction sequence of store below, F and I values
13860 /// are bundled together as an i64 value before being stored into memory.
13861 /// Sometimes it is more efficent to generate separate stores for F and I,
13862 /// which can remove the bitwise instructions or sink them to colder places.
13863 ///
13864 ///   (store (or (zext (bitcast F to i32) to i64),
13865 ///              (shl (zext I to i64), 32)), addr)  -->
13866 ///   (store F, addr) and (store I, addr+4)
13867 ///
13868 /// Similarly, splitting for other merged store can also be beneficial, like:
13869 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13870 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13871 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13872 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13873 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13874 ///
13875 /// We allow each target to determine specifically which kind of splitting is
13876 /// supported.
13877 ///
13878 /// The store patterns are commonly seen from the simple code snippet below
13879 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13880 ///   void goo(const std::pair<int, float> &);
13881 ///   hoo() {
13882 ///     ...
13883 ///     goo(std::make_pair(tmp, ftmp));
13884 ///     ...
13885 ///   }
13886 ///
13887 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13888   if (OptLevel == CodeGenOpt::None)
13889     return SDValue();
13890
13891   SDValue Val = ST->getValue();
13892   SDLoc DL(ST);
13893
13894   // Match OR operand.
13895   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13896     return SDValue();
13897
13898   // Match SHL operand and get Lower and Higher parts of Val.
13899   SDValue Op1 = Val.getOperand(0);
13900   SDValue Op2 = Val.getOperand(1);
13901   SDValue Lo, Hi;
13902   if (Op1.getOpcode() != ISD::SHL) {
13903     std::swap(Op1, Op2);
13904     if (Op1.getOpcode() != ISD::SHL)
13905       return SDValue();
13906   }
13907   Lo = Op2;
13908   Hi = Op1.getOperand(0);
13909   if (!Op1.hasOneUse())
13910     return SDValue();
13911
13912   // Match shift amount to HalfValBitSize.
13913   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13914   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13915   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13916     return SDValue();
13917
13918   // Lo and Hi are zero-extended from int with size less equal than 32
13919   // to i64.
13920   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13921       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13922       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13923       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13924       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13925       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13926     return SDValue();
13927
13928   // Use the EVT of low and high parts before bitcast as the input
13929   // of target query.
13930   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13931                   ? Lo.getOperand(0).getValueType()
13932                   : Lo.getValueType();
13933   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13934                    ? Hi.getOperand(0).getValueType()
13935                    : Hi.getValueType();
13936   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13937     return SDValue();
13938
13939   // Start to split store.
13940   unsigned Alignment = ST->getAlignment();
13941   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13942   AAMDNodes AAInfo = ST->getAAInfo();
13943
13944   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13945   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13946   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13947   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13948
13949   SDValue Chain = ST->getChain();
13950   SDValue Ptr = ST->getBasePtr();
13951   // Lower value store.
13952   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13953                              ST->getAlignment(), MMOFlags, AAInfo);
13954   Ptr =
13955       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13956                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13957   // Higher value store.
13958   SDValue St1 =
13959       DAG.getStore(St0, DL, Hi, Ptr,
13960                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13961                    Alignment / 2, MMOFlags, AAInfo);
13962   return St1;
13963 }
13964
13965 /// Convert a disguised subvector insertion into a shuffle:
13966 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
13967 /// bitcast(shuffle (bitcast V), (extended X), Mask)
13968 /// Note: We do not use an insert_subvector node because that requires a legal
13969 /// subvector type.
13970 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
13971   SDValue InsertVal = N->getOperand(1);
13972   if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
13973       !InsertVal.getOperand(0).getValueType().isVector())
13974     return SDValue();
13975
13976   SDValue SubVec = InsertVal.getOperand(0);
13977   SDValue DestVec = N->getOperand(0);
13978   EVT SubVecVT = SubVec.getValueType();
13979   EVT VT = DestVec.getValueType();
13980   unsigned NumSrcElts = SubVecVT.getVectorNumElements();
13981   unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
13982   unsigned NumMaskVals = ExtendRatio * NumSrcElts;
13983
13984   // Step 1: Create a shuffle mask that implements this insert operation. The
13985   // vector that we are inserting into will be operand 0 of the shuffle, so
13986   // those elements are just 'i'. The inserted subvector is in the first
13987   // positions of operand 1 of the shuffle. Example:
13988   // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
13989   SmallVector<int, 16> Mask(NumMaskVals);
13990   for (unsigned i = 0; i != NumMaskVals; ++i) {
13991     if (i / NumSrcElts == InsIndex)
13992       Mask[i] = (i % NumSrcElts) + NumMaskVals;
13993     else
13994       Mask[i] = i;
13995   }
13996
13997   // Bail out if the target can not handle the shuffle we want to create.
13998   EVT SubVecEltVT = SubVecVT.getVectorElementType();
13999   EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14000   if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14001     return SDValue();
14002
14003   // Step 2: Create a wide vector from the inserted source vector by appending
14004   // undefined elements. This is the same size as our destination vector.
14005   SDLoc DL(N);
14006   SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14007   ConcatOps[0] = SubVec;
14008   SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14009
14010   // Step 3: Shuffle in the padded subvector.
14011   SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14012   SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14013   AddToWorklist(PaddedSubV.getNode());
14014   AddToWorklist(DestVecBC.getNode());
14015   AddToWorklist(Shuf.getNode());
14016   return DAG.getBitcast(VT, Shuf);
14017 }
14018
14019 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14020   SDValue InVec = N->getOperand(0);
14021   SDValue InVal = N->getOperand(1);
14022   SDValue EltNo = N->getOperand(2);
14023   SDLoc DL(N);
14024
14025   // If the inserted element is an UNDEF, just use the input vector.
14026   if (InVal.isUndef())
14027     return InVec;
14028
14029   EVT VT = InVec.getValueType();
14030
14031   // Remove redundant insertions:
14032   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14033   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14034       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14035     return InVec;
14036
14037   // We must know which element is being inserted for folds below here.
14038   auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14039   if (!IndexC)
14040     return SDValue();
14041   unsigned Elt = IndexC->getZExtValue();
14042
14043   if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14044     return Shuf;
14045
14046   // Canonicalize insert_vector_elt dag nodes.
14047   // Example:
14048   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14049   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14050   //
14051   // Do this only if the child insert_vector node has one use; also
14052   // do this only if indices are both constants and Idx1 < Idx0.
14053   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14054       && isa<ConstantSDNode>(InVec.getOperand(2))) {
14055     unsigned OtherElt = InVec.getConstantOperandVal(2);
14056     if (Elt < OtherElt) {
14057       // Swap nodes.
14058       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14059                                   InVec.getOperand(0), InVal, EltNo);
14060       AddToWorklist(NewOp.getNode());
14061       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14062                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14063     }
14064   }
14065
14066   // If we can't generate a legal BUILD_VECTOR, exit
14067   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14068     return SDValue();
14069
14070   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14071   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
14072   // vector elements.
14073   SmallVector<SDValue, 8> Ops;
14074   // Do not combine these two vectors if the output vector will not replace
14075   // the input vector.
14076   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14077     Ops.append(InVec.getNode()->op_begin(),
14078                InVec.getNode()->op_end());
14079   } else if (InVec.isUndef()) {
14080     unsigned NElts = VT.getVectorNumElements();
14081     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14082   } else {
14083     return SDValue();
14084   }
14085
14086   // Insert the element
14087   if (Elt < Ops.size()) {
14088     // All the operands of BUILD_VECTOR must have the same type;
14089     // we enforce that here.
14090     EVT OpVT = Ops[0].getValueType();
14091     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14092   }
14093
14094   // Return the new vector
14095   return DAG.getBuildVector(VT, DL, Ops);
14096 }
14097
14098 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14099     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14100   assert(!OriginalLoad->isVolatile());
14101
14102   EVT ResultVT = EVE->getValueType(0);
14103   EVT VecEltVT = InVecVT.getVectorElementType();
14104   unsigned Align = OriginalLoad->getAlignment();
14105   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14106       VecEltVT.getTypeForEVT(*DAG.getContext()));
14107
14108   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14109     return SDValue();
14110
14111   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14112     ISD::NON_EXTLOAD : ISD::EXTLOAD;
14113   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14114     return SDValue();
14115
14116   Align = NewAlign;
14117
14118   SDValue NewPtr = OriginalLoad->getBasePtr();
14119   SDValue Offset;
14120   EVT PtrType = NewPtr.getValueType();
14121   MachinePointerInfo MPI;
14122   SDLoc DL(EVE);
14123   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14124     int Elt = ConstEltNo->getZExtValue();
14125     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14126     Offset = DAG.getConstant(PtrOff, DL, PtrType);
14127     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14128   } else {
14129     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14130     Offset = DAG.getNode(
14131         ISD::MUL, DL, PtrType, Offset,
14132         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14133     MPI = OriginalLoad->getPointerInfo();
14134   }
14135   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14136
14137   // The replacement we need to do here is a little tricky: we need to
14138   // replace an extractelement of a load with a load.
14139   // Use ReplaceAllUsesOfValuesWith to do the replacement.
14140   // Note that this replacement assumes that the extractvalue is the only
14141   // use of the load; that's okay because we don't want to perform this
14142   // transformation in other cases anyway.
14143   SDValue Load;
14144   SDValue Chain;
14145   if (ResultVT.bitsGT(VecEltVT)) {
14146     // If the result type of vextract is wider than the load, then issue an
14147     // extending load instead.
14148     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14149                                                   VecEltVT)
14150                                    ? ISD::ZEXTLOAD
14151                                    : ISD::EXTLOAD;
14152     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14153                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14154                           Align, OriginalLoad->getMemOperand()->getFlags(),
14155                           OriginalLoad->getAAInfo());
14156     Chain = Load.getValue(1);
14157   } else {
14158     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14159                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14160                        OriginalLoad->getAAInfo());
14161     Chain = Load.getValue(1);
14162     if (ResultVT.bitsLT(VecEltVT))
14163       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14164     else
14165       Load = DAG.getBitcast(ResultVT, Load);
14166   }
14167   WorklistRemover DeadNodes(*this);
14168   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14169   SDValue To[] = { Load, Chain };
14170   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14171   // Since we're explicitly calling ReplaceAllUses, add the new node to the
14172   // worklist explicitly as well.
14173   AddToWorklist(Load.getNode());
14174   AddUsersToWorklist(Load.getNode()); // Add users too
14175   // Make sure to revisit this node to clean it up; it will usually be dead.
14176   AddToWorklist(EVE);
14177   ++OpsNarrowed;
14178   return SDValue(EVE, 0);
14179 }
14180
14181 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14182   // (vextract (scalar_to_vector val, 0) -> val
14183   SDValue InVec = N->getOperand(0);
14184   EVT VT = InVec.getValueType();
14185   EVT NVT = N->getValueType(0);
14186
14187   if (InVec.isUndef())
14188     return DAG.getUNDEF(NVT);
14189
14190   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14191     // Check if the result type doesn't match the inserted element type. A
14192     // SCALAR_TO_VECTOR may truncate the inserted element and the
14193     // EXTRACT_VECTOR_ELT may widen the extracted vector.
14194     SDValue InOp = InVec.getOperand(0);
14195     if (InOp.getValueType() != NVT) {
14196       assert(InOp.getValueType().isInteger() && NVT.isInteger());
14197       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14198     }
14199     return InOp;
14200   }
14201
14202   SDValue EltNo = N->getOperand(1);
14203   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14204
14205   // extract_vector_elt (build_vector x, y), 1 -> y
14206   if (ConstEltNo &&
14207       InVec.getOpcode() == ISD::BUILD_VECTOR &&
14208       TLI.isTypeLegal(VT) &&
14209       (InVec.hasOneUse() ||
14210        TLI.aggressivelyPreferBuildVectorSources(VT))) {
14211     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14212     EVT InEltVT = Elt.getValueType();
14213
14214     // Sometimes build_vector's scalar input types do not match result type.
14215     if (NVT == InEltVT)
14216       return Elt;
14217
14218     // TODO: It may be useful to truncate if free if the build_vector implicitly
14219     // converts.
14220   }
14221
14222   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14223   bool isLE = DAG.getDataLayout().isLittleEndian();
14224   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14225   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14226       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14227     SDValue BCSrc = InVec.getOperand(0);
14228     if (BCSrc.getValueType().isScalarInteger())
14229       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14230   }
14231
14232   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14233   //
14234   // This only really matters if the index is non-constant since other combines
14235   // on the constant elements already work.
14236   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14237       EltNo == InVec.getOperand(2)) {
14238     SDValue Elt = InVec.getOperand(1);
14239     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14240   }
14241
14242   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14243   // We only perform this optimization before the op legalization phase because
14244   // we may introduce new vector instructions which are not backed by TD
14245   // patterns. For example on AVX, extracting elements from a wide vector
14246   // without using extract_subvector. However, if we can find an underlying
14247   // scalar value, then we can always use that.
14248   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14249     int NumElem = VT.getVectorNumElements();
14250     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14251     // Find the new index to extract from.
14252     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14253
14254     // Extracting an undef index is undef.
14255     if (OrigElt == -1)
14256       return DAG.getUNDEF(NVT);
14257
14258     // Select the right vector half to extract from.
14259     SDValue SVInVec;
14260     if (OrigElt < NumElem) {
14261       SVInVec = InVec->getOperand(0);
14262     } else {
14263       SVInVec = InVec->getOperand(1);
14264       OrigElt -= NumElem;
14265     }
14266
14267     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14268       SDValue InOp = SVInVec.getOperand(OrigElt);
14269       if (InOp.getValueType() != NVT) {
14270         assert(InOp.getValueType().isInteger() && NVT.isInteger());
14271         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
14272       }
14273
14274       return InOp;
14275     }
14276
14277     // FIXME: We should handle recursing on other vector shuffles and
14278     // scalar_to_vector here as well.
14279
14280     if (!LegalOperations ||
14281         // FIXME: Should really be just isOperationLegalOrCustom.
14282         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14283         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14284       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14285       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14286                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14287     }
14288   }
14289
14290   bool BCNumEltsChanged = false;
14291   EVT ExtVT = VT.getVectorElementType();
14292   EVT LVT = ExtVT;
14293
14294   // If the result of load has to be truncated, then it's not necessarily
14295   // profitable.
14296   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14297     return SDValue();
14298
14299   if (InVec.getOpcode() == ISD::BITCAST) {
14300     // Don't duplicate a load with other uses.
14301     if (!InVec.hasOneUse())
14302       return SDValue();
14303
14304     EVT BCVT = InVec.getOperand(0).getValueType();
14305     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14306       return SDValue();
14307     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14308       BCNumEltsChanged = true;
14309     InVec = InVec.getOperand(0);
14310     ExtVT = BCVT.getVectorElementType();
14311   }
14312
14313   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14314   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14315       ISD::isNormalLoad(InVec.getNode()) &&
14316       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14317     SDValue Index = N->getOperand(1);
14318     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14319       if (!OrigLoad->isVolatile()) {
14320         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14321                                                              OrigLoad);
14322       }
14323     }
14324   }
14325
14326   // Perform only after legalization to ensure build_vector / vector_shuffle
14327   // optimizations have already been done.
14328   if (!LegalOperations) return SDValue();
14329
14330   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14331   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14332   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14333
14334   if (ConstEltNo) {
14335     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14336
14337     LoadSDNode *LN0 = nullptr;
14338     const ShuffleVectorSDNode *SVN = nullptr;
14339     if (ISD::isNormalLoad(InVec.getNode())) {
14340       LN0 = cast<LoadSDNode>(InVec);
14341     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14342                InVec.getOperand(0).getValueType() == ExtVT &&
14343                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14344       // Don't duplicate a load with other uses.
14345       if (!InVec.hasOneUse())
14346         return SDValue();
14347
14348       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14349     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14350       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14351       // =>
14352       // (load $addr+1*size)
14353
14354       // Don't duplicate a load with other uses.
14355       if (!InVec.hasOneUse())
14356         return SDValue();
14357
14358       // If the bit convert changed the number of elements, it is unsafe
14359       // to examine the mask.
14360       if (BCNumEltsChanged)
14361         return SDValue();
14362
14363       // Select the input vector, guarding against out of range extract vector.
14364       unsigned NumElems = VT.getVectorNumElements();
14365       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14366       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14367
14368       if (InVec.getOpcode() == ISD::BITCAST) {
14369         // Don't duplicate a load with other uses.
14370         if (!InVec.hasOneUse())
14371           return SDValue();
14372
14373         InVec = InVec.getOperand(0);
14374       }
14375       if (ISD::isNormalLoad(InVec.getNode())) {
14376         LN0 = cast<LoadSDNode>(InVec);
14377         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14378         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14379       }
14380     }
14381
14382     // Make sure we found a non-volatile load and the extractelement is
14383     // the only use.
14384     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14385       return SDValue();
14386
14387     // If Idx was -1 above, Elt is going to be -1, so just return undef.
14388     if (Elt == -1)
14389       return DAG.getUNDEF(LVT);
14390
14391     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14392   }
14393
14394   return SDValue();
14395 }
14396
14397 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14398 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14399   // We perform this optimization post type-legalization because
14400   // the type-legalizer often scalarizes integer-promoted vectors.
14401   // Performing this optimization before may create bit-casts which
14402   // will be type-legalized to complex code sequences.
14403   // We perform this optimization only before the operation legalizer because we
14404   // may introduce illegal operations.
14405   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14406     return SDValue();
14407
14408   unsigned NumInScalars = N->getNumOperands();
14409   SDLoc DL(N);
14410   EVT VT = N->getValueType(0);
14411
14412   // Check to see if this is a BUILD_VECTOR of a bunch of values
14413   // which come from any_extend or zero_extend nodes. If so, we can create
14414   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14415   // optimizations. We do not handle sign-extend because we can't fill the sign
14416   // using shuffles.
14417   EVT SourceType = MVT::Other;
14418   bool AllAnyExt = true;
14419
14420   for (unsigned i = 0; i != NumInScalars; ++i) {
14421     SDValue In = N->getOperand(i);
14422     // Ignore undef inputs.
14423     if (In.isUndef()) continue;
14424
14425     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14426     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14427
14428     // Abort if the element is not an extension.
14429     if (!ZeroExt && !AnyExt) {
14430       SourceType = MVT::Other;
14431       break;
14432     }
14433
14434     // The input is a ZeroExt or AnyExt. Check the original type.
14435     EVT InTy = In.getOperand(0).getValueType();
14436
14437     // Check that all of the widened source types are the same.
14438     if (SourceType == MVT::Other)
14439       // First time.
14440       SourceType = InTy;
14441     else if (InTy != SourceType) {
14442       // Multiple income types. Abort.
14443       SourceType = MVT::Other;
14444       break;
14445     }
14446
14447     // Check if all of the extends are ANY_EXTENDs.
14448     AllAnyExt &= AnyExt;
14449   }
14450
14451   // In order to have valid types, all of the inputs must be extended from the
14452   // same source type and all of the inputs must be any or zero extend.
14453   // Scalar sizes must be a power of two.
14454   EVT OutScalarTy = VT.getScalarType();
14455   bool ValidTypes = SourceType != MVT::Other &&
14456                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14457                  isPowerOf2_32(SourceType.getSizeInBits());
14458
14459   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14460   // turn into a single shuffle instruction.
14461   if (!ValidTypes)
14462     return SDValue();
14463
14464   bool isLE = DAG.getDataLayout().isLittleEndian();
14465   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14466   assert(ElemRatio > 1 && "Invalid element size ratio");
14467   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14468                                DAG.getConstant(0, DL, SourceType);
14469
14470   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14471   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14472
14473   // Populate the new build_vector
14474   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14475     SDValue Cast = N->getOperand(i);
14476     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14477             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14478             Cast.isUndef()) && "Invalid cast opcode");
14479     SDValue In;
14480     if (Cast.isUndef())
14481       In = DAG.getUNDEF(SourceType);
14482     else
14483       In = Cast->getOperand(0);
14484     unsigned Index = isLE ? (i * ElemRatio) :
14485                             (i * ElemRatio + (ElemRatio - 1));
14486
14487     assert(Index < Ops.size() && "Invalid index");
14488     Ops[Index] = In;
14489   }
14490
14491   // The type of the new BUILD_VECTOR node.
14492   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14493   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14494          "Invalid vector size");
14495   // Check if the new vector type is legal.
14496   if (!isTypeLegal(VecVT)) return SDValue();
14497
14498   // Make the new BUILD_VECTOR.
14499   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14500
14501   // The new BUILD_VECTOR node has the potential to be further optimized.
14502   AddToWorklist(BV.getNode());
14503   // Bitcast to the desired type.
14504   return DAG.getBitcast(VT, BV);
14505 }
14506
14507 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14508   EVT VT = N->getValueType(0);
14509
14510   unsigned NumInScalars = N->getNumOperands();
14511   SDLoc DL(N);
14512
14513   EVT SrcVT = MVT::Other;
14514   unsigned Opcode = ISD::DELETED_NODE;
14515   unsigned NumDefs = 0;
14516
14517   for (unsigned i = 0; i != NumInScalars; ++i) {
14518     SDValue In = N->getOperand(i);
14519     unsigned Opc = In.getOpcode();
14520
14521     if (Opc == ISD::UNDEF)
14522       continue;
14523
14524     // If all scalar values are floats and converted from integers.
14525     if (Opcode == ISD::DELETED_NODE &&
14526         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14527       Opcode = Opc;
14528     }
14529
14530     if (Opc != Opcode)
14531       return SDValue();
14532
14533     EVT InVT = In.getOperand(0).getValueType();
14534
14535     // If all scalar values are typed differently, bail out. It's chosen to
14536     // simplify BUILD_VECTOR of integer types.
14537     if (SrcVT == MVT::Other)
14538       SrcVT = InVT;
14539     if (SrcVT != InVT)
14540       return SDValue();
14541     NumDefs++;
14542   }
14543
14544   // If the vector has just one element defined, it's not worth to fold it into
14545   // a vectorized one.
14546   if (NumDefs < 2)
14547     return SDValue();
14548
14549   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14550          && "Should only handle conversion from integer to float.");
14551   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14552
14553   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14554
14555   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14556     return SDValue();
14557
14558   // Just because the floating-point vector type is legal does not necessarily
14559   // mean that the corresponding integer vector type is.
14560   if (!isTypeLegal(NVT))
14561     return SDValue();
14562
14563   SmallVector<SDValue, 8> Opnds;
14564   for (unsigned i = 0; i != NumInScalars; ++i) {
14565     SDValue In = N->getOperand(i);
14566
14567     if (In.isUndef())
14568       Opnds.push_back(DAG.getUNDEF(SrcVT));
14569     else
14570       Opnds.push_back(In.getOperand(0));
14571   }
14572   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14573   AddToWorklist(BV.getNode());
14574
14575   return DAG.getNode(Opcode, DL, VT, BV);
14576 }
14577
14578 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14579                                            ArrayRef<int> VectorMask,
14580                                            SDValue VecIn1, SDValue VecIn2,
14581                                            unsigned LeftIdx) {
14582   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14583   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14584
14585   EVT VT = N->getValueType(0);
14586   EVT InVT1 = VecIn1.getValueType();
14587   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14588
14589   unsigned Vec2Offset = 0;
14590   unsigned NumElems = VT.getVectorNumElements();
14591   unsigned ShuffleNumElems = NumElems;
14592
14593   // In case both the input vectors are extracted from same base
14594   // vector we do not need extra addend (Vec2Offset) while
14595   // computing shuffle mask.
14596   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14597       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14598       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14599     Vec2Offset = InVT1.getVectorNumElements();
14600
14601   // We can't generate a shuffle node with mismatched input and output types.
14602   // Try to make the types match the type of the output.
14603   if (InVT1 != VT || InVT2 != VT) {
14604     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14605       // If the output vector length is a multiple of both input lengths,
14606       // we can concatenate them and pad the rest with undefs.
14607       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14608       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14609       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14610       ConcatOps[0] = VecIn1;
14611       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14612       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14613       VecIn2 = SDValue();
14614     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14615       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14616         return SDValue();
14617
14618       if (!VecIn2.getNode()) {
14619         // If we only have one input vector, and it's twice the size of the
14620         // output, split it in two.
14621         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14622                              DAG.getConstant(NumElems, DL, IdxTy));
14623         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14624         // Since we now have shorter input vectors, adjust the offset of the
14625         // second vector's start.
14626         Vec2Offset = NumElems;
14627       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14628         // VecIn1 is wider than the output, and we have another, possibly
14629         // smaller input. Pad the smaller input with undefs, shuffle at the
14630         // input vector width, and extract the output.
14631         // The shuffle type is different than VT, so check legality again.
14632         if (LegalOperations &&
14633             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14634           return SDValue();
14635
14636         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14637         // lower it back into a BUILD_VECTOR. So if the inserted type is
14638         // illegal, don't even try.
14639         if (InVT1 != InVT2) {
14640           if (!TLI.isTypeLegal(InVT2))
14641             return SDValue();
14642           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14643                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14644         }
14645         ShuffleNumElems = NumElems * 2;
14646       } else {
14647         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14648         // than VecIn1. We can't handle this for now - this case will disappear
14649         // when we start sorting the vectors by type.
14650         return SDValue();
14651       }
14652     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14653                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14654       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14655       ConcatOps[0] = VecIn2;
14656       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14657     } else {
14658       // TODO: Support cases where the length mismatch isn't exactly by a
14659       // factor of 2.
14660       // TODO: Move this check upwards, so that if we have bad type
14661       // mismatches, we don't create any DAG nodes.
14662       return SDValue();
14663     }
14664   }
14665
14666   // Initialize mask to undef.
14667   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14668
14669   // Only need to run up to the number of elements actually used, not the
14670   // total number of elements in the shuffle - if we are shuffling a wider
14671   // vector, the high lanes should be set to undef.
14672   for (unsigned i = 0; i != NumElems; ++i) {
14673     if (VectorMask[i] <= 0)
14674       continue;
14675
14676     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14677     if (VectorMask[i] == (int)LeftIdx) {
14678       Mask[i] = ExtIndex;
14679     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14680       Mask[i] = Vec2Offset + ExtIndex;
14681     }
14682   }
14683
14684   // The type the input vectors may have changed above.
14685   InVT1 = VecIn1.getValueType();
14686
14687   // If we already have a VecIn2, it should have the same type as VecIn1.
14688   // If we don't, get an undef/zero vector of the appropriate type.
14689   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14690   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14691
14692   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14693   if (ShuffleNumElems > NumElems)
14694     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14695
14696   return Shuffle;
14697 }
14698
14699 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14700 // operations. If the types of the vectors we're extracting from allow it,
14701 // turn this into a vector_shuffle node.
14702 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14703   SDLoc DL(N);
14704   EVT VT = N->getValueType(0);
14705
14706   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14707   if (!isTypeLegal(VT))
14708     return SDValue();
14709
14710   // May only combine to shuffle after legalize if shuffle is legal.
14711   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14712     return SDValue();
14713
14714   bool UsesZeroVector = false;
14715   unsigned NumElems = N->getNumOperands();
14716
14717   // Record, for each element of the newly built vector, which input vector
14718   // that element comes from. -1 stands for undef, 0 for the zero vector,
14719   // and positive values for the input vectors.
14720   // VectorMask maps each element to its vector number, and VecIn maps vector
14721   // numbers to their initial SDValues.
14722
14723   SmallVector<int, 8> VectorMask(NumElems, -1);
14724   SmallVector<SDValue, 8> VecIn;
14725   VecIn.push_back(SDValue());
14726
14727   for (unsigned i = 0; i != NumElems; ++i) {
14728     SDValue Op = N->getOperand(i);
14729
14730     if (Op.isUndef())
14731       continue;
14732
14733     // See if we can use a blend with a zero vector.
14734     // TODO: Should we generalize this to a blend with an arbitrary constant
14735     // vector?
14736     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14737       UsesZeroVector = true;
14738       VectorMask[i] = 0;
14739       continue;
14740     }
14741
14742     // Not an undef or zero. If the input is something other than an
14743     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14744     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14745         !isa<ConstantSDNode>(Op.getOperand(1)))
14746       return SDValue();
14747     SDValue ExtractedFromVec = Op.getOperand(0);
14748
14749     // All inputs must have the same element type as the output.
14750     if (VT.getVectorElementType() !=
14751         ExtractedFromVec.getValueType().getVectorElementType())
14752       return SDValue();
14753
14754     // Have we seen this input vector before?
14755     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14756     // a map back from SDValues to numbers isn't worth it.
14757     unsigned Idx = std::distance(
14758         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14759     if (Idx == VecIn.size())
14760       VecIn.push_back(ExtractedFromVec);
14761
14762     VectorMask[i] = Idx;
14763   }
14764
14765   // If we didn't find at least one input vector, bail out.
14766   if (VecIn.size() < 2)
14767     return SDValue();
14768
14769   // If all the Operands of BUILD_VECTOR extract from same
14770   // vector, then split the vector efficiently based on the maximum
14771   // vector access index and adjust the VectorMask and
14772   // VecIn accordingly.
14773   if (VecIn.size() == 2) {
14774     unsigned MaxIndex = 0;
14775     unsigned NearestPow2 = 0;
14776     SDValue Vec = VecIn.back();
14777     EVT InVT = Vec.getValueType();
14778     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14779     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14780
14781     for (unsigned i = 0; i < NumElems; i++) {
14782       if (VectorMask[i] <= 0)
14783         continue;
14784       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14785       IndexVec[i] = Index;
14786       MaxIndex = std::max(MaxIndex, Index);
14787     }
14788
14789     NearestPow2 = PowerOf2Ceil(MaxIndex);
14790     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
14791         NumElems * 2 < NearestPow2) {
14792       unsigned SplitSize = NearestPow2 / 2;
14793       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14794                                      InVT.getVectorElementType(), SplitSize);
14795       if (TLI.isTypeLegal(SplitVT)) {
14796         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14797                                      DAG.getConstant(SplitSize, DL, IdxTy));
14798         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14799                                      DAG.getConstant(0, DL, IdxTy));
14800         VecIn.pop_back();
14801         VecIn.push_back(VecIn1);
14802         VecIn.push_back(VecIn2);
14803
14804         for (unsigned i = 0; i < NumElems; i++) {
14805           if (VectorMask[i] <= 0)
14806             continue;
14807           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
14808         }
14809       }
14810     }
14811   }
14812
14813   // TODO: We want to sort the vectors by descending length, so that adjacent
14814   // pairs have similar length, and the longer vector is always first in the
14815   // pair.
14816
14817   // TODO: Should this fire if some of the input vectors has illegal type (like
14818   // it does now), or should we let legalization run its course first?
14819
14820   // Shuffle phase:
14821   // Take pairs of vectors, and shuffle them so that the result has elements
14822   // from these vectors in the correct places.
14823   // For example, given:
14824   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14825   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14826   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14827   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14828   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14829   // We will generate:
14830   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14831   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14832   SmallVector<SDValue, 4> Shuffles;
14833   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14834     unsigned LeftIdx = 2 * In + 1;
14835     SDValue VecLeft = VecIn[LeftIdx];
14836     SDValue VecRight =
14837         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14838
14839     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14840                                                 VecRight, LeftIdx))
14841       Shuffles.push_back(Shuffle);
14842     else
14843       return SDValue();
14844   }
14845
14846   // If we need the zero vector as an "ingredient" in the blend tree, add it
14847   // to the list of shuffles.
14848   if (UsesZeroVector)
14849     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14850                                       : DAG.getConstantFP(0.0, DL, VT));
14851
14852   // If we only have one shuffle, we're done.
14853   if (Shuffles.size() == 1)
14854     return Shuffles[0];
14855
14856   // Update the vector mask to point to the post-shuffle vectors.
14857   for (int &Vec : VectorMask)
14858     if (Vec == 0)
14859       Vec = Shuffles.size() - 1;
14860     else
14861       Vec = (Vec - 1) / 2;
14862
14863   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14864   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14865   // generate:
14866   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14867   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14868   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14869   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14870   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14871   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14872   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14873
14874   // Make sure the initial size of the shuffle list is even.
14875   if (Shuffles.size() % 2)
14876     Shuffles.push_back(DAG.getUNDEF(VT));
14877
14878   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14879     if (CurSize % 2) {
14880       Shuffles[CurSize] = DAG.getUNDEF(VT);
14881       CurSize++;
14882     }
14883     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14884       int Left = 2 * In;
14885       int Right = 2 * In + 1;
14886       SmallVector<int, 8> Mask(NumElems, -1);
14887       for (unsigned i = 0; i != NumElems; ++i) {
14888         if (VectorMask[i] == Left) {
14889           Mask[i] = i;
14890           VectorMask[i] = In;
14891         } else if (VectorMask[i] == Right) {
14892           Mask[i] = i + NumElems;
14893           VectorMask[i] = In;
14894         }
14895       }
14896
14897       Shuffles[In] =
14898           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14899     }
14900   }
14901   return Shuffles[0];
14902 }
14903
14904 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14905   EVT VT = N->getValueType(0);
14906
14907   // A vector built entirely of undefs is undef.
14908   if (ISD::allOperandsUndef(N))
14909     return DAG.getUNDEF(VT);
14910
14911   // Check if we can express BUILD VECTOR via subvector extract.
14912   if (!LegalTypes && (N->getNumOperands() > 1)) {
14913     SDValue Op0 = N->getOperand(0);
14914     auto checkElem = [&](SDValue Op) -> uint64_t {
14915       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14916           (Op0.getOperand(0) == Op.getOperand(0)))
14917         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14918           return CNode->getZExtValue();
14919       return -1;
14920     };
14921
14922     int Offset = checkElem(Op0);
14923     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14924       if (Offset + i != checkElem(N->getOperand(i))) {
14925         Offset = -1;
14926         break;
14927       }
14928     }
14929
14930     if ((Offset == 0) &&
14931         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14932       return Op0.getOperand(0);
14933     if ((Offset != -1) &&
14934         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14935          0)) // IDX must be multiple of output size.
14936       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14937                          Op0.getOperand(0), Op0.getOperand(1));
14938   }
14939
14940   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14941     return V;
14942
14943   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14944     return V;
14945
14946   if (SDValue V = reduceBuildVecToShuffle(N))
14947     return V;
14948
14949   return SDValue();
14950 }
14951
14952 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14954   EVT OpVT = N->getOperand(0).getValueType();
14955
14956   // If the operands are legal vectors, leave them alone.
14957   if (TLI.isTypeLegal(OpVT))
14958     return SDValue();
14959
14960   SDLoc DL(N);
14961   EVT VT = N->getValueType(0);
14962   SmallVector<SDValue, 8> Ops;
14963
14964   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14965   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14966
14967   // Keep track of what we encounter.
14968   bool AnyInteger = false;
14969   bool AnyFP = false;
14970   for (const SDValue &Op : N->ops()) {
14971     if (ISD::BITCAST == Op.getOpcode() &&
14972         !Op.getOperand(0).getValueType().isVector())
14973       Ops.push_back(Op.getOperand(0));
14974     else if (ISD::UNDEF == Op.getOpcode())
14975       Ops.push_back(ScalarUndef);
14976     else
14977       return SDValue();
14978
14979     // Note whether we encounter an integer or floating point scalar.
14980     // If it's neither, bail out, it could be something weird like x86mmx.
14981     EVT LastOpVT = Ops.back().getValueType();
14982     if (LastOpVT.isFloatingPoint())
14983       AnyFP = true;
14984     else if (LastOpVT.isInteger())
14985       AnyInteger = true;
14986     else
14987       return SDValue();
14988   }
14989
14990   // If any of the operands is a floating point scalar bitcast to a vector,
14991   // use floating point types throughout, and bitcast everything.
14992   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14993   if (AnyFP) {
14994     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14995     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14996     if (AnyInteger) {
14997       for (SDValue &Op : Ops) {
14998         if (Op.getValueType() == SVT)
14999           continue;
15000         if (Op.isUndef())
15001           Op = ScalarUndef;
15002         else
15003           Op = DAG.getBitcast(SVT, Op);
15004       }
15005     }
15006   }
15007
15008   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15009                                VT.getSizeInBits() / SVT.getSizeInBits());
15010   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15011 }
15012
15013 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15014 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15015 // most two distinct vectors the same size as the result, attempt to turn this
15016 // into a legal shuffle.
15017 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15018   EVT VT = N->getValueType(0);
15019   EVT OpVT = N->getOperand(0).getValueType();
15020   int NumElts = VT.getVectorNumElements();
15021   int NumOpElts = OpVT.getVectorNumElements();
15022
15023   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15024   SmallVector<int, 8> Mask;
15025
15026   for (SDValue Op : N->ops()) {
15027     // Peek through any bitcast.
15028     Op = peekThroughBitcast(Op);
15029
15030     // UNDEF nodes convert to UNDEF shuffle mask values.
15031     if (Op.isUndef()) {
15032       Mask.append((unsigned)NumOpElts, -1);
15033       continue;
15034     }
15035
15036     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15037       return SDValue();
15038
15039     // What vector are we extracting the subvector from and at what index?
15040     SDValue ExtVec = Op.getOperand(0);
15041
15042     // We want the EVT of the original extraction to correctly scale the
15043     // extraction index.
15044     EVT ExtVT = ExtVec.getValueType();
15045
15046     // Peek through any bitcast.
15047     ExtVec = peekThroughBitcast(ExtVec);
15048
15049     // UNDEF nodes convert to UNDEF shuffle mask values.
15050     if (ExtVec.isUndef()) {
15051       Mask.append((unsigned)NumOpElts, -1);
15052       continue;
15053     }
15054
15055     if (!isa<ConstantSDNode>(Op.getOperand(1)))
15056       return SDValue();
15057     int ExtIdx = Op.getConstantOperandVal(1);
15058
15059     // Ensure that we are extracting a subvector from a vector the same
15060     // size as the result.
15061     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15062       return SDValue();
15063
15064     // Scale the subvector index to account for any bitcast.
15065     int NumExtElts = ExtVT.getVectorNumElements();
15066     if (0 == (NumExtElts % NumElts))
15067       ExtIdx /= (NumExtElts / NumElts);
15068     else if (0 == (NumElts % NumExtElts))
15069       ExtIdx *= (NumElts / NumExtElts);
15070     else
15071       return SDValue();
15072
15073     // At most we can reference 2 inputs in the final shuffle.
15074     if (SV0.isUndef() || SV0 == ExtVec) {
15075       SV0 = ExtVec;
15076       for (int i = 0; i != NumOpElts; ++i)
15077         Mask.push_back(i + ExtIdx);
15078     } else if (SV1.isUndef() || SV1 == ExtVec) {
15079       SV1 = ExtVec;
15080       for (int i = 0; i != NumOpElts; ++i)
15081         Mask.push_back(i + ExtIdx + NumElts);
15082     } else {
15083       return SDValue();
15084     }
15085   }
15086
15087   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15088     return SDValue();
15089
15090   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15091                               DAG.getBitcast(VT, SV1), Mask);
15092 }
15093
15094 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15095   // If we only have one input vector, we don't need to do any concatenation.
15096   if (N->getNumOperands() == 1)
15097     return N->getOperand(0);
15098
15099   // Check if all of the operands are undefs.
15100   EVT VT = N->getValueType(0);
15101   if (ISD::allOperandsUndef(N))
15102     return DAG.getUNDEF(VT);
15103
15104   // Optimize concat_vectors where all but the first of the vectors are undef.
15105   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15106         return Op.isUndef();
15107       })) {
15108     SDValue In = N->getOperand(0);
15109     assert(In.getValueType().isVector() && "Must concat vectors");
15110
15111     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15112     if (In->getOpcode() == ISD::BITCAST &&
15113         !In->getOperand(0)->getValueType(0).isVector()) {
15114       SDValue Scalar = In->getOperand(0);
15115
15116       // If the bitcast type isn't legal, it might be a trunc of a legal type;
15117       // look through the trunc so we can still do the transform:
15118       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15119       if (Scalar->getOpcode() == ISD::TRUNCATE &&
15120           !TLI.isTypeLegal(Scalar.getValueType()) &&
15121           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15122         Scalar = Scalar->getOperand(0);
15123
15124       EVT SclTy = Scalar->getValueType(0);
15125
15126       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15127         return SDValue();
15128
15129       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15130       if (VNTNumElms < 2)
15131         return SDValue();
15132
15133       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15134       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15135         return SDValue();
15136
15137       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15138       return DAG.getBitcast(VT, Res);
15139     }
15140   }
15141
15142   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15143   // We have already tested above for an UNDEF only concatenation.
15144   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15145   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15146   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15147     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15148   };
15149   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15150     SmallVector<SDValue, 8> Opnds;
15151     EVT SVT = VT.getScalarType();
15152
15153     EVT MinVT = SVT;
15154     if (!SVT.isFloatingPoint()) {
15155       // If BUILD_VECTOR are from built from integer, they may have different
15156       // operand types. Get the smallest type and truncate all operands to it.
15157       bool FoundMinVT = false;
15158       for (const SDValue &Op : N->ops())
15159         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15160           EVT OpSVT = Op.getOperand(0)->getValueType(0);
15161           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15162           FoundMinVT = true;
15163         }
15164       assert(FoundMinVT && "Concat vector type mismatch");
15165     }
15166
15167     for (const SDValue &Op : N->ops()) {
15168       EVT OpVT = Op.getValueType();
15169       unsigned NumElts = OpVT.getVectorNumElements();
15170
15171       if (ISD::UNDEF == Op.getOpcode())
15172         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
15173
15174       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15175         if (SVT.isFloatingPoint()) {
15176           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
15177           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
15178         } else {
15179           for (unsigned i = 0; i != NumElts; ++i)
15180             Opnds.push_back(
15181                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15182         }
15183       }
15184     }
15185
15186     assert(VT.getVectorNumElements() == Opnds.size() &&
15187            "Concat vector type mismatch");
15188     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15189   }
15190
15191   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15192   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15193     return V;
15194
15195   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15196   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15197     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15198       return V;
15199
15200   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15201   // nodes often generate nop CONCAT_VECTOR nodes.
15202   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15203   // place the incoming vectors at the exact same location.
15204   SDValue SingleSource = SDValue();
15205   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15206
15207   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15208     SDValue Op = N->getOperand(i);
15209
15210     if (Op.isUndef())
15211       continue;
15212
15213     // Check if this is the identity extract:
15214     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15215       return SDValue();
15216
15217     // Find the single incoming vector for the extract_subvector.
15218     if (SingleSource.getNode()) {
15219       if (Op.getOperand(0) != SingleSource)
15220         return SDValue();
15221     } else {
15222       SingleSource = Op.getOperand(0);
15223
15224       // Check the source type is the same as the type of the result.
15225       // If not, this concat may extend the vector, so we can not
15226       // optimize it away.
15227       if (SingleSource.getValueType() != N->getValueType(0))
15228         return SDValue();
15229     }
15230
15231     unsigned IdentityIndex = i * PartNumElem;
15232     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15233     // The extract index must be constant.
15234     if (!CS)
15235       return SDValue();
15236
15237     // Check that we are reading from the identity index.
15238     if (CS->getZExtValue() != IdentityIndex)
15239       return SDValue();
15240   }
15241
15242   if (SingleSource.getNode())
15243     return SingleSource;
15244
15245   return SDValue();
15246 }
15247
15248 /// If we are extracting a subvector produced by a wide binary operator with at
15249 /// at least one operand that was the result of a vector concatenation, then try
15250 /// to use the narrow vector operands directly to avoid the concatenation and
15251 /// extraction.
15252 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15253   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15254   // some of these bailouts with other transforms.
15255
15256   // The extract index must be a constant, so we can map it to a concat operand.
15257   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15258   if (!ExtractIndex)
15259     return SDValue();
15260
15261   // Only handle the case where we are doubling and then halving. A larger ratio
15262   // may require more than two narrow binops to replace the wide binop.
15263   EVT VT = Extract->getValueType(0);
15264   unsigned NumElems = VT.getVectorNumElements();
15265   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15266          "Extract index is not a multiple of the vector length.");
15267   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15268     return SDValue();
15269
15270   // We are looking for an optionally bitcasted wide vector binary operator
15271   // feeding an extract subvector.
15272   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15273
15274   // TODO: The motivating case for this transform is an x86 AVX1 target. That
15275   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15276   // flavors, but no other 256-bit integer support. This could be extended to
15277   // handle any binop, but that may require fixing/adding other folds to avoid
15278   // codegen regressions.
15279   unsigned BOpcode = BinOp.getOpcode();
15280   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15281     return SDValue();
15282
15283   // The binop must be a vector type, so we can chop it in half.
15284   EVT WideBVT = BinOp.getValueType();
15285   if (!WideBVT.isVector())
15286     return SDValue();
15287
15288   // Bail out if the target does not support a narrower version of the binop.
15289   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15290                                    WideBVT.getVectorNumElements() / 2);
15291   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15292   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15293     return SDValue();
15294
15295   // Peek through bitcasts of the binary operator operands if needed.
15296   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15297   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15298
15299   // We need at least one concatenation operation of a binop operand to make
15300   // this transform worthwhile. The concat must double the input vector sizes.
15301   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15302   bool ConcatL =
15303       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15304   bool ConcatR =
15305       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15306   if (!ConcatL && !ConcatR)
15307     return SDValue();
15308
15309   // If one of the binop operands was not the result of a concat, we must
15310   // extract a half-sized operand for our new narrow binop. We can't just reuse
15311   // the original extract index operand because we may have bitcasted.
15312   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15313   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15314   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15315   SDLoc DL(Extract);
15316
15317   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15318   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15319   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15320   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15321                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15322                                     BinOp.getOperand(0),
15323                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15324
15325   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15326                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15327                                     BinOp.getOperand(1),
15328                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15329
15330   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15331   return DAG.getBitcast(VT, NarrowBinOp);
15332 }
15333
15334 /// If we are extracting a subvector from a wide vector load, convert to a
15335 /// narrow load to eliminate the extraction:
15336 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15337 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15338   // TODO: Add support for big-endian. The offset calculation must be adjusted.
15339   if (DAG.getDataLayout().isBigEndian())
15340     return SDValue();
15341
15342   // TODO: The one-use check is overly conservative. Check the cost of the
15343   // extract instead or remove that condition entirely.
15344   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15345   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15346   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15347       !ExtIdx)
15348     return SDValue();
15349
15350   // The narrow load will be offset from the base address of the old load if
15351   // we are extracting from something besides index 0 (little-endian).
15352   EVT VT = Extract->getValueType(0);
15353   SDLoc DL(Extract);
15354   SDValue BaseAddr = Ld->getOperand(1);
15355   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15356
15357   // TODO: Use "BaseIndexOffset" to make this more effective.
15358   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15359   MachineFunction &MF = DAG.getMachineFunction();
15360   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15361                                                    VT.getStoreSize());
15362   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15363   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15364   return NewLd;
15365 }
15366
15367 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15368   EVT NVT = N->getValueType(0);
15369   SDValue V = N->getOperand(0);
15370
15371   // Extract from UNDEF is UNDEF.
15372   if (V.isUndef())
15373     return DAG.getUNDEF(NVT);
15374
15375   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15376     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15377       return NarrowLoad;
15378
15379   // Combine:
15380   //    (extract_subvec (concat V1, V2, ...), i)
15381   // Into:
15382   //    Vi if possible
15383   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15384   // type.
15385   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15386       isa<ConstantSDNode>(N->getOperand(1)) &&
15387       V->getOperand(0).getValueType() == NVT) {
15388     unsigned Idx = N->getConstantOperandVal(1);
15389     unsigned NumElems = NVT.getVectorNumElements();
15390     assert((Idx % NumElems) == 0 &&
15391            "IDX in concat is not a multiple of the result vector length.");
15392     return V->getOperand(Idx / NumElems);
15393   }
15394
15395   // Skip bitcasting
15396   V = peekThroughBitcast(V);
15397
15398   // If the input is a build vector. Try to make a smaller build vector.
15399   if (V->getOpcode() == ISD::BUILD_VECTOR) {
15400     if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15401       EVT InVT = V->getValueType(0);
15402       unsigned ExtractSize = NVT.getSizeInBits();
15403       unsigned EltSize = InVT.getScalarSizeInBits();
15404       // Only do this if we won't split any elements.
15405       if (ExtractSize % EltSize == 0) {
15406         unsigned NumElems = ExtractSize / EltSize;
15407         EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15408                                          InVT.getVectorElementType(), NumElems);
15409         if ((!LegalOperations ||
15410              TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15411             (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15412           unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15413                             EltSize;
15414
15415           // Extract the pieces from the original build_vector.
15416           SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15417                                             makeArrayRef(V->op_begin() + IdxVal,
15418                                                          NumElems));
15419           return DAG.getBitcast(NVT, BuildVec);
15420         }
15421       }
15422     }
15423   }
15424
15425   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15426     // Handle only simple case where vector being inserted and vector
15427     // being extracted are of same size.
15428     EVT SmallVT = V->getOperand(1).getValueType();
15429     if (!NVT.bitsEq(SmallVT))
15430       return SDValue();
15431
15432     // Only handle cases where both indexes are constants.
15433     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15434     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15435
15436     if (InsIdx && ExtIdx) {
15437       // Combine:
15438       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15439       // Into:
15440       //    indices are equal or bit offsets are equal => V1
15441       //    otherwise => (extract_subvec V1, ExtIdx)
15442       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15443           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15444         return DAG.getBitcast(NVT, V->getOperand(1));
15445       return DAG.getNode(
15446           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15447           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15448           N->getOperand(1));
15449     }
15450   }
15451
15452   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15453     return NarrowBOp;
15454
15455   return SDValue();
15456 }
15457
15458 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15459                                                  SDValue V, SelectionDAG &DAG) {
15460   SDLoc DL(V);
15461   EVT VT = V.getValueType();
15462
15463   switch (V.getOpcode()) {
15464   default:
15465     return V;
15466
15467   case ISD::CONCAT_VECTORS: {
15468     EVT OpVT = V->getOperand(0).getValueType();
15469     int OpSize = OpVT.getVectorNumElements();
15470     SmallBitVector OpUsedElements(OpSize, false);
15471     bool FoundSimplification = false;
15472     SmallVector<SDValue, 4> NewOps;
15473     NewOps.reserve(V->getNumOperands());
15474     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15475       SDValue Op = V->getOperand(i);
15476       bool OpUsed = false;
15477       for (int j = 0; j < OpSize; ++j)
15478         if (UsedElements[i * OpSize + j]) {
15479           OpUsedElements[j] = true;
15480           OpUsed = true;
15481         }
15482       NewOps.push_back(
15483           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15484                  : DAG.getUNDEF(OpVT));
15485       FoundSimplification |= Op == NewOps.back();
15486       OpUsedElements.reset();
15487     }
15488     if (FoundSimplification)
15489       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15490     return V;
15491   }
15492
15493   case ISD::INSERT_SUBVECTOR: {
15494     SDValue BaseV = V->getOperand(0);
15495     SDValue SubV = V->getOperand(1);
15496     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15497     if (!IdxN)
15498       return V;
15499
15500     int SubSize = SubV.getValueType().getVectorNumElements();
15501     int Idx = IdxN->getZExtValue();
15502     bool SubVectorUsed = false;
15503     SmallBitVector SubUsedElements(SubSize, false);
15504     for (int i = 0; i < SubSize; ++i)
15505       if (UsedElements[i + Idx]) {
15506         SubVectorUsed = true;
15507         SubUsedElements[i] = true;
15508         UsedElements[i + Idx] = false;
15509       }
15510
15511     // Now recurse on both the base and sub vectors.
15512     SDValue SimplifiedSubV =
15513         SubVectorUsed
15514             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15515             : DAG.getUNDEF(SubV.getValueType());
15516     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15517     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15518       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15519                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15520     return V;
15521   }
15522   }
15523 }
15524
15525 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15526                                        SDValue N1, SelectionDAG &DAG) {
15527   EVT VT = SVN->getValueType(0);
15528   int NumElts = VT.getVectorNumElements();
15529   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15530   for (int M : SVN->getMask())
15531     if (M >= 0 && M < NumElts)
15532       N0UsedElements[M] = true;
15533     else if (M >= NumElts)
15534       N1UsedElements[M - NumElts] = true;
15535
15536   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15537   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15538   if (S0 == N0 && S1 == N1)
15539     return SDValue();
15540
15541   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15542 }
15543
15544 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15545                                    SDValue N1, SelectionDAG &DAG) {
15546   auto isUndefElt = [](SDValue V, int Idx) {
15547     // TODO - handle more cases as required.
15548     if (V.getOpcode() == ISD::BUILD_VECTOR)
15549       return V.getOperand(Idx).isUndef();
15550     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
15551       return (Idx != 0) || V.getOperand(0).isUndef();
15552     return false;
15553   };
15554
15555   EVT VT = SVN->getValueType(0);
15556   unsigned NumElts = VT.getVectorNumElements();
15557
15558   bool Changed = false;
15559   SmallVector<int, 8> NewMask;
15560   for (unsigned i = 0; i != NumElts; ++i) {
15561     int Idx = SVN->getMaskElt(i);
15562     if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15563         ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15564       Changed = true;
15565       Idx = -1;
15566     }
15567     NewMask.push_back(Idx);
15568   }
15569   if (Changed)
15570     return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15571
15572   return SDValue();
15573 }
15574
15575 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15576 // or turn a shuffle of a single concat into simpler shuffle then concat.
15577 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15578   EVT VT = N->getValueType(0);
15579   unsigned NumElts = VT.getVectorNumElements();
15580
15581   SDValue N0 = N->getOperand(0);
15582   SDValue N1 = N->getOperand(1);
15583   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15584
15585   SmallVector<SDValue, 4> Ops;
15586   EVT ConcatVT = N0.getOperand(0).getValueType();
15587   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15588   unsigned NumConcats = NumElts / NumElemsPerConcat;
15589
15590   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15591   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15592   // half vector elements.
15593   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15594       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15595                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15596     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15597                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15598     N1 = DAG.getUNDEF(ConcatVT);
15599     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15600   }
15601
15602   // Look at every vector that's inserted. We're looking for exact
15603   // subvector-sized copies from a concatenated vector
15604   for (unsigned I = 0; I != NumConcats; ++I) {
15605     // Make sure we're dealing with a copy.
15606     unsigned Begin = I * NumElemsPerConcat;
15607     bool AllUndef = true, NoUndef = true;
15608     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15609       if (SVN->getMaskElt(J) >= 0)
15610         AllUndef = false;
15611       else
15612         NoUndef = false;
15613     }
15614
15615     if (NoUndef) {
15616       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15617         return SDValue();
15618
15619       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15620         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15621           return SDValue();
15622
15623       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15624       if (FirstElt < N0.getNumOperands())
15625         Ops.push_back(N0.getOperand(FirstElt));
15626       else
15627         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15628
15629     } else if (AllUndef) {
15630       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15631     } else { // Mixed with general masks and undefs, can't do optimization.
15632       return SDValue();
15633     }
15634   }
15635
15636   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15637 }
15638
15639 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15640 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15641 //
15642 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15643 // a simplification in some sense, but it isn't appropriate in general: some
15644 // BUILD_VECTORs are substantially cheaper than others. The general case
15645 // of a BUILD_VECTOR requires inserting each element individually (or
15646 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15647 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15648 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15649 // are undef lowers to a small number of element insertions.
15650 //
15651 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15652 // We don't fold shuffles where one side is a non-zero constant, and we don't
15653 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
15654 // non-constant operands. This seems to work out reasonably well in practice.
15655 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15656                                        SelectionDAG &DAG,
15657                                        const TargetLowering &TLI) {
15658   EVT VT = SVN->getValueType(0);
15659   unsigned NumElts = VT.getVectorNumElements();
15660   SDValue N0 = SVN->getOperand(0);
15661   SDValue N1 = SVN->getOperand(1);
15662
15663   if (!N0->hasOneUse() || !N1->hasOneUse())
15664     return SDValue();
15665
15666   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15667   // discussed above.
15668   if (!N1.isUndef()) {
15669     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15670     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15671     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15672       return SDValue();
15673     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15674       return SDValue();
15675   }
15676
15677   // If both inputs are splats of the same value then we can safely merge this
15678   // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
15679   bool IsSplat = false;
15680   auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
15681   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
15682   if (BV0 && BV1)
15683     if (SDValue Splat0 = BV0->getSplatValue())
15684       IsSplat = (Splat0 == BV1->getSplatValue());
15685
15686   SmallVector<SDValue, 8> Ops;
15687   SmallSet<SDValue, 16> DuplicateOps;
15688   for (int M : SVN->getMask()) {
15689     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15690     if (M >= 0) {
15691       int Idx = M < (int)NumElts ? M : M - NumElts;
15692       SDValue &S = (M < (int)NumElts ? N0 : N1);
15693       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15694         Op = S.getOperand(Idx);
15695       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15696         assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.");
15697         Op = S.getOperand(0);
15698       } else {
15699         // Operand can't be combined - bail out.
15700         return SDValue();
15701       }
15702     }
15703
15704     // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
15705     // generating a splat; semantically, this is fine, but it's likely to
15706     // generate low-quality code if the target can't reconstruct an appropriate
15707     // shuffle.
15708     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15709       if (!IsSplat && !DuplicateOps.insert(Op).second)
15710         return SDValue();
15711
15712     Ops.push_back(Op);
15713   }
15714
15715   // BUILD_VECTOR requires all inputs to be of the same type, find the
15716   // maximum type and extend them all.
15717   EVT SVT = VT.getScalarType();
15718   if (SVT.isInteger())
15719     for (SDValue &Op : Ops)
15720       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15721   if (SVT != VT.getScalarType())
15722     for (SDValue &Op : Ops)
15723       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15724                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15725                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15726   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15727 }
15728
15729 // Match shuffles that can be converted to any_vector_extend_in_reg.
15730 // This is often generated during legalization.
15731 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15732 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15733 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15734                                             SelectionDAG &DAG,
15735                                             const TargetLowering &TLI,
15736                                             bool LegalOperations,
15737                                             bool LegalTypes) {
15738   EVT VT = SVN->getValueType(0);
15739   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15740
15741   // TODO Add support for big-endian when we have a test case.
15742   if (!VT.isInteger() || IsBigEndian)
15743     return SDValue();
15744
15745   unsigned NumElts = VT.getVectorNumElements();
15746   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15747   ArrayRef<int> Mask = SVN->getMask();
15748   SDValue N0 = SVN->getOperand(0);
15749
15750   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15751   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15752     for (unsigned i = 0; i != NumElts; ++i) {
15753       if (Mask[i] < 0)
15754         continue;
15755       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15756         continue;
15757       return false;
15758     }
15759     return true;
15760   };
15761
15762   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15763   // power-of-2 extensions as they are the most likely.
15764   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15765     // Check for non power of 2 vector sizes
15766     if (NumElts % Scale != 0)
15767       continue;
15768     if (!isAnyExtend(Scale))
15769       continue;
15770
15771     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15772     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15773     if (!LegalTypes || TLI.isTypeLegal(OutVT))
15774       if (!LegalOperations ||
15775           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15776         return DAG.getBitcast(VT,
15777                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15778   }
15779
15780   return SDValue();
15781 }
15782
15783 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15784 // each source element of a large type into the lowest elements of a smaller
15785 // destination type. This is often generated during legalization.
15786 // If the source node itself was a '*_extend_vector_inreg' node then we should
15787 // then be able to remove it.
15788 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15789                                         SelectionDAG &DAG) {
15790   EVT VT = SVN->getValueType(0);
15791   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15792
15793   // TODO Add support for big-endian when we have a test case.
15794   if (!VT.isInteger() || IsBigEndian)
15795     return SDValue();
15796
15797   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15798
15799   unsigned Opcode = N0.getOpcode();
15800   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15801       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15802       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15803     return SDValue();
15804
15805   SDValue N00 = N0.getOperand(0);
15806   ArrayRef<int> Mask = SVN->getMask();
15807   unsigned NumElts = VT.getVectorNumElements();
15808   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15809   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15810   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15811
15812   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15813     return SDValue();
15814   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15815
15816   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15817   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15818   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15819   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15820     for (unsigned i = 0; i != NumElts; ++i) {
15821       if (Mask[i] < 0)
15822         continue;
15823       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15824         continue;
15825       return false;
15826     }
15827     return true;
15828   };
15829
15830   // At the moment we just handle the case where we've truncated back to the
15831   // same size as before the extension.
15832   // TODO: handle more extension/truncation cases as cases arise.
15833   if (EltSizeInBits != ExtSrcSizeInBits)
15834     return SDValue();
15835
15836   // We can remove *extend_vector_inreg only if the truncation happens at
15837   // the same scale as the extension.
15838   if (isTruncate(ExtScale))
15839     return DAG.getBitcast(VT, N00);
15840
15841   return SDValue();
15842 }
15843
15844 // Combine shuffles of splat-shuffles of the form:
15845 // shuffle (shuffle V, undef, splat-mask), undef, M
15846 // If splat-mask contains undef elements, we need to be careful about
15847 // introducing undef's in the folded mask which are not the result of composing
15848 // the masks of the shuffles.
15849 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15850                                      ShuffleVectorSDNode *Splat,
15851                                      SelectionDAG &DAG) {
15852   ArrayRef<int> SplatMask = Splat->getMask();
15853   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15854
15855   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15856   // every undef mask element in the splat-shuffle has a corresponding undef
15857   // element in the user-shuffle's mask or if the composition of mask elements
15858   // would result in undef.
15859   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15860   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15861   //   In this case it is not legal to simplify to the splat-shuffle because we
15862   //   may be exposing the users of the shuffle an undef element at index 1
15863   //   which was not there before the combine.
15864   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15865   //   In this case the composition of masks yields SplatMask, so it's ok to
15866   //   simplify to the splat-shuffle.
15867   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15868   //   In this case the composed mask includes all undef elements of SplatMask
15869   //   and in addition sets element zero to undef. It is safe to simplify to
15870   //   the splat-shuffle.
15871   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15872                                        ArrayRef<int> SplatMask) {
15873     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15874       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15875           SplatMask[UserMask[i]] != -1)
15876         return false;
15877     return true;
15878   };
15879   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15880     return SDValue(Splat, 0);
15881
15882   // Create a new shuffle with a mask that is composed of the two shuffles'
15883   // masks.
15884   SmallVector<int, 32> NewMask;
15885   for (int Idx : UserMask)
15886     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15887
15888   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15889                               Splat->getOperand(0), Splat->getOperand(1),
15890                               NewMask);
15891 }
15892
15893 /// If the shuffle mask is taking exactly one element from the first vector
15894 /// operand and passing through all other elements from the second vector
15895 /// operand, return the index of the mask element that is choosing an element
15896 /// from the first operand. Otherwise, return -1.
15897 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
15898   int MaskSize = Mask.size();
15899   int EltFromOp0 = -1;
15900   // TODO: This does not match if there are undef elements in the shuffle mask.
15901   // Should we ignore undefs in the shuffle mask instead? The trade-off is
15902   // removing an instruction (a shuffle), but losing the knowledge that some
15903   // vector lanes are not needed.
15904   for (int i = 0; i != MaskSize; ++i) {
15905     if (Mask[i] >= 0 && Mask[i] < MaskSize) {
15906       // We're looking for a shuffle of exactly one element from operand 0.
15907       if (EltFromOp0 != -1)
15908         return -1;
15909       EltFromOp0 = i;
15910     } else if (Mask[i] != i + MaskSize) {
15911       // Nothing from operand 1 can change lanes.
15912       return -1;
15913     }
15914   }
15915   return EltFromOp0;
15916 }
15917
15918 /// If a shuffle inserts exactly one element from a source vector operand into
15919 /// another vector operand and we can access the specified element as a scalar,
15920 /// then we can eliminate the shuffle.
15921 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
15922                                       SelectionDAG &DAG) {
15923   // First, check if we are taking one element of a vector and shuffling that
15924   // element into another vector.
15925   ArrayRef<int> Mask = Shuf->getMask();
15926   SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
15927   SDValue Op0 = Shuf->getOperand(0);
15928   SDValue Op1 = Shuf->getOperand(1);
15929   int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
15930   if (ShufOp0Index == -1) {
15931     // Commute mask and check again.
15932     ShuffleVectorSDNode::commuteMask(CommutedMask);
15933     ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
15934     if (ShufOp0Index == -1)
15935       return SDValue();
15936     // Commute operands to match the commuted shuffle mask.
15937     std::swap(Op0, Op1);
15938     Mask = CommutedMask;
15939   }
15940
15941   // The shuffle inserts exactly one element from operand 0 into operand 1.
15942   // Now see if we can access that element as a scalar via a real insert element
15943   // instruction.
15944   // TODO: We can try harder to locate the element as a scalar. Examples: it
15945   // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
15946   assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
15947          "Shuffle mask value must be from operand 0");
15948   if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
15949     return SDValue();
15950
15951   auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
15952   if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
15953     return SDValue();
15954
15955   // There's an existing insertelement with constant insertion index, so we
15956   // don't need to check the legality/profitability of a replacement operation
15957   // that differs at most in the constant value. The target should be able to
15958   // lower any of those in a similar way. If not, legalization will expand this
15959   // to a scalar-to-vector plus shuffle.
15960   //
15961   // Note that the shuffle may move the scalar from the position that the insert
15962   // element used. Therefore, our new insert element occurs at the shuffle's
15963   // mask index value, not the insert's index value.
15964   // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
15965   SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
15966                                         Op0.getOperand(2).getValueType());
15967   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
15968                      Op1, Op0.getOperand(1), NewInsIndex);
15969 }
15970
15971 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15972   EVT VT = N->getValueType(0);
15973   unsigned NumElts = VT.getVectorNumElements();
15974
15975   SDValue N0 = N->getOperand(0);
15976   SDValue N1 = N->getOperand(1);
15977
15978   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15979
15980   // Canonicalize shuffle undef, undef -> undef
15981   if (N0.isUndef() && N1.isUndef())
15982     return DAG.getUNDEF(VT);
15983
15984   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15985
15986   // Canonicalize shuffle v, v -> v, undef
15987   if (N0 == N1) {
15988     SmallVector<int, 8> NewMask;
15989     for (unsigned i = 0; i != NumElts; ++i) {
15990       int Idx = SVN->getMaskElt(i);
15991       if (Idx >= (int)NumElts) Idx -= NumElts;
15992       NewMask.push_back(Idx);
15993     }
15994     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15995   }
15996
15997   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15998   if (N0.isUndef())
15999     return DAG.getCommutedVectorShuffle(*SVN);
16000
16001   // Remove references to rhs if it is undef
16002   if (N1.isUndef()) {
16003     bool Changed = false;
16004     SmallVector<int, 8> NewMask;
16005     for (unsigned i = 0; i != NumElts; ++i) {
16006       int Idx = SVN->getMaskElt(i);
16007       if (Idx >= (int)NumElts) {
16008         Idx = -1;
16009         Changed = true;
16010       }
16011       NewMask.push_back(Idx);
16012     }
16013     if (Changed)
16014       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16015   }
16016
16017   // Simplify shuffle mask if a referenced element is UNDEF.
16018   if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
16019     return V;
16020
16021   if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
16022     return InsElt;
16023
16024   // A shuffle of a single vector that is a splat can always be folded.
16025   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
16026     if (N1->isUndef() && N0Shuf->isSplat())
16027       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16028
16029   // If it is a splat, check if the argument vector is another splat or a
16030   // build_vector.
16031   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
16032     SDNode *V = N0.getNode();
16033
16034     // If this is a bit convert that changes the element type of the vector but
16035     // not the number of vector elements, look through it.  Be careful not to
16036     // look though conversions that change things like v4f32 to v2f64.
16037     if (V->getOpcode() == ISD::BITCAST) {
16038       SDValue ConvInput = V->getOperand(0);
16039       if (ConvInput.getValueType().isVector() &&
16040           ConvInput.getValueType().getVectorNumElements() == NumElts)
16041         V = ConvInput.getNode();
16042     }
16043
16044     if (V->getOpcode() == ISD::BUILD_VECTOR) {
16045       assert(V->getNumOperands() == NumElts &&
16046              "BUILD_VECTOR has wrong number of operands");
16047       SDValue Base;
16048       bool AllSame = true;
16049       for (unsigned i = 0; i != NumElts; ++i) {
16050         if (!V->getOperand(i).isUndef()) {
16051           Base = V->getOperand(i);
16052           break;
16053         }
16054       }
16055       // Splat of <u, u, u, u>, return <u, u, u, u>
16056       if (!Base.getNode())
16057         return N0;
16058       for (unsigned i = 0; i != NumElts; ++i) {
16059         if (V->getOperand(i) != Base) {
16060           AllSame = false;
16061           break;
16062         }
16063       }
16064       // Splat of <x, x, x, x>, return <x, x, x, x>
16065       if (AllSame)
16066         return N0;
16067
16068       // Canonicalize any other splat as a build_vector.
16069       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16070       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16071       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16072
16073       // We may have jumped through bitcasts, so the type of the
16074       // BUILD_VECTOR may not match the type of the shuffle.
16075       if (V->getValueType(0) != VT)
16076         NewBV = DAG.getBitcast(VT, NewBV);
16077       return NewBV;
16078     }
16079   }
16080
16081   // There are various patterns used to build up a vector from smaller vectors,
16082   // subvectors, or elements. Scan chains of these and replace unused insertions
16083   // or components with undef.
16084   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
16085     return S;
16086
16087   // Match shuffles that can be converted to any_vector_extend_in_reg.
16088   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16089     return V;
16090
16091   // Combine "truncate_vector_in_reg" style shuffles.
16092   if (SDValue V = combineTruncationShuffle(SVN, DAG))
16093     return V;
16094
16095   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16096       Level < AfterLegalizeVectorOps &&
16097       (N1.isUndef() ||
16098       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16099        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16100     if (SDValue V = partitionShuffleOfConcats(N, DAG))
16101       return V;
16102   }
16103
16104   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16105   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16106   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16107     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16108       return Res;
16109
16110   // If this shuffle only has a single input that is a bitcasted shuffle,
16111   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16112   // back to their original types.
16113   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16114       N1.isUndef() && Level < AfterLegalizeVectorOps &&
16115       TLI.isTypeLegal(VT)) {
16116
16117     // Peek through the bitcast only if there is one user.
16118     SDValue BC0 = N0;
16119     while (BC0.getOpcode() == ISD::BITCAST) {
16120       if (!BC0.hasOneUse())
16121         break;
16122       BC0 = BC0.getOperand(0);
16123     }
16124
16125     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16126       if (Scale == 1)
16127         return SmallVector<int, 8>(Mask.begin(), Mask.end());
16128
16129       SmallVector<int, 8> NewMask;
16130       for (int M : Mask)
16131         for (int s = 0; s != Scale; ++s)
16132           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16133       return NewMask;
16134     };
16135
16136     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16137       EVT SVT = VT.getScalarType();
16138       EVT InnerVT = BC0->getValueType(0);
16139       EVT InnerSVT = InnerVT.getScalarType();
16140
16141       // Determine which shuffle works with the smaller scalar type.
16142       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16143       EVT ScaleSVT = ScaleVT.getScalarType();
16144
16145       if (TLI.isTypeLegal(ScaleVT) &&
16146           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16147           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16148         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16149         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16150
16151         // Scale the shuffle masks to the smaller scalar type.
16152         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16153         SmallVector<int, 8> InnerMask =
16154             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16155         SmallVector<int, 8> OuterMask =
16156             ScaleShuffleMask(SVN->getMask(), OuterScale);
16157
16158         // Merge the shuffle masks.
16159         SmallVector<int, 8> NewMask;
16160         for (int M : OuterMask)
16161           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16162
16163         // Test for shuffle mask legality over both commutations.
16164         SDValue SV0 = BC0->getOperand(0);
16165         SDValue SV1 = BC0->getOperand(1);
16166         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16167         if (!LegalMask) {
16168           std::swap(SV0, SV1);
16169           ShuffleVectorSDNode::commuteMask(NewMask);
16170           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16171         }
16172
16173         if (LegalMask) {
16174           SV0 = DAG.getBitcast(ScaleVT, SV0);
16175           SV1 = DAG.getBitcast(ScaleVT, SV1);
16176           return DAG.getBitcast(
16177               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16178         }
16179       }
16180     }
16181   }
16182
16183   // Canonicalize shuffles according to rules:
16184   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16185   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16186   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16187   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16188       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16189       TLI.isTypeLegal(VT)) {
16190     // The incoming shuffle must be of the same type as the result of the
16191     // current shuffle.
16192     assert(N1->getOperand(0).getValueType() == VT &&
16193            "Shuffle types don't match");
16194
16195     SDValue SV0 = N1->getOperand(0);
16196     SDValue SV1 = N1->getOperand(1);
16197     bool HasSameOp0 = N0 == SV0;
16198     bool IsSV1Undef = SV1.isUndef();
16199     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16200       // Commute the operands of this shuffle so that next rule
16201       // will trigger.
16202       return DAG.getCommutedVectorShuffle(*SVN);
16203   }
16204
16205   // Try to fold according to rules:
16206   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16207   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16208   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16209   // Don't try to fold shuffles with illegal type.
16210   // Only fold if this shuffle is the only user of the other shuffle.
16211   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16212       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16213     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16214
16215     // Don't try to fold splats; they're likely to simplify somehow, or they
16216     // might be free.
16217     if (OtherSV->isSplat())
16218       return SDValue();
16219
16220     // The incoming shuffle must be of the same type as the result of the
16221     // current shuffle.
16222     assert(OtherSV->getOperand(0).getValueType() == VT &&
16223            "Shuffle types don't match");
16224
16225     SDValue SV0, SV1;
16226     SmallVector<int, 4> Mask;
16227     // Compute the combined shuffle mask for a shuffle with SV0 as the first
16228     // operand, and SV1 as the second operand.
16229     for (unsigned i = 0; i != NumElts; ++i) {
16230       int Idx = SVN->getMaskElt(i);
16231       if (Idx < 0) {
16232         // Propagate Undef.
16233         Mask.push_back(Idx);
16234         continue;
16235       }
16236
16237       SDValue CurrentVec;
16238       if (Idx < (int)NumElts) {
16239         // This shuffle index refers to the inner shuffle N0. Lookup the inner
16240         // shuffle mask to identify which vector is actually referenced.
16241         Idx = OtherSV->getMaskElt(Idx);
16242         if (Idx < 0) {
16243           // Propagate Undef.
16244           Mask.push_back(Idx);
16245           continue;
16246         }
16247
16248         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16249                                            : OtherSV->getOperand(1);
16250       } else {
16251         // This shuffle index references an element within N1.
16252         CurrentVec = N1;
16253       }
16254
16255       // Simple case where 'CurrentVec' is UNDEF.
16256       if (CurrentVec.isUndef()) {
16257         Mask.push_back(-1);
16258         continue;
16259       }
16260
16261       // Canonicalize the shuffle index. We don't know yet if CurrentVec
16262       // will be the first or second operand of the combined shuffle.
16263       Idx = Idx % NumElts;
16264       if (!SV0.getNode() || SV0 == CurrentVec) {
16265         // Ok. CurrentVec is the left hand side.
16266         // Update the mask accordingly.
16267         SV0 = CurrentVec;
16268         Mask.push_back(Idx);
16269         continue;
16270       }
16271
16272       // Bail out if we cannot convert the shuffle pair into a single shuffle.
16273       if (SV1.getNode() && SV1 != CurrentVec)
16274         return SDValue();
16275
16276       // Ok. CurrentVec is the right hand side.
16277       // Update the mask accordingly.
16278       SV1 = CurrentVec;
16279       Mask.push_back(Idx + NumElts);
16280     }
16281
16282     // Check if all indices in Mask are Undef. In case, propagate Undef.
16283     bool isUndefMask = true;
16284     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16285       isUndefMask &= Mask[i] < 0;
16286
16287     if (isUndefMask)
16288       return DAG.getUNDEF(VT);
16289
16290     if (!SV0.getNode())
16291       SV0 = DAG.getUNDEF(VT);
16292     if (!SV1.getNode())
16293       SV1 = DAG.getUNDEF(VT);
16294
16295     // Avoid introducing shuffles with illegal mask.
16296     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16297       ShuffleVectorSDNode::commuteMask(Mask);
16298
16299       if (!TLI.isShuffleMaskLegal(Mask, VT))
16300         return SDValue();
16301
16302       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16303       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16304       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16305       std::swap(SV0, SV1);
16306     }
16307
16308     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16309     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16310     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16311     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16312   }
16313
16314   return SDValue();
16315 }
16316
16317 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16318   SDValue InVal = N->getOperand(0);
16319   EVT VT = N->getValueType(0);
16320
16321   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16322   // with a VECTOR_SHUFFLE and possible truncate.
16323   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16324     SDValue InVec = InVal->getOperand(0);
16325     SDValue EltNo = InVal->getOperand(1);
16326     auto InVecT = InVec.getValueType();
16327     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16328       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16329       int Elt = C0->getZExtValue();
16330       NewMask[0] = Elt;
16331       SDValue Val;
16332       // If we have an implict truncate do truncate here as long as it's legal.
16333       // if it's not legal, this should
16334       if (VT.getScalarType() != InVal.getValueType() &&
16335           InVal.getValueType().isScalarInteger() &&
16336           isTypeLegal(VT.getScalarType())) {
16337         Val =
16338             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16339         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16340       }
16341       if (VT.getScalarType() == InVecT.getScalarType() &&
16342           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16343           TLI.isShuffleMaskLegal(NewMask, VT)) {
16344         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16345                                    DAG.getUNDEF(InVecT), NewMask);
16346         // If the initial vector is the correct size this shuffle is a
16347         // valid result.
16348         if (VT == InVecT)
16349           return Val;
16350         // If not we must truncate the vector.
16351         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16352           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16353           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16354           EVT SubVT =
16355               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16356                                VT.getVectorNumElements());
16357           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16358                             ZeroIdx);
16359           return Val;
16360         }
16361       }
16362     }
16363   }
16364
16365   return SDValue();
16366 }
16367
16368 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16369   EVT VT = N->getValueType(0);
16370   SDValue N0 = N->getOperand(0);
16371   SDValue N1 = N->getOperand(1);
16372   SDValue N2 = N->getOperand(2);
16373
16374   // If inserting an UNDEF, just return the original vector.
16375   if (N1.isUndef())
16376     return N0;
16377
16378   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16379   // us to pull BITCASTs from input to output.
16380   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16381     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16382       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16383
16384   // If this is an insert of an extracted vector into an undef vector, we can
16385   // just use the input to the extract.
16386   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16387       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16388     return N1.getOperand(0);
16389
16390   // If we are inserting a bitcast value into an undef, with the same
16391   // number of elements, just use the bitcast input of the extract.
16392   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16393   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16394   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16395       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16396       N1.getOperand(0).getOperand(1) == N2 &&
16397       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16398           VT.getVectorNumElements()) {
16399     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16400   }
16401
16402   // If both N1 and N2 are bitcast values on which insert_subvector
16403   // would makes sense, pull the bitcast through.
16404   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16405   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16406   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16407     SDValue CN0 = N0.getOperand(0);
16408     SDValue CN1 = N1.getOperand(0);
16409     if (CN0.getValueType().getVectorElementType() ==
16410             CN1.getValueType().getVectorElementType() &&
16411         CN0.getValueType().getVectorNumElements() ==
16412             VT.getVectorNumElements()) {
16413       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16414                                       CN0.getValueType(), CN0, CN1, N2);
16415       return DAG.getBitcast(VT, NewINSERT);
16416     }
16417   }
16418
16419   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16420   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16421   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16422   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16423       N0.getOperand(1).getValueType() == N1.getValueType() &&
16424       N0.getOperand(2) == N2)
16425     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16426                        N1, N2);
16427
16428   if (!isa<ConstantSDNode>(N2))
16429     return SDValue();
16430
16431   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16432
16433   // Canonicalize insert_subvector dag nodes.
16434   // Example:
16435   // (insert_subvector (insert_subvector A, Idx0), Idx1)
16436   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16437   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16438       N1.getValueType() == N0.getOperand(1).getValueType() &&
16439       isa<ConstantSDNode>(N0.getOperand(2))) {
16440     unsigned OtherIdx = N0.getConstantOperandVal(2);
16441     if (InsIdx < OtherIdx) {
16442       // Swap nodes.
16443       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16444                                   N0.getOperand(0), N1, N2);
16445       AddToWorklist(NewOp.getNode());
16446       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16447                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16448     }
16449   }
16450
16451   // If the input vector is a concatenation, and the insert replaces
16452   // one of the pieces, we can optimize into a single concat_vectors.
16453   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16454       N0.getOperand(0).getValueType() == N1.getValueType()) {
16455     unsigned Factor = N1.getValueType().getVectorNumElements();
16456
16457     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16458     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16459
16460     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16461   }
16462
16463   return SDValue();
16464 }
16465
16466 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16467   SDValue N0 = N->getOperand(0);
16468
16469   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16470   if (N0->getOpcode() == ISD::FP16_TO_FP)
16471     return N0->getOperand(0);
16472
16473   return SDValue();
16474 }
16475
16476 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16477   SDValue N0 = N->getOperand(0);
16478
16479   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16480   if (N0->getOpcode() == ISD::AND) {
16481     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16482     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16483       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16484                          N0.getOperand(0));
16485     }
16486   }
16487
16488   return SDValue();
16489 }
16490
16491 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16492 /// with the destination vector and a zero vector.
16493 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16494 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16495 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16496   EVT VT = N->getValueType(0);
16497   SDValue LHS = N->getOperand(0);
16498   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16499   SDLoc DL(N);
16500
16501   // Make sure we're not running after operation legalization where it
16502   // may have custom lowered the vector shuffles.
16503   if (LegalOperations)
16504     return SDValue();
16505
16506   if (N->getOpcode() != ISD::AND)
16507     return SDValue();
16508
16509   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16510     return SDValue();
16511
16512   EVT RVT = RHS.getValueType();
16513   unsigned NumElts = RHS.getNumOperands();
16514
16515   // Attempt to create a valid clear mask, splitting the mask into
16516   // sub elements and checking to see if each is
16517   // all zeros or all ones - suitable for shuffle masking.
16518   auto BuildClearMask = [&](int Split) {
16519     int NumSubElts = NumElts * Split;
16520     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16521
16522     SmallVector<int, 8> Indices;
16523     for (int i = 0; i != NumSubElts; ++i) {
16524       int EltIdx = i / Split;
16525       int SubIdx = i % Split;
16526       SDValue Elt = RHS.getOperand(EltIdx);
16527       if (Elt.isUndef()) {
16528         Indices.push_back(-1);
16529         continue;
16530       }
16531
16532       APInt Bits;
16533       if (isa<ConstantSDNode>(Elt))
16534         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16535       else if (isa<ConstantFPSDNode>(Elt))
16536         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16537       else
16538         return SDValue();
16539
16540       // Extract the sub element from the constant bit mask.
16541       if (DAG.getDataLayout().isBigEndian()) {
16542         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16543       } else {
16544         Bits.lshrInPlace(SubIdx * NumSubBits);
16545       }
16546
16547       if (Split > 1)
16548         Bits = Bits.trunc(NumSubBits);
16549
16550       if (Bits.isAllOnesValue())
16551         Indices.push_back(i);
16552       else if (Bits == 0)
16553         Indices.push_back(i + NumSubElts);
16554       else
16555         return SDValue();
16556     }
16557
16558     // Let's see if the target supports this vector_shuffle.
16559     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16560     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16561     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16562       return SDValue();
16563
16564     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16565     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16566                                                    DAG.getBitcast(ClearVT, LHS),
16567                                                    Zero, Indices));
16568   };
16569
16570   // Determine maximum split level (byte level masking).
16571   int MaxSplit = 1;
16572   if (RVT.getScalarSizeInBits() % 8 == 0)
16573     MaxSplit = RVT.getScalarSizeInBits() / 8;
16574
16575   for (int Split = 1; Split <= MaxSplit; ++Split)
16576     if (RVT.getScalarSizeInBits() % Split == 0)
16577       if (SDValue S = BuildClearMask(Split))
16578         return S;
16579
16580   return SDValue();
16581 }
16582
16583 /// Visit a binary vector operation, like ADD.
16584 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16585   assert(N->getValueType(0).isVector() &&
16586          "SimplifyVBinOp only works on vectors!");
16587
16588   SDValue LHS = N->getOperand(0);
16589   SDValue RHS = N->getOperand(1);
16590   SDValue Ops[] = {LHS, RHS};
16591
16592   // See if we can constant fold the vector operation.
16593   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16594           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16595     return Fold;
16596
16597   // Try to convert a constant mask AND into a shuffle clear mask.
16598   if (SDValue Shuffle = XformToShuffleWithZero(N))
16599     return Shuffle;
16600
16601   // Type legalization might introduce new shuffles in the DAG.
16602   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16603   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16604   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16605       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16606       LHS.getOperand(1).isUndef() &&
16607       RHS.getOperand(1).isUndef()) {
16608     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16609     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16610
16611     if (SVN0->getMask().equals(SVN1->getMask())) {
16612       EVT VT = N->getValueType(0);
16613       SDValue UndefVector = LHS.getOperand(1);
16614       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16615                                      LHS.getOperand(0), RHS.getOperand(0),
16616                                      N->getFlags());
16617       AddUsersToWorklist(N);
16618       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16619                                   SVN0->getMask());
16620     }
16621   }
16622
16623   return SDValue();
16624 }
16625
16626 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16627                                     SDValue N2) {
16628   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16629
16630   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16631                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16632
16633   // If we got a simplified select_cc node back from SimplifySelectCC, then
16634   // break it down into a new SETCC node, and a new SELECT node, and then return
16635   // the SELECT node, since we were called with a SELECT node.
16636   if (SCC.getNode()) {
16637     // Check to see if we got a select_cc back (to turn into setcc/select).
16638     // Otherwise, just return whatever node we got back, like fabs.
16639     if (SCC.getOpcode() == ISD::SELECT_CC) {
16640       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16641                                   N0.getValueType(),
16642                                   SCC.getOperand(0), SCC.getOperand(1),
16643                                   SCC.getOperand(4));
16644       AddToWorklist(SETCC.getNode());
16645       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16646                            SCC.getOperand(2), SCC.getOperand(3));
16647     }
16648
16649     return SCC;
16650   }
16651   return SDValue();
16652 }
16653
16654 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16655 /// being selected between, see if we can simplify the select.  Callers of this
16656 /// should assume that TheSelect is deleted if this returns true.  As such, they
16657 /// should return the appropriate thing (e.g. the node) back to the top-level of
16658 /// the DAG combiner loop to avoid it being looked at.
16659 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16660                                     SDValue RHS) {
16661   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16662   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16663   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16664     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16665       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16666       SDValue Sqrt = RHS;
16667       ISD::CondCode CC;
16668       SDValue CmpLHS;
16669       const ConstantFPSDNode *Zero = nullptr;
16670
16671       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16672         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16673         CmpLHS = TheSelect->getOperand(0);
16674         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16675       } else {
16676         // SELECT or VSELECT
16677         SDValue Cmp = TheSelect->getOperand(0);
16678         if (Cmp.getOpcode() == ISD::SETCC) {
16679           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16680           CmpLHS = Cmp.getOperand(0);
16681           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16682         }
16683       }
16684       if (Zero && Zero->isZero() &&
16685           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16686           CC == ISD::SETULT || CC == ISD::SETLT)) {
16687         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16688         CombineTo(TheSelect, Sqrt);
16689         return true;
16690       }
16691     }
16692   }
16693   // Cannot simplify select with vector condition
16694   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16695
16696   // If this is a select from two identical things, try to pull the operation
16697   // through the select.
16698   if (LHS.getOpcode() != RHS.getOpcode() ||
16699       !LHS.hasOneUse() || !RHS.hasOneUse())
16700     return false;
16701
16702   // If this is a load and the token chain is identical, replace the select
16703   // of two loads with a load through a select of the address to load from.
16704   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16705   // constants have been dropped into the constant pool.
16706   if (LHS.getOpcode() == ISD::LOAD) {
16707     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16708     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16709
16710     // Token chains must be identical.
16711     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16712         // Do not let this transformation reduce the number of volatile loads.
16713         LLD->isVolatile() || RLD->isVolatile() ||
16714         // FIXME: If either is a pre/post inc/dec load,
16715         // we'd need to split out the address adjustment.
16716         LLD->isIndexed() || RLD->isIndexed() ||
16717         // If this is an EXTLOAD, the VT's must match.
16718         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16719         // If this is an EXTLOAD, the kind of extension must match.
16720         (LLD->getExtensionType() != RLD->getExtensionType() &&
16721          // The only exception is if one of the extensions is anyext.
16722          LLD->getExtensionType() != ISD::EXTLOAD &&
16723          RLD->getExtensionType() != ISD::EXTLOAD) ||
16724         // FIXME: this discards src value information.  This is
16725         // over-conservative. It would be beneficial to be able to remember
16726         // both potential memory locations.  Since we are discarding
16727         // src value info, don't do the transformation if the memory
16728         // locations are not in the default address space.
16729         LLD->getPointerInfo().getAddrSpace() != 0 ||
16730         RLD->getPointerInfo().getAddrSpace() != 0 ||
16731         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16732                                       LLD->getBasePtr().getValueType()))
16733       return false;
16734
16735     // Check that the select condition doesn't reach either load.  If so,
16736     // folding this will induce a cycle into the DAG.  If not, this is safe to
16737     // xform, so create a select of the addresses.
16738     SDValue Addr;
16739     if (TheSelect->getOpcode() == ISD::SELECT) {
16740       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16741       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16742           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16743         return false;
16744       // The loads must not depend on one another.
16745       if (LLD->isPredecessorOf(RLD) ||
16746           RLD->isPredecessorOf(LLD))
16747         return false;
16748       Addr = DAG.getSelect(SDLoc(TheSelect),
16749                            LLD->getBasePtr().getValueType(),
16750                            TheSelect->getOperand(0), LLD->getBasePtr(),
16751                            RLD->getBasePtr());
16752     } else {  // Otherwise SELECT_CC
16753       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16754       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16755
16756       if ((LLD->hasAnyUseOfValue(1) &&
16757            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16758           (RLD->hasAnyUseOfValue(1) &&
16759            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16760         return false;
16761
16762       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16763                          LLD->getBasePtr().getValueType(),
16764                          TheSelect->getOperand(0),
16765                          TheSelect->getOperand(1),
16766                          LLD->getBasePtr(), RLD->getBasePtr(),
16767                          TheSelect->getOperand(4));
16768     }
16769
16770     SDValue Load;
16771     // It is safe to replace the two loads if they have different alignments,
16772     // but the new load must be the minimum (most restrictive) alignment of the
16773     // inputs.
16774     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16775     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16776     if (!RLD->isInvariant())
16777       MMOFlags &= ~MachineMemOperand::MOInvariant;
16778     if (!RLD->isDereferenceable())
16779       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16780     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16781       // FIXME: Discards pointer and AA info.
16782       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16783                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16784                          MMOFlags);
16785     } else {
16786       // FIXME: Discards pointer and AA info.
16787       Load = DAG.getExtLoad(
16788           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16789                                                   : LLD->getExtensionType(),
16790           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16791           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16792     }
16793
16794     // Users of the select now use the result of the load.
16795     CombineTo(TheSelect, Load);
16796
16797     // Users of the old loads now use the new load's chain.  We know the
16798     // old-load value is dead now.
16799     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16800     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16801     return true;
16802   }
16803
16804   return false;
16805 }
16806
16807 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16808 /// bitwise 'and'.
16809 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16810                                             SDValue N1, SDValue N2, SDValue N3,
16811                                             ISD::CondCode CC) {
16812   // If this is a select where the false operand is zero and the compare is a
16813   // check of the sign bit, see if we can perform the "gzip trick":
16814   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16815   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16816   EVT XType = N0.getValueType();
16817   EVT AType = N2.getValueType();
16818   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16819     return SDValue();
16820
16821   // If the comparison is testing for a positive value, we have to invert
16822   // the sign bit mask, so only do that transform if the target has a bitwise
16823   // 'and not' instruction (the invert is free).
16824   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16825     // (X > -1) ? A : 0
16826     // (X >  0) ? X : 0 <-- This is canonical signed max.
16827     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16828       return SDValue();
16829   } else if (CC == ISD::SETLT) {
16830     // (X <  0) ? A : 0
16831     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16832     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16833       return SDValue();
16834   } else {
16835     return SDValue();
16836   }
16837
16838   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16839   // constant.
16840   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16841   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16842   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16843     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16844     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16845     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16846     AddToWorklist(Shift.getNode());
16847
16848     if (XType.bitsGT(AType)) {
16849       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16850       AddToWorklist(Shift.getNode());
16851     }
16852
16853     if (CC == ISD::SETGT)
16854       Shift = DAG.getNOT(DL, Shift, AType);
16855
16856     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16857   }
16858
16859   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16860   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16861   AddToWorklist(Shift.getNode());
16862
16863   if (XType.bitsGT(AType)) {
16864     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16865     AddToWorklist(Shift.getNode());
16866   }
16867
16868   if (CC == ISD::SETGT)
16869     Shift = DAG.getNOT(DL, Shift, AType);
16870
16871   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16872 }
16873
16874 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16875 /// where 'cond' is the comparison specified by CC.
16876 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16877                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16878                                       bool NotExtCompare) {
16879   // (x ? y : y) -> y.
16880   if (N2 == N3) return N2;
16881
16882   EVT VT = N2.getValueType();
16883   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16884   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16885
16886   // Determine if the condition we're dealing with is constant
16887   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16888                               N0, N1, CC, DL, false);
16889   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16890
16891   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16892     // fold select_cc true, x, y -> x
16893     // fold select_cc false, x, y -> y
16894     return !SCCC->isNullValue() ? N2 : N3;
16895   }
16896
16897   // Check to see if we can simplify the select into an fabs node
16898   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16899     // Allow either -0.0 or 0.0
16900     if (CFP->isZero()) {
16901       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16902       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16903           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16904           N2 == N3.getOperand(0))
16905         return DAG.getNode(ISD::FABS, DL, VT, N0);
16906
16907       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16908       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16909           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16910           N2.getOperand(0) == N3)
16911         return DAG.getNode(ISD::FABS, DL, VT, N3);
16912     }
16913   }
16914
16915   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16916   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16917   // in it.  This is a win when the constant is not otherwise available because
16918   // it replaces two constant pool loads with one.  We only do this if the FP
16919   // type is known to be legal, because if it isn't, then we are before legalize
16920   // types an we want the other legalization to happen first (e.g. to avoid
16921   // messing with soft float) and if the ConstantFP is not legal, because if
16922   // it is legal, we may not need to store the FP constant in a constant pool.
16923   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16924     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16925       if (TLI.isTypeLegal(N2.getValueType()) &&
16926           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16927                TargetLowering::Legal &&
16928            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16929            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16930           // If both constants have multiple uses, then we won't need to do an
16931           // extra load, they are likely around in registers for other users.
16932           (TV->hasOneUse() || FV->hasOneUse())) {
16933         Constant *Elts[] = {
16934           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16935           const_cast<ConstantFP*>(TV->getConstantFPValue())
16936         };
16937         Type *FPTy = Elts[0]->getType();
16938         const DataLayout &TD = DAG.getDataLayout();
16939
16940         // Create a ConstantArray of the two constants.
16941         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16942         SDValue CPIdx =
16943             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16944                                 TD.getPrefTypeAlignment(FPTy));
16945         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16946
16947         // Get the offsets to the 0 and 1 element of the array so that we can
16948         // select between them.
16949         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16950         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16951         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16952
16953         SDValue Cond = DAG.getSetCC(DL,
16954                                     getSetCCResultType(N0.getValueType()),
16955                                     N0, N1, CC);
16956         AddToWorklist(Cond.getNode());
16957         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16958                                           Cond, One, Zero);
16959         AddToWorklist(CstOffset.getNode());
16960         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16961                             CstOffset);
16962         AddToWorklist(CPIdx.getNode());
16963         return DAG.getLoad(
16964             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16965             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16966             Alignment);
16967       }
16968     }
16969
16970   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16971     return V;
16972
16973   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16974   // where y is has a single bit set.
16975   // A plaintext description would be, we can turn the SELECT_CC into an AND
16976   // when the condition can be materialized as an all-ones register.  Any
16977   // single bit-test can be materialized as an all-ones register with
16978   // shift-left and shift-right-arith.
16979   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16980       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16981     SDValue AndLHS = N0->getOperand(0);
16982     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16983     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16984       // Shift the tested bit over the sign bit.
16985       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16986       SDValue ShlAmt =
16987         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16988                         getShiftAmountTy(AndLHS.getValueType()));
16989       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16990
16991       // Now arithmetic right shift it all the way over, so the result is either
16992       // all-ones, or zero.
16993       SDValue ShrAmt =
16994         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16995                         getShiftAmountTy(Shl.getValueType()));
16996       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16997
16998       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16999     }
17000   }
17001
17002   // fold select C, 16, 0 -> shl C, 4
17003   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17004       TLI.getBooleanContents(N0.getValueType()) ==
17005           TargetLowering::ZeroOrOneBooleanContent) {
17006
17007     // If the caller doesn't want us to simplify this into a zext of a compare,
17008     // don't do it.
17009     if (NotExtCompare && N2C->isOne())
17010       return SDValue();
17011
17012     // Get a SetCC of the condition
17013     // NOTE: Don't create a SETCC if it's not legal on this target.
17014     if (!LegalOperations ||
17015         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17016       SDValue Temp, SCC;
17017       // cast from setcc result type to select result type
17018       if (LegalTypes) {
17019         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17020                             N0, N1, CC);
17021         if (N2.getValueType().bitsLT(SCC.getValueType()))
17022           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17023                                         N2.getValueType());
17024         else
17025           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17026                              N2.getValueType(), SCC);
17027       } else {
17028         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17029         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17030                            N2.getValueType(), SCC);
17031       }
17032
17033       AddToWorklist(SCC.getNode());
17034       AddToWorklist(Temp.getNode());
17035
17036       if (N2C->isOne())
17037         return Temp;
17038
17039       // shl setcc result by log2 n2c
17040       return DAG.getNode(
17041           ISD::SHL, DL, N2.getValueType(), Temp,
17042           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17043                           getShiftAmountTy(Temp.getValueType())));
17044     }
17045   }
17046
17047   // Check to see if this is an integer abs.
17048   // select_cc setg[te] X,  0,  X, -X ->
17049   // select_cc setgt    X, -1,  X, -X ->
17050   // select_cc setl[te] X,  0, -X,  X ->
17051   // select_cc setlt    X,  1, -X,  X ->
17052   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17053   if (N1C) {
17054     ConstantSDNode *SubC = nullptr;
17055     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17056          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17057         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17058       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17059     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17060               (N1C->isOne() && CC == ISD::SETLT)) &&
17061              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17062       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17063
17064     EVT XType = N0.getValueType();
17065     if (SubC && SubC->isNullValue() && XType.isInteger()) {
17066       SDLoc DL(N0);
17067       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17068                                   N0,
17069                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
17070                                          getShiftAmountTy(N0.getValueType())));
17071       SDValue Add = DAG.getNode(ISD::ADD, DL,
17072                                 XType, N0, Shift);
17073       AddToWorklist(Shift.getNode());
17074       AddToWorklist(Add.getNode());
17075       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17076     }
17077   }
17078
17079   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17080   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17081   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17082   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17083   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17084   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17085   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17086   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17087   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17088     SDValue ValueOnZero = N2;
17089     SDValue Count = N3;
17090     // If the condition is NE instead of E, swap the operands.
17091     if (CC == ISD::SETNE)
17092       std::swap(ValueOnZero, Count);
17093     // Check if the value on zero is a constant equal to the bits in the type.
17094     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17095       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17096         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17097         // legal, combine to just cttz.
17098         if ((Count.getOpcode() == ISD::CTTZ ||
17099              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17100             N0 == Count.getOperand(0) &&
17101             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17102           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17103         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17104         // legal, combine to just ctlz.
17105         if ((Count.getOpcode() == ISD::CTLZ ||
17106              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17107             N0 == Count.getOperand(0) &&
17108             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17109           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17110       }
17111     }
17112   }
17113
17114   return SDValue();
17115 }
17116
17117 /// This is a stub for TargetLowering::SimplifySetCC.
17118 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17119                                    ISD::CondCode Cond, const SDLoc &DL,
17120                                    bool foldBooleans) {
17121   TargetLowering::DAGCombinerInfo
17122     DagCombineInfo(DAG, Level, false, this);
17123   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17124 }
17125
17126 /// Given an ISD::SDIV node expressing a divide by constant, return
17127 /// a DAG expression to select that will generate the same value by multiplying
17128 /// by a magic number.
17129 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17130 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17131   // when optimising for minimum size, we don't want to expand a div to a mul
17132   // and a shift.
17133   if (DAG.getMachineFunction().getFunction().optForMinSize())
17134     return SDValue();
17135
17136   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17137   if (!C)
17138     return SDValue();
17139
17140   // Avoid division by zero.
17141   if (C->isNullValue())
17142     return SDValue();
17143
17144   std::vector<SDNode *> Built;
17145   SDValue S =
17146       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17147
17148   for (SDNode *N : Built)
17149     AddToWorklist(N);
17150   return S;
17151 }
17152
17153 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17154 /// DAG expression that will generate the same value by right shifting.
17155 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17156   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17157   if (!C)
17158     return SDValue();
17159
17160   // Avoid division by zero.
17161   if (C->isNullValue())
17162     return SDValue();
17163
17164   std::vector<SDNode *> Built;
17165   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17166
17167   for (SDNode *N : Built)
17168     AddToWorklist(N);
17169   return S;
17170 }
17171
17172 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17173 /// expression that will generate the same value by multiplying by a magic
17174 /// number.
17175 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17176 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17177   // when optimising for minimum size, we don't want to expand a div to a mul
17178   // and a shift.
17179   if (DAG.getMachineFunction().getFunction().optForMinSize())
17180     return SDValue();
17181
17182   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17183   if (!C)
17184     return SDValue();
17185
17186   // Avoid division by zero.
17187   if (C->isNullValue())
17188     return SDValue();
17189
17190   std::vector<SDNode *> Built;
17191   SDValue S =
17192       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17193
17194   for (SDNode *N : Built)
17195     AddToWorklist(N);
17196   return S;
17197 }
17198
17199 /// Determines the LogBase2 value for a non-null input value using the
17200 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17201 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17202   EVT VT = V.getValueType();
17203   unsigned EltBits = VT.getScalarSizeInBits();
17204   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17205   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17206   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17207   return LogBase2;
17208 }
17209
17210 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17211 /// For the reciprocal, we need to find the zero of the function:
17212 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
17213 ///     =>
17214 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17215 ///     does not require additional intermediate precision]
17216 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17217   if (Level >= AfterLegalizeDAG)
17218     return SDValue();
17219
17220   // TODO: Handle half and/or extended types?
17221   EVT VT = Op.getValueType();
17222   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17223     return SDValue();
17224
17225   // If estimates are explicitly disabled for this function, we're done.
17226   MachineFunction &MF = DAG.getMachineFunction();
17227   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17228   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17229     return SDValue();
17230
17231   // Estimates may be explicitly enabled for this type with a custom number of
17232   // refinement steps.
17233   int Iterations = TLI.getDivRefinementSteps(VT, MF);
17234   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17235     AddToWorklist(Est.getNode());
17236
17237     if (Iterations) {
17238       EVT VT = Op.getValueType();
17239       SDLoc DL(Op);
17240       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17241
17242       // Newton iterations: Est = Est + Est (1 - Arg * Est)
17243       for (int i = 0; i < Iterations; ++i) {
17244         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17245         AddToWorklist(NewEst.getNode());
17246
17247         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17248         AddToWorklist(NewEst.getNode());
17249
17250         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17251         AddToWorklist(NewEst.getNode());
17252
17253         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17254         AddToWorklist(Est.getNode());
17255       }
17256     }
17257     return Est;
17258   }
17259
17260   return SDValue();
17261 }
17262
17263 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17264 /// For the reciprocal sqrt, we need to find the zero of the function:
17265 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17266 ///     =>
17267 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17268 /// As a result, we precompute A/2 prior to the iteration loop.
17269 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17270                                          unsigned Iterations,
17271                                          SDNodeFlags Flags, bool Reciprocal) {
17272   EVT VT = Arg.getValueType();
17273   SDLoc DL(Arg);
17274   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17275
17276   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17277   // this entire sequence requires only one FP constant.
17278   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17279   AddToWorklist(HalfArg.getNode());
17280
17281   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17282   AddToWorklist(HalfArg.getNode());
17283
17284   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17285   for (unsigned i = 0; i < Iterations; ++i) {
17286     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17287     AddToWorklist(NewEst.getNode());
17288
17289     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17290     AddToWorklist(NewEst.getNode());
17291
17292     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17293     AddToWorklist(NewEst.getNode());
17294
17295     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17296     AddToWorklist(Est.getNode());
17297   }
17298
17299   // If non-reciprocal square root is requested, multiply the result by Arg.
17300   if (!Reciprocal) {
17301     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17302     AddToWorklist(Est.getNode());
17303   }
17304
17305   return Est;
17306 }
17307
17308 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17309 /// For the reciprocal sqrt, we need to find the zero of the function:
17310 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17311 ///     =>
17312 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17313 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17314                                          unsigned Iterations,
17315                                          SDNodeFlags Flags, bool Reciprocal) {
17316   EVT VT = Arg.getValueType();
17317   SDLoc DL(Arg);
17318   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17319   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17320
17321   // This routine must enter the loop below to work correctly
17322   // when (Reciprocal == false).
17323   assert(Iterations > 0);
17324
17325   // Newton iterations for reciprocal square root:
17326   // E = (E * -0.5) * ((A * E) * E + -3.0)
17327   for (unsigned i = 0; i < Iterations; ++i) {
17328     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17329     AddToWorklist(AE.getNode());
17330
17331     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17332     AddToWorklist(AEE.getNode());
17333
17334     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17335     AddToWorklist(RHS.getNode());
17336
17337     // When calculating a square root at the last iteration build:
17338     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17339     // (notice a common subexpression)
17340     SDValue LHS;
17341     if (Reciprocal || (i + 1) < Iterations) {
17342       // RSQRT: LHS = (E * -0.5)
17343       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17344     } else {
17345       // SQRT: LHS = (A * E) * -0.5
17346       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17347     }
17348     AddToWorklist(LHS.getNode());
17349
17350     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17351     AddToWorklist(Est.getNode());
17352   }
17353
17354   return Est;
17355 }
17356
17357 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17358 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17359 /// Op can be zero.
17360 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17361                                            bool Reciprocal) {
17362   if (Level >= AfterLegalizeDAG)
17363     return SDValue();
17364
17365   // TODO: Handle half and/or extended types?
17366   EVT VT = Op.getValueType();
17367   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17368     return SDValue();
17369
17370   // If estimates are explicitly disabled for this function, we're done.
17371   MachineFunction &MF = DAG.getMachineFunction();
17372   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17373   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17374     return SDValue();
17375
17376   // Estimates may be explicitly enabled for this type with a custom number of
17377   // refinement steps.
17378   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17379
17380   bool UseOneConstNR = false;
17381   if (SDValue Est =
17382       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17383                           Reciprocal)) {
17384     AddToWorklist(Est.getNode());
17385
17386     if (Iterations) {
17387       Est = UseOneConstNR
17388             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17389             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17390
17391       if (!Reciprocal) {
17392         // Unfortunately, Est is now NaN if the input was exactly 0.0.
17393         // Select out this case and force the answer to 0.0.
17394         EVT VT = Op.getValueType();
17395         SDLoc DL(Op);
17396
17397         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17398         EVT CCVT = getSetCCResultType(VT);
17399         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17400         AddToWorklist(ZeroCmp.getNode());
17401
17402         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
17403                           ZeroCmp, FPZero, Est);
17404         AddToWorklist(Est.getNode());
17405       }
17406     }
17407     return Est;
17408   }
17409
17410   return SDValue();
17411 }
17412
17413 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17414   return buildSqrtEstimateImpl(Op, Flags, true);
17415 }
17416
17417 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17418   return buildSqrtEstimateImpl(Op, Flags, false);
17419 }
17420
17421 /// Return true if base is a frame index, which is known not to alias with
17422 /// anything but itself.  Provides base object and offset as results.
17423 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
17424                            const GlobalValue *&GV, const void *&CV) {
17425   // Assume it is a primitive operation.
17426   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
17427
17428   // If it's an adding a simple constant then integrate the offset.
17429   if (Base.getOpcode() == ISD::ADD) {
17430     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
17431       Base = Base.getOperand(0);
17432       Offset += C->getSExtValue();
17433     }
17434   }
17435
17436   // Return the underlying GlobalValue, and update the Offset.  Return false
17437   // for GlobalAddressSDNode since the same GlobalAddress may be represented
17438   // by multiple nodes with different offsets.
17439   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
17440     GV = G->getGlobal();
17441     Offset += G->getOffset();
17442     return false;
17443   }
17444
17445   // Return the underlying Constant value, and update the Offset.  Return false
17446   // for ConstantSDNodes since the same constant pool entry may be represented
17447   // by multiple nodes with different offsets.
17448   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
17449     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
17450                                          : (const void *)C->getConstVal();
17451     Offset += C->getOffset();
17452     return false;
17453   }
17454   // If it's any of the following then it can't alias with anything but itself.
17455   return isa<FrameIndexSDNode>(Base);
17456 }
17457
17458 /// Return true if there is any possibility that the two addresses overlap.
17459 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17460   // If they are the same then they must be aliases.
17461   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17462
17463   // If they are both volatile then they cannot be reordered.
17464   if (Op0->isVolatile() && Op1->isVolatile()) return true;
17465
17466   // If one operation reads from invariant memory, and the other may store, they
17467   // cannot alias. These should really be checking the equivalent of mayWrite,
17468   // but it only matters for memory nodes other than load /store.
17469   if (Op0->isInvariant() && Op1->writeMem())
17470     return false;
17471
17472   if (Op1->isInvariant() && Op0->writeMem())
17473     return false;
17474
17475   unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
17476   unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
17477
17478   // Check for BaseIndexOffset matching.
17479   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
17480   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
17481   int64_t PtrDiff;
17482   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17483     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17484
17485   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17486   // able to calculate their relative offset if at least one arises
17487   // from an alloca. However, these allocas cannot overlap and we
17488   // can infer there is no alias.
17489   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17490     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17491       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17492       // If the base are the same frame index but the we couldn't find a
17493       // constant offset, (indices are different) be conservative.
17494       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17495                      !MFI.isFixedObjectIndex(B->getIndex())))
17496         return false;
17497     }
17498
17499   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
17500   // modified to use BaseIndexOffset.
17501
17502   // Gather base node and offset information.
17503   SDValue Base0, Base1;
17504   int64_t Offset0, Offset1;
17505   const GlobalValue *GV0, *GV1;
17506   const void *CV0, *CV1;
17507   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
17508                                       Base0, Offset0, GV0, CV0);
17509   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
17510                                       Base1, Offset1, GV1, CV1);
17511
17512   // If they have the same base address, then check to see if they overlap.
17513   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
17514     return !((Offset0 + NumBytes0) <= Offset1 ||
17515              (Offset1 + NumBytes1) <= Offset0);
17516
17517   // It is possible for different frame indices to alias each other, mostly
17518   // when tail call optimization reuses return address slots for arguments.
17519   // To catch this case, look up the actual index of frame indices to compute
17520   // the real alias relationship.
17521   if (IsFrameIndex0 && IsFrameIndex1) {
17522     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17523     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
17524     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
17525     return !((Offset0 + NumBytes0) <= Offset1 ||
17526              (Offset1 + NumBytes1) <= Offset0);
17527   }
17528
17529   // Otherwise, if we know what the bases are, and they aren't identical, then
17530   // we know they cannot alias.
17531   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
17532     return false;
17533
17534   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
17535   // compared to the size and offset of the access, we may be able to prove they
17536   // do not alias. This check is conservative for now to catch cases created by
17537   // splitting vector types.
17538   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17539   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17540   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17541   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17542   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17543       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17544     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17545     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17546
17547     // There is no overlap between these relatively aligned accesses of similar
17548     // size. Return no alias.
17549     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17550         (OffAlign1 + NumBytes1) <= OffAlign0)
17551       return false;
17552   }
17553
17554   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17555                    ? CombinerGlobalAA
17556                    : DAG.getSubtarget().useAA();
17557 #ifndef NDEBUG
17558   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17559       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17560     UseAA = false;
17561 #endif
17562
17563   if (UseAA && AA &&
17564       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17565     // Use alias analysis information.
17566     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17567     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17568     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17569     AliasResult AAResult =
17570         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17571                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17572                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17573                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17574     if (AAResult == NoAlias)
17575       return false;
17576   }
17577
17578   // Otherwise we have to assume they alias.
17579   return true;
17580 }
17581
17582 /// Walk up chain skipping non-aliasing memory nodes,
17583 /// looking for aliasing nodes and adding them to the Aliases vector.
17584 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17585                                    SmallVectorImpl<SDValue> &Aliases) {
17586   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17587   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17588
17589   // Get alias information for node.
17590   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17591
17592   // Starting off.
17593   Chains.push_back(OriginalChain);
17594   unsigned Depth = 0;
17595
17596   // Look at each chain and determine if it is an alias.  If so, add it to the
17597   // aliases list.  If not, then continue up the chain looking for the next
17598   // candidate.
17599   while (!Chains.empty()) {
17600     SDValue Chain = Chains.pop_back_val();
17601
17602     // For TokenFactor nodes, look at each operand and only continue up the
17603     // chain until we reach the depth limit.
17604     //
17605     // FIXME: The depth check could be made to return the last non-aliasing
17606     // chain we found before we hit a tokenfactor rather than the original
17607     // chain.
17608     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17609       Aliases.clear();
17610       Aliases.push_back(OriginalChain);
17611       return;
17612     }
17613
17614     // Don't bother if we've been before.
17615     if (!Visited.insert(Chain.getNode()).second)
17616       continue;
17617
17618     switch (Chain.getOpcode()) {
17619     case ISD::EntryToken:
17620       // Entry token is ideal chain operand, but handled in FindBetterChain.
17621       break;
17622
17623     case ISD::LOAD:
17624     case ISD::STORE: {
17625       // Get alias information for Chain.
17626       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17627           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17628
17629       // If chain is alias then stop here.
17630       if (!(IsLoad && IsOpLoad) &&
17631           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17632         Aliases.push_back(Chain);
17633       } else {
17634         // Look further up the chain.
17635         Chains.push_back(Chain.getOperand(0));
17636         ++Depth;
17637       }
17638       break;
17639     }
17640
17641     case ISD::TokenFactor:
17642       // We have to check each of the operands of the token factor for "small"
17643       // token factors, so we queue them up.  Adding the operands to the queue
17644       // (stack) in reverse order maintains the original order and increases the
17645       // likelihood that getNode will find a matching token factor (CSE.)
17646       if (Chain.getNumOperands() > 16) {
17647         Aliases.push_back(Chain);
17648         break;
17649       }
17650       for (unsigned n = Chain.getNumOperands(); n;)
17651         Chains.push_back(Chain.getOperand(--n));
17652       ++Depth;
17653       break;
17654
17655     case ISD::CopyFromReg:
17656       // Forward past CopyFromReg.
17657       Chains.push_back(Chain.getOperand(0));
17658       ++Depth;
17659       break;
17660
17661     default:
17662       // For all other instructions we will just have to take what we can get.
17663       Aliases.push_back(Chain);
17664       break;
17665     }
17666   }
17667 }
17668
17669 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17670 /// (aliasing node.)
17671 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17672   if (OptLevel == CodeGenOpt::None)
17673     return OldChain;
17674
17675   // Ops for replacing token factor.
17676   SmallVector<SDValue, 8> Aliases;
17677
17678   // Accumulate all the aliases to this node.
17679   GatherAllAliases(N, OldChain, Aliases);
17680
17681   // If no operands then chain to entry token.
17682   if (Aliases.size() == 0)
17683     return DAG.getEntryNode();
17684
17685   // If a single operand then chain to it.  We don't need to revisit it.
17686   if (Aliases.size() == 1)
17687     return Aliases[0];
17688
17689   // Construct a custom tailored token factor.
17690   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17691 }
17692
17693 // This function tries to collect a bunch of potentially interesting
17694 // nodes to improve the chains of, all at once. This might seem
17695 // redundant, as this function gets called when visiting every store
17696 // node, so why not let the work be done on each store as it's visited?
17697 //
17698 // I believe this is mainly important because MergeConsecutiveStores
17699 // is unable to deal with merging stores of different sizes, so unless
17700 // we improve the chains of all the potential candidates up-front
17701 // before running MergeConsecutiveStores, it might only see some of
17702 // the nodes that will eventually be candidates, and then not be able
17703 // to go from a partially-merged state to the desired final
17704 // fully-merged state.
17705 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17706   if (OptLevel == CodeGenOpt::None)
17707     return false;
17708
17709   // This holds the base pointer, index, and the offset in bytes from the base
17710   // pointer.
17711   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
17712
17713   // We must have a base and an offset.
17714   if (!BasePtr.getBase().getNode())
17715     return false;
17716
17717   // Do not handle stores to undef base pointers.
17718   if (BasePtr.getBase().isUndef())
17719     return false;
17720
17721   SmallVector<StoreSDNode *, 8> ChainedStores;
17722   ChainedStores.push_back(St);
17723
17724   // Walk up the chain and look for nodes with offsets from the same
17725   // base pointer. Stop when reaching an instruction with a different kind
17726   // or instruction which has a different base pointer.
17727   StoreSDNode *Index = St;
17728   while (Index) {
17729     // If the chain has more than one use, then we can't reorder the mem ops.
17730     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17731       break;
17732
17733     if (Index->isVolatile() || Index->isIndexed())
17734       break;
17735
17736     // Find the base pointer and offset for this memory node.
17737     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17738
17739     // Check that the base pointer is the same as the original one.
17740     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17741       break;
17742
17743     // Walk up the chain to find the next store node, ignoring any
17744     // intermediate loads. Any other kind of node will halt the loop.
17745     SDNode *NextInChain = Index->getChain().getNode();
17746     while (true) {
17747       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17748         // We found a store node. Use it for the next iteration.
17749         if (STn->isVolatile() || STn->isIndexed()) {
17750           Index = nullptr;
17751           break;
17752         }
17753         ChainedStores.push_back(STn);
17754         Index = STn;
17755         break;
17756       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17757         NextInChain = Ldn->getChain().getNode();
17758         continue;
17759       } else {
17760         Index = nullptr;
17761         break;
17762       }
17763     } // end while
17764   }
17765
17766   // At this point, ChainedStores lists all of the Store nodes
17767   // reachable by iterating up through chain nodes matching the above
17768   // conditions.  For each such store identified, try to find an
17769   // earlier chain to attach the store to which won't violate the
17770   // required ordering.
17771   bool MadeChangeToSt = false;
17772   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17773
17774   for (StoreSDNode *ChainedStore : ChainedStores) {
17775     SDValue Chain = ChainedStore->getChain();
17776     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17777
17778     if (Chain != BetterChain) {
17779       if (ChainedStore == St)
17780         MadeChangeToSt = true;
17781       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17782     }
17783   }
17784
17785   // Do all replacements after finding the replacements to make to avoid making
17786   // the chains more complicated by introducing new TokenFactors.
17787   for (auto Replacement : BetterChains)
17788     replaceStoreChain(Replacement.first, Replacement.second);
17789
17790   return MadeChangeToSt;
17791 }
17792
17793 /// This is the entry point for the file.
17794 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17795                            CodeGenOpt::Level OptLevel) {
17796   /// This is the main entry point to this class.
17797   DAGCombiner(*this, AA, OptLevel).Run(Level);
17798 }