1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "dagcombine"
44 
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51 
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60 
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64 
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71 
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79 
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83 
84 //------------------------------ DAGCombiner ---------------------------------//
85 
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94 
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103 
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110 
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 32> CombinedNodes;
116 
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119 
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126 
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129 
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138 
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142 
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146 
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150 
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155 
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158 
159     /// Replaces all uses of the results of one DAG node with new values.
160     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161                       bool AddTo = true);
162 
163     /// Replaces all uses of the results of one DAG node with new values.
164     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165       return CombineTo(N, &Res, 1, AddTo);
166     }
167 
168     /// Replaces all uses of the results of one DAG node with new values.
169     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
170                       bool AddTo = true) {
171       SDValue To[] = { Res0, Res1 };
172       return CombineTo(N, To, 2, AddTo);
173     }
174 
175     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 
177   private:
178 
179     /// Check the specified integer node value to see if it can be simplified or
180     /// if things it uses can be simplified by bit propagation.
181     /// If so, return true.
182     bool SimplifyDemandedBits(SDValue Op) {
183       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184       APInt Demanded = APInt::getAllOnesValue(BitWidth);
185       return SimplifyDemandedBits(Op, Demanded);
186     }
187 
188     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
189 
190     bool CombineToPreIndexedLoadStore(SDNode *N);
191     bool CombineToPostIndexedLoadStore(SDNode *N);
192     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193     bool SliceUpLoad(SDNode *N);
194 
195     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196     ///   load.
197     ///
198     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200     /// \param EltNo index of the vector element to load.
201     /// \param OriginalLoad load that EVE came from to be replaced.
202     /// \returns EVE on success SDValue() on failure.
203     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue PromoteIntBinOp(SDValue Op);
210     SDValue PromoteIntShiftOp(SDValue Op);
211     SDValue PromoteExtend(SDValue Op);
212     bool PromoteLoad(SDValue Op);
213 
214     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216                          ISD::NodeType ExtType);
217 
218     /// Call the node-specific routine that knows how to fold each
219     /// particular type of node. If that doesn't do anything, try the
220     /// target-specific DAG combines.
221     SDValue combine(SDNode *N);
222 
223     // Visitation implementation - Implement dag node combining for different
224     // node types.  The semantics are as follows:
225     // Return Value:
226     //   SDValue.getNode() == 0 - No change was made
227     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
228     //   otherwise              - N should be replaced by the returned Operand.
229     //
230     SDValue visitTokenFactor(SDNode *N);
231     SDValue visitMERGE_VALUES(SDNode *N);
232     SDValue visitADD(SDNode *N);
233     SDValue visitSUB(SDNode *N);
234     SDValue visitADDC(SDNode *N);
235     SDValue visitSUBC(SDNode *N);
236     SDValue visitADDE(SDNode *N);
237     SDValue visitSUBE(SDNode *N);
238     SDValue visitMUL(SDNode *N);
239     SDValue useDivRem(SDNode *N);
240     SDValue visitSDIV(SDNode *N);
241     SDValue visitUDIV(SDNode *N);
242     SDValue visitREM(SDNode *N);
243     SDValue visitMULHU(SDNode *N);
244     SDValue visitMULHS(SDNode *N);
245     SDValue visitSMUL_LOHI(SDNode *N);
246     SDValue visitUMUL_LOHI(SDNode *N);
247     SDValue visitSMULO(SDNode *N);
248     SDValue visitUMULO(SDNode *N);
249     SDValue visitIMINMAX(SDNode *N);
250     SDValue visitAND(SDNode *N);
251     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitOR(SDNode *N);
253     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254     SDValue visitXOR(SDNode *N);
255     SDValue SimplifyVBinOp(SDNode *N);
256     SDValue visitSHL(SDNode *N);
257     SDValue visitSRA(SDNode *N);
258     SDValue visitSRL(SDNode *N);
259     SDValue visitRotate(SDNode *N);
260     SDValue visitBSWAP(SDNode *N);
261     SDValue visitCTLZ(SDNode *N);
262     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTTZ(SDNode *N);
264     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTPOP(SDNode *N);
266     SDValue visitSELECT(SDNode *N);
267     SDValue visitVSELECT(SDNode *N);
268     SDValue visitSELECT_CC(SDNode *N);
269     SDValue visitSETCC(SDNode *N);
270     SDValue visitSETCCE(SDNode *N);
271     SDValue visitSIGN_EXTEND(SDNode *N);
272     SDValue visitZERO_EXTEND(SDNode *N);
273     SDValue visitANY_EXTEND(SDNode *N);
274     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
275     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
276     SDValue visitTRUNCATE(SDNode *N);
277     SDValue visitBITCAST(SDNode *N);
278     SDValue visitBUILD_PAIR(SDNode *N);
279     SDValue visitFADD(SDNode *N);
280     SDValue visitFSUB(SDNode *N);
281     SDValue visitFMUL(SDNode *N);
282     SDValue visitFMA(SDNode *N);
283     SDValue visitFDIV(SDNode *N);
284     SDValue visitFREM(SDNode *N);
285     SDValue visitFSQRT(SDNode *N);
286     SDValue visitFCOPYSIGN(SDNode *N);
287     SDValue visitSINT_TO_FP(SDNode *N);
288     SDValue visitUINT_TO_FP(SDNode *N);
289     SDValue visitFP_TO_SINT(SDNode *N);
290     SDValue visitFP_TO_UINT(SDNode *N);
291     SDValue visitFP_ROUND(SDNode *N);
292     SDValue visitFP_ROUND_INREG(SDNode *N);
293     SDValue visitFP_EXTEND(SDNode *N);
294     SDValue visitFNEG(SDNode *N);
295     SDValue visitFABS(SDNode *N);
296     SDValue visitFCEIL(SDNode *N);
297     SDValue visitFTRUNC(SDNode *N);
298     SDValue visitFFLOOR(SDNode *N);
299     SDValue visitFMINNUM(SDNode *N);
300     SDValue visitFMAXNUM(SDNode *N);
301     SDValue visitBRCOND(SDNode *N);
302     SDValue visitBR_CC(SDNode *N);
303     SDValue visitLOAD(SDNode *N);
304 
305     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
306     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
307 
308     SDValue visitSTORE(SDNode *N);
309     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
310     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
311     SDValue visitBUILD_VECTOR(SDNode *N);
312     SDValue visitCONCAT_VECTORS(SDNode *N);
313     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
314     SDValue visitVECTOR_SHUFFLE(SDNode *N);
315     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
316     SDValue visitINSERT_SUBVECTOR(SDNode *N);
317     SDValue visitMLOAD(SDNode *N);
318     SDValue visitMSTORE(SDNode *N);
319     SDValue visitMGATHER(SDNode *N);
320     SDValue visitMSCATTER(SDNode *N);
321     SDValue visitFP_TO_FP16(SDNode *N);
322     SDValue visitFP16_TO_FP(SDNode *N);
323 
324     SDValue visitFADDForFMACombine(SDNode *N);
325     SDValue visitFSUBForFMACombine(SDNode *N);
326     SDValue visitFMULForFMACombine(SDNode *N);
327 
328     SDValue XformToShuffleWithZero(SDNode *N);
329     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
330 
331     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
332 
333     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
334     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
335     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
336     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
337                              SDValue N3, ISD::CondCode CC,
338                              bool NotExtCompare = false);
339     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
340                           SDLoc DL, bool foldBooleans = true);
341 
342     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
343                            SDValue &CC) const;
344     bool isOneUseSetCC(SDValue N) const;
345 
346     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
347                                          unsigned HiOp);
348     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
349     SDValue CombineExtLoad(SDNode *N);
350     SDValue combineRepeatedFPDivisors(SDNode *N);
351     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
352     SDValue BuildSDIV(SDNode *N);
353     SDValue BuildSDIVPow2(SDNode *N);
354     SDValue BuildUDIV(SDNode *N);
355     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
356     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
357     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
358                                  SDNodeFlags *Flags);
359     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
360                                  SDNodeFlags *Flags);
361     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
362                                bool DemandHighBits = true);
363     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
364     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
365                               SDValue InnerPos, SDValue InnerNeg,
366                               unsigned PosOpcode, unsigned NegOpcode,
367                               SDLoc DL);
368     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
369     SDValue ReduceLoadWidth(SDNode *N);
370     SDValue ReduceLoadOpStoreWidth(SDNode *N);
371     SDValue TransformFPLoadStorePair(SDNode *N);
372     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
373     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
374 
375     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
376 
377     /// Walk up chain skipping non-aliasing memory nodes,
378     /// looking for aliasing nodes and adding them to the Aliases vector.
379     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
380                           SmallVectorImpl<SDValue> &Aliases);
381 
382     /// Return true if there is any possibility that the two addresses overlap.
383     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
384 
385     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
386     /// chain (aliasing node.)
387     SDValue FindBetterChain(SDNode *N, SDValue Chain);
388 
389     /// Do FindBetterChain for a store and any possibly adjacent stores on
390     /// consecutive chains.
391     bool findBetterNeighborChains(StoreSDNode *St);
392 
393     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
394     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
395 
396     /// Holds a pointer to an LSBaseSDNode as well as information on where it
397     /// is located in a sequence of memory operations connected by a chain.
398     struct MemOpLink {
399       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
400       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
401       // Ptr to the mem node.
402       LSBaseSDNode *MemNode;
403       // Offset from the base ptr.
404       int64_t OffsetFromBase;
405       // What is the sequence number of this mem node.
406       // Lowest mem operand in the DAG starts at zero.
407       unsigned SequenceNum;
408     };
409 
410     /// This is a helper function for visitMUL to check the profitability
411     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
412     /// MulNode is the original multiply, AddNode is (add x, c1),
413     /// and ConstNode is c2.
414     bool isMulAddWithConstProfitable(SDNode *MulNode,
415                                      SDValue &AddNode,
416                                      SDValue &ConstNode);
417 
418     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
419     /// constant build_vector of the stored constant values in Stores.
420     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
421                                          SDLoc SL,
422                                          ArrayRef<MemOpLink> Stores,
423                                          SmallVectorImpl<SDValue> &Chains,
424                                          EVT Ty) const;
425 
426     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
427     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
428     /// the type of the loaded value to be extended.  LoadedVT returns the type
429     /// of the original loaded value.  NarrowLoad returns whether the load would
430     /// need to be narrowed in order to match.
431     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
432                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
433                           bool &NarrowLoad);
434 
435     /// This is a helper function for MergeConsecutiveStores. When the source
436     /// elements of the consecutive stores are all constants or all extracted
437     /// vector elements, try to merge them into one larger store.
438     /// \return True if a merged store was created.
439     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
440                                          EVT MemVT, unsigned NumStores,
441                                          bool IsConstantSrc, bool UseVector);
442 
443     /// This is a helper function for MergeConsecutiveStores.
444     /// Stores that may be merged are placed in StoreNodes.
445     /// Loads that may alias with those stores are placed in AliasLoadNodes.
446     void getStoreMergeAndAliasCandidates(
447         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
448         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
449 
450     /// Merge consecutive store operations into a wide store.
451     /// This optimization uses wide integers or vectors when possible.
452     /// \return True if some memory operations were changed.
453     bool MergeConsecutiveStores(StoreSDNode *N);
454 
455     /// \brief Try to transform a truncation where C is a constant:
456     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
457     ///
458     /// \p N needs to be a truncation and its first operand an AND. Other
459     /// requirements are checked by the function (e.g. that trunc is
460     /// single-use) and if missed an empty SDValue is returned.
461     SDValue distributeTruncateThroughAnd(SDNode *N);
462 
463   public:
464     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
465         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
466           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
467       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
468     }
469 
470     /// Runs the dag combiner on all nodes in the work list
471     void Run(CombineLevel AtLevel);
472 
473     SelectionDAG &getDAG() const { return DAG; }
474 
475     /// Returns a type large enough to hold any valid shift amount - before type
476     /// legalization these can be huge.
477     EVT getShiftAmountTy(EVT LHSTy) {
478       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
479       if (LHSTy.isVector())
480         return LHSTy;
481       auto &DL = DAG.getDataLayout();
482       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
483                         : TLI.getPointerTy(DL);
484     }
485 
486     /// This method returns true if we are running before type legalization or
487     /// if the specified VT is legal.
488     bool isTypeLegal(const EVT &VT) {
489       if (!LegalTypes) return true;
490       return TLI.isTypeLegal(VT);
491     }
492 
493     /// Convenience wrapper around TargetLowering::getSetCCResultType
494     EVT getSetCCResultType(EVT VT) const {
495       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
496     }
497   };
498 }
499 
500 
501 namespace {
502 /// This class is a DAGUpdateListener that removes any deleted
503 /// nodes from the worklist.
504 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
505   DAGCombiner &DC;
506 public:
507   explicit WorklistRemover(DAGCombiner &dc)
508     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
509 
510   void NodeDeleted(SDNode *N, SDNode *E) override {
511     DC.removeFromWorklist(N);
512   }
513 };
514 }
515 
516 //===----------------------------------------------------------------------===//
517 //  TargetLowering::DAGCombinerInfo implementation
518 //===----------------------------------------------------------------------===//
519 
520 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
521   ((DAGCombiner*)DC)->AddToWorklist(N);
522 }
523 
524 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
525   ((DAGCombiner*)DC)->removeFromWorklist(N);
526 }
527 
528 SDValue TargetLowering::DAGCombinerInfo::
529 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
530   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
531 }
532 
533 SDValue TargetLowering::DAGCombinerInfo::
534 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
535   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
536 }
537 
538 
539 SDValue TargetLowering::DAGCombinerInfo::
540 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
541   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
542 }
543 
544 void TargetLowering::DAGCombinerInfo::
545 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
546   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
547 }
548 
549 //===----------------------------------------------------------------------===//
550 // Helper Functions
551 //===----------------------------------------------------------------------===//
552 
553 void DAGCombiner::deleteAndRecombine(SDNode *N) {
554   removeFromWorklist(N);
555 
556   // If the operands of this node are only used by the node, they will now be
557   // dead. Make sure to re-visit them and recursively delete dead nodes.
558   for (const SDValue &Op : N->ops())
559     // For an operand generating multiple values, one of the values may
560     // become dead allowing further simplification (e.g. split index
561     // arithmetic from an indexed load).
562     if (Op->hasOneUse() || Op->getNumValues() > 1)
563       AddToWorklist(Op.getNode());
564 
565   DAG.DeleteNode(N);
566 }
567 
568 /// Return 1 if we can compute the negated form of the specified expression for
569 /// the same cost as the expression itself, or 2 if we can compute the negated
570 /// form more cheaply than the expression itself.
571 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
572                                const TargetLowering &TLI,
573                                const TargetOptions *Options,
574                                unsigned Depth = 0) {
575   // fneg is removable even if it has multiple uses.
576   if (Op.getOpcode() == ISD::FNEG) return 2;
577 
578   // Don't allow anything with multiple uses.
579   if (!Op.hasOneUse()) return 0;
580 
581   // Don't recurse exponentially.
582   if (Depth > 6) return 0;
583 
584   switch (Op.getOpcode()) {
585   default: return false;
586   case ISD::ConstantFP:
587     // Don't invert constant FP values after legalize.  The negated constant
588     // isn't necessarily legal.
589     return LegalOperations ? 0 : 1;
590   case ISD::FADD:
591     // FIXME: determine better conditions for this xform.
592     if (!Options->UnsafeFPMath) return 0;
593 
594     // After operation legalization, it might not be legal to create new FSUBs.
595     if (LegalOperations &&
596         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
597       return 0;
598 
599     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
600     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
601                                     Options, Depth + 1))
602       return V;
603     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
604     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
605                               Depth + 1);
606   case ISD::FSUB:
607     // We can't turn -(A-B) into B-A when we honor signed zeros.
608     if (!Options->UnsafeFPMath) return 0;
609 
610     // fold (fneg (fsub A, B)) -> (fsub B, A)
611     return 1;
612 
613   case ISD::FMUL:
614   case ISD::FDIV:
615     if (Options->HonorSignDependentRoundingFPMath()) return 0;
616 
617     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
618     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
619                                     Options, Depth + 1))
620       return V;
621 
622     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
623                               Depth + 1);
624 
625   case ISD::FP_EXTEND:
626   case ISD::FP_ROUND:
627   case ISD::FSIN:
628     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
629                               Depth + 1);
630   }
631 }
632 
633 /// If isNegatibleForFree returns true, return the newly negated expression.
634 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
635                                     bool LegalOperations, unsigned Depth = 0) {
636   const TargetOptions &Options = DAG.getTarget().Options;
637   // fneg is removable even if it has multiple uses.
638   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
639 
640   // Don't allow anything with multiple uses.
641   assert(Op.hasOneUse() && "Unknown reuse!");
642 
643   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
644 
645   const SDNodeFlags *Flags = Op.getNode()->getFlags();
646 
647   switch (Op.getOpcode()) {
648   default: llvm_unreachable("Unknown code");
649   case ISD::ConstantFP: {
650     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
651     V.changeSign();
652     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
653   }
654   case ISD::FADD:
655     // FIXME: determine better conditions for this xform.
656     assert(Options.UnsafeFPMath);
657 
658     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
659     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
660                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
661       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
662                          GetNegatedExpression(Op.getOperand(0), DAG,
663                                               LegalOperations, Depth+1),
664                          Op.getOperand(1), Flags);
665     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
666     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
667                        GetNegatedExpression(Op.getOperand(1), DAG,
668                                             LegalOperations, Depth+1),
669                        Op.getOperand(0), Flags);
670   case ISD::FSUB:
671     // We can't turn -(A-B) into B-A when we honor signed zeros.
672     assert(Options.UnsafeFPMath);
673 
674     // fold (fneg (fsub 0, B)) -> B
675     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
676       if (N0CFP->isZero())
677         return Op.getOperand(1);
678 
679     // fold (fneg (fsub A, B)) -> (fsub B, A)
680     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
681                        Op.getOperand(1), Op.getOperand(0), Flags);
682 
683   case ISD::FMUL:
684   case ISD::FDIV:
685     assert(!Options.HonorSignDependentRoundingFPMath());
686 
687     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
688     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
689                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
690       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
691                          GetNegatedExpression(Op.getOperand(0), DAG,
692                                               LegalOperations, Depth+1),
693                          Op.getOperand(1), Flags);
694 
695     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
696     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
697                        Op.getOperand(0),
698                        GetNegatedExpression(Op.getOperand(1), DAG,
699                                             LegalOperations, Depth+1), Flags);
700 
701   case ISD::FP_EXTEND:
702   case ISD::FSIN:
703     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
704                        GetNegatedExpression(Op.getOperand(0), DAG,
705                                             LegalOperations, Depth+1));
706   case ISD::FP_ROUND:
707       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
708                          GetNegatedExpression(Op.getOperand(0), DAG,
709                                               LegalOperations, Depth+1),
710                          Op.getOperand(1));
711   }
712 }
713 
714 // Return true if this node is a setcc, or is a select_cc
715 // that selects between the target values used for true and false, making it
716 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
717 // the appropriate nodes based on the type of node we are checking. This
718 // simplifies life a bit for the callers.
719 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
720                                     SDValue &CC) const {
721   if (N.getOpcode() == ISD::SETCC) {
722     LHS = N.getOperand(0);
723     RHS = N.getOperand(1);
724     CC  = N.getOperand(2);
725     return true;
726   }
727 
728   if (N.getOpcode() != ISD::SELECT_CC ||
729       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
730       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
731     return false;
732 
733   if (TLI.getBooleanContents(N.getValueType()) ==
734       TargetLowering::UndefinedBooleanContent)
735     return false;
736 
737   LHS = N.getOperand(0);
738   RHS = N.getOperand(1);
739   CC  = N.getOperand(4);
740   return true;
741 }
742 
743 /// Return true if this is a SetCC-equivalent operation with only one use.
744 /// If this is true, it allows the users to invert the operation for free when
745 /// it is profitable to do so.
746 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
747   SDValue N0, N1, N2;
748   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
749     return true;
750   return false;
751 }
752 
753 /// Returns true if N is a BUILD_VECTOR node whose
754 /// elements are all the same constant or undefined.
755 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
756   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
757   if (!C)
758     return false;
759 
760   APInt SplatUndef;
761   unsigned SplatBitSize;
762   bool HasAnyUndefs;
763   EVT EltVT = N->getValueType(0).getVectorElementType();
764   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
765                              HasAnyUndefs) &&
766           EltVT.getSizeInBits() >= SplatBitSize);
767 }
768 
769 // \brief Returns the SDNode if it is a constant float BuildVector
770 // or constant float.
771 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
772   if (isa<ConstantFPSDNode>(N))
773     return N.getNode();
774   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
775     return N.getNode();
776   return nullptr;
777 }
778 
779 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
780 // int.
781 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
782   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
783     return CN;
784 
785   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
786     BitVector UndefElements;
787     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
788 
789     // BuildVectors can truncate their operands. Ignore that case here.
790     // FIXME: We blindly ignore splats which include undef which is overly
791     // pessimistic.
792     if (CN && UndefElements.none() &&
793         CN->getValueType(0) == N.getValueType().getScalarType())
794       return CN;
795   }
796 
797   return nullptr;
798 }
799 
800 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
801 // float.
802 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
803   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
804     return CN;
805 
806   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
807     BitVector UndefElements;
808     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
809 
810     if (CN && UndefElements.none())
811       return CN;
812   }
813 
814   return nullptr;
815 }
816 
817 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
818                                     SDValue N0, SDValue N1) {
819   EVT VT = N0.getValueType();
820   if (N0.getOpcode() == Opc) {
821     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
822       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
823         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
824         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
825           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
826         return SDValue();
827       }
828       if (N0.hasOneUse()) {
829         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
830         // use
831         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
832         if (!OpNode.getNode())
833           return SDValue();
834         AddToWorklist(OpNode.getNode());
835         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
836       }
837     }
838   }
839 
840   if (N1.getOpcode() == Opc) {
841     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
842       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
843         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
844         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
845           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
846         return SDValue();
847       }
848       if (N1.hasOneUse()) {
849         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
850         // use
851         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
852         if (!OpNode.getNode())
853           return SDValue();
854         AddToWorklist(OpNode.getNode());
855         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
856       }
857     }
858   }
859 
860   return SDValue();
861 }
862 
863 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
864                                bool AddTo) {
865   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
866   ++NodesCombined;
867   DEBUG(dbgs() << "\nReplacing.1 ";
868         N->dump(&DAG);
869         dbgs() << "\nWith: ";
870         To[0].getNode()->dump(&DAG);
871         dbgs() << " and " << NumTo-1 << " other values\n");
872   for (unsigned i = 0, e = NumTo; i != e; ++i)
873     assert((!To[i].getNode() ||
874             N->getValueType(i) == To[i].getValueType()) &&
875            "Cannot combine value to value of different type!");
876 
877   WorklistRemover DeadNodes(*this);
878   DAG.ReplaceAllUsesWith(N, To);
879   if (AddTo) {
880     // Push the new nodes and any users onto the worklist
881     for (unsigned i = 0, e = NumTo; i != e; ++i) {
882       if (To[i].getNode()) {
883         AddToWorklist(To[i].getNode());
884         AddUsersToWorklist(To[i].getNode());
885       }
886     }
887   }
888 
889   // Finally, if the node is now dead, remove it from the graph.  The node
890   // may not be dead if the replacement process recursively simplified to
891   // something else needing this node.
892   if (N->use_empty())
893     deleteAndRecombine(N);
894   return SDValue(N, 0);
895 }
896 
897 void DAGCombiner::
898 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
899   // Replace all uses.  If any nodes become isomorphic to other nodes and
900   // are deleted, make sure to remove them from our worklist.
901   WorklistRemover DeadNodes(*this);
902   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
903 
904   // Push the new node and any (possibly new) users onto the worklist.
905   AddToWorklist(TLO.New.getNode());
906   AddUsersToWorklist(TLO.New.getNode());
907 
908   // Finally, if the node is now dead, remove it from the graph.  The node
909   // may not be dead if the replacement process recursively simplified to
910   // something else needing this node.
911   if (TLO.Old.getNode()->use_empty())
912     deleteAndRecombine(TLO.Old.getNode());
913 }
914 
915 /// Check the specified integer node value to see if it can be simplified or if
916 /// things it uses can be simplified by bit propagation. If so, return true.
917 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
918   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
919   APInt KnownZero, KnownOne;
920   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
921     return false;
922 
923   // Revisit the node.
924   AddToWorklist(Op.getNode());
925 
926   // Replace the old value with the new one.
927   ++NodesCombined;
928   DEBUG(dbgs() << "\nReplacing.2 ";
929         TLO.Old.getNode()->dump(&DAG);
930         dbgs() << "\nWith: ";
931         TLO.New.getNode()->dump(&DAG);
932         dbgs() << '\n');
933 
934   CommitTargetLoweringOpt(TLO);
935   return true;
936 }
937 
938 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
939   SDLoc dl(Load);
940   EVT VT = Load->getValueType(0);
941   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
942 
943   DEBUG(dbgs() << "\nReplacing.9 ";
944         Load->dump(&DAG);
945         dbgs() << "\nWith: ";
946         Trunc.getNode()->dump(&DAG);
947         dbgs() << '\n');
948   WorklistRemover DeadNodes(*this);
949   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
950   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
951   deleteAndRecombine(Load);
952   AddToWorklist(Trunc.getNode());
953 }
954 
955 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
956   Replace = false;
957   SDLoc dl(Op);
958   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
959     EVT MemVT = LD->getMemoryVT();
960     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
961       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
962                                                        : ISD::EXTLOAD)
963       : LD->getExtensionType();
964     Replace = true;
965     return DAG.getExtLoad(ExtType, dl, PVT,
966                           LD->getChain(), LD->getBasePtr(),
967                           MemVT, LD->getMemOperand());
968   }
969 
970   unsigned Opc = Op.getOpcode();
971   switch (Opc) {
972   default: break;
973   case ISD::AssertSext:
974     return DAG.getNode(ISD::AssertSext, dl, PVT,
975                        SExtPromoteOperand(Op.getOperand(0), PVT),
976                        Op.getOperand(1));
977   case ISD::AssertZext:
978     return DAG.getNode(ISD::AssertZext, dl, PVT,
979                        ZExtPromoteOperand(Op.getOperand(0), PVT),
980                        Op.getOperand(1));
981   case ISD::Constant: {
982     unsigned ExtOpc =
983       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
984     return DAG.getNode(ExtOpc, dl, PVT, Op);
985   }
986   }
987 
988   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
989     return SDValue();
990   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
991 }
992 
993 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
994   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
995     return SDValue();
996   EVT OldVT = Op.getValueType();
997   SDLoc dl(Op);
998   bool Replace = false;
999   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1000   if (!NewOp.getNode())
1001     return SDValue();
1002   AddToWorklist(NewOp.getNode());
1003 
1004   if (Replace)
1005     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1006   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1007                      DAG.getValueType(OldVT));
1008 }
1009 
1010 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1011   EVT OldVT = Op.getValueType();
1012   SDLoc dl(Op);
1013   bool Replace = false;
1014   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1015   if (!NewOp.getNode())
1016     return SDValue();
1017   AddToWorklist(NewOp.getNode());
1018 
1019   if (Replace)
1020     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1021   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1022 }
1023 
1024 /// Promote the specified integer binary operation if the target indicates it is
1025 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1026 /// i32 since i16 instructions are longer.
1027 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1028   if (!LegalOperations)
1029     return SDValue();
1030 
1031   EVT VT = Op.getValueType();
1032   if (VT.isVector() || !VT.isInteger())
1033     return SDValue();
1034 
1035   // If operation type is 'undesirable', e.g. i16 on x86, consider
1036   // promoting it.
1037   unsigned Opc = Op.getOpcode();
1038   if (TLI.isTypeDesirableForOp(Opc, VT))
1039     return SDValue();
1040 
1041   EVT PVT = VT;
1042   // Consult target whether it is a good idea to promote this operation and
1043   // what's the right type to promote it to.
1044   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1045     assert(PVT != VT && "Don't know what type to promote to!");
1046 
1047     bool Replace0 = false;
1048     SDValue N0 = Op.getOperand(0);
1049     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1050     if (!NN0.getNode())
1051       return SDValue();
1052 
1053     bool Replace1 = false;
1054     SDValue N1 = Op.getOperand(1);
1055     SDValue NN1;
1056     if (N0 == N1)
1057       NN1 = NN0;
1058     else {
1059       NN1 = PromoteOperand(N1, PVT, Replace1);
1060       if (!NN1.getNode())
1061         return SDValue();
1062     }
1063 
1064     AddToWorklist(NN0.getNode());
1065     if (NN1.getNode())
1066       AddToWorklist(NN1.getNode());
1067 
1068     if (Replace0)
1069       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1070     if (Replace1)
1071       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1072 
1073     DEBUG(dbgs() << "\nPromoting ";
1074           Op.getNode()->dump(&DAG));
1075     SDLoc dl(Op);
1076     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1078   }
1079   return SDValue();
1080 }
1081 
1082 /// Promote the specified integer shift operation if the target indicates it is
1083 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1084 /// i32 since i16 instructions are longer.
1085 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1086   if (!LegalOperations)
1087     return SDValue();
1088 
1089   EVT VT = Op.getValueType();
1090   if (VT.isVector() || !VT.isInteger())
1091     return SDValue();
1092 
1093   // If operation type is 'undesirable', e.g. i16 on x86, consider
1094   // promoting it.
1095   unsigned Opc = Op.getOpcode();
1096   if (TLI.isTypeDesirableForOp(Opc, VT))
1097     return SDValue();
1098 
1099   EVT PVT = VT;
1100   // Consult target whether it is a good idea to promote this operation and
1101   // what's the right type to promote it to.
1102   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1103     assert(PVT != VT && "Don't know what type to promote to!");
1104 
1105     bool Replace = false;
1106     SDValue N0 = Op.getOperand(0);
1107     if (Opc == ISD::SRA)
1108       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1109     else if (Opc == ISD::SRL)
1110       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1111     else
1112       N0 = PromoteOperand(N0, PVT, Replace);
1113     if (!N0.getNode())
1114       return SDValue();
1115 
1116     AddToWorklist(N0.getNode());
1117     if (Replace)
1118       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1119 
1120     DEBUG(dbgs() << "\nPromoting ";
1121           Op.getNode()->dump(&DAG));
1122     SDLoc dl(Op);
1123     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1124                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1125   }
1126   return SDValue();
1127 }
1128 
1129 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1130   if (!LegalOperations)
1131     return SDValue();
1132 
1133   EVT VT = Op.getValueType();
1134   if (VT.isVector() || !VT.isInteger())
1135     return SDValue();
1136 
1137   // If operation type is 'undesirable', e.g. i16 on x86, consider
1138   // promoting it.
1139   unsigned Opc = Op.getOpcode();
1140   if (TLI.isTypeDesirableForOp(Opc, VT))
1141     return SDValue();
1142 
1143   EVT PVT = VT;
1144   // Consult target whether it is a good idea to promote this operation and
1145   // what's the right type to promote it to.
1146   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147     assert(PVT != VT && "Don't know what type to promote to!");
1148     // fold (aext (aext x)) -> (aext x)
1149     // fold (aext (zext x)) -> (zext x)
1150     // fold (aext (sext x)) -> (sext x)
1151     DEBUG(dbgs() << "\nPromoting ";
1152           Op.getNode()->dump(&DAG));
1153     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1154   }
1155   return SDValue();
1156 }
1157 
1158 bool DAGCombiner::PromoteLoad(SDValue Op) {
1159   if (!LegalOperations)
1160     return false;
1161 
1162   EVT VT = Op.getValueType();
1163   if (VT.isVector() || !VT.isInteger())
1164     return false;
1165 
1166   // If operation type is 'undesirable', e.g. i16 on x86, consider
1167   // promoting it.
1168   unsigned Opc = Op.getOpcode();
1169   if (TLI.isTypeDesirableForOp(Opc, VT))
1170     return false;
1171 
1172   EVT PVT = VT;
1173   // Consult target whether it is a good idea to promote this operation and
1174   // what's the right type to promote it to.
1175   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1176     assert(PVT != VT && "Don't know what type to promote to!");
1177 
1178     SDLoc dl(Op);
1179     SDNode *N = Op.getNode();
1180     LoadSDNode *LD = cast<LoadSDNode>(N);
1181     EVT MemVT = LD->getMemoryVT();
1182     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1183       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1184                                                        : ISD::EXTLOAD)
1185       : LD->getExtensionType();
1186     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1187                                    LD->getChain(), LD->getBasePtr(),
1188                                    MemVT, LD->getMemOperand());
1189     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1190 
1191     DEBUG(dbgs() << "\nPromoting ";
1192           N->dump(&DAG);
1193           dbgs() << "\nTo: ";
1194           Result.getNode()->dump(&DAG);
1195           dbgs() << '\n');
1196     WorklistRemover DeadNodes(*this);
1197     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1198     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1199     deleteAndRecombine(N);
1200     AddToWorklist(Result.getNode());
1201     return true;
1202   }
1203   return false;
1204 }
1205 
1206 /// \brief Recursively delete a node which has no uses and any operands for
1207 /// which it is the only use.
1208 ///
1209 /// Note that this both deletes the nodes and removes them from the worklist.
1210 /// It also adds any nodes who have had a user deleted to the worklist as they
1211 /// may now have only one use and subject to other combines.
1212 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1213   if (!N->use_empty())
1214     return false;
1215 
1216   SmallSetVector<SDNode *, 16> Nodes;
1217   Nodes.insert(N);
1218   do {
1219     N = Nodes.pop_back_val();
1220     if (!N)
1221       continue;
1222 
1223     if (N->use_empty()) {
1224       for (const SDValue &ChildN : N->op_values())
1225         Nodes.insert(ChildN.getNode());
1226 
1227       removeFromWorklist(N);
1228       DAG.DeleteNode(N);
1229     } else {
1230       AddToWorklist(N);
1231     }
1232   } while (!Nodes.empty());
1233   return true;
1234 }
1235 
1236 //===----------------------------------------------------------------------===//
1237 //  Main DAG Combiner implementation
1238 //===----------------------------------------------------------------------===//
1239 
1240 void DAGCombiner::Run(CombineLevel AtLevel) {
1241   // set the instance variables, so that the various visit routines may use it.
1242   Level = AtLevel;
1243   LegalOperations = Level >= AfterLegalizeVectorOps;
1244   LegalTypes = Level >= AfterLegalizeTypes;
1245 
1246   // Add all the dag nodes to the worklist.
1247   for (SDNode &Node : DAG.allnodes())
1248     AddToWorklist(&Node);
1249 
1250   // Create a dummy node (which is not added to allnodes), that adds a reference
1251   // to the root node, preventing it from being deleted, and tracking any
1252   // changes of the root.
1253   HandleSDNode Dummy(DAG.getRoot());
1254 
1255   // while the worklist isn't empty, find a node and
1256   // try and combine it.
1257   while (!WorklistMap.empty()) {
1258     SDNode *N;
1259     // The Worklist holds the SDNodes in order, but it may contain null entries.
1260     do {
1261       N = Worklist.pop_back_val();
1262     } while (!N);
1263 
1264     bool GoodWorklistEntry = WorklistMap.erase(N);
1265     (void)GoodWorklistEntry;
1266     assert(GoodWorklistEntry &&
1267            "Found a worklist entry without a corresponding map entry!");
1268 
1269     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1270     // N is deleted from the DAG, since they too may now be dead or may have a
1271     // reduced number of uses, allowing other xforms.
1272     if (recursivelyDeleteUnusedNodes(N))
1273       continue;
1274 
1275     WorklistRemover DeadNodes(*this);
1276 
1277     // If this combine is running after legalizing the DAG, re-legalize any
1278     // nodes pulled off the worklist.
1279     if (Level == AfterLegalizeDAG) {
1280       SmallSetVector<SDNode *, 16> UpdatedNodes;
1281       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1282 
1283       for (SDNode *LN : UpdatedNodes) {
1284         AddToWorklist(LN);
1285         AddUsersToWorklist(LN);
1286       }
1287       if (!NIsValid)
1288         continue;
1289     }
1290 
1291     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1292 
1293     // Add any operands of the new node which have not yet been combined to the
1294     // worklist as well. Because the worklist uniques things already, this
1295     // won't repeatedly process the same operand.
1296     CombinedNodes.insert(N);
1297     for (const SDValue &ChildN : N->op_values())
1298       if (!CombinedNodes.count(ChildN.getNode()))
1299         AddToWorklist(ChildN.getNode());
1300 
1301     SDValue RV = combine(N);
1302 
1303     if (!RV.getNode())
1304       continue;
1305 
1306     ++NodesCombined;
1307 
1308     // If we get back the same node we passed in, rather than a new node or
1309     // zero, we know that the node must have defined multiple values and
1310     // CombineTo was used.  Since CombineTo takes care of the worklist
1311     // mechanics for us, we have no work to do in this case.
1312     if (RV.getNode() == N)
1313       continue;
1314 
1315     assert(N->getOpcode() != ISD::DELETED_NODE &&
1316            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1317            "Node was deleted but visit returned new node!");
1318 
1319     DEBUG(dbgs() << " ... into: ";
1320           RV.getNode()->dump(&DAG));
1321 
1322     // Transfer debug value.
1323     DAG.TransferDbgValues(SDValue(N, 0), RV);
1324     if (N->getNumValues() == RV.getNode()->getNumValues())
1325       DAG.ReplaceAllUsesWith(N, RV.getNode());
1326     else {
1327       assert(N->getValueType(0) == RV.getValueType() &&
1328              N->getNumValues() == 1 && "Type mismatch");
1329       SDValue OpV = RV;
1330       DAG.ReplaceAllUsesWith(N, &OpV);
1331     }
1332 
1333     // Push the new node and any users onto the worklist
1334     AddToWorklist(RV.getNode());
1335     AddUsersToWorklist(RV.getNode());
1336 
1337     // Finally, if the node is now dead, remove it from the graph.  The node
1338     // may not be dead if the replacement process recursively simplified to
1339     // something else needing this node. This will also take care of adding any
1340     // operands which have lost a user to the worklist.
1341     recursivelyDeleteUnusedNodes(N);
1342   }
1343 
1344   // If the root changed (e.g. it was a dead load, update the root).
1345   DAG.setRoot(Dummy.getValue());
1346   DAG.RemoveDeadNodes();
1347 }
1348 
1349 SDValue DAGCombiner::visit(SDNode *N) {
1350   switch (N->getOpcode()) {
1351   default: break;
1352   case ISD::TokenFactor:        return visitTokenFactor(N);
1353   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1354   case ISD::ADD:                return visitADD(N);
1355   case ISD::SUB:                return visitSUB(N);
1356   case ISD::ADDC:               return visitADDC(N);
1357   case ISD::SUBC:               return visitSUBC(N);
1358   case ISD::ADDE:               return visitADDE(N);
1359   case ISD::SUBE:               return visitSUBE(N);
1360   case ISD::MUL:                return visitMUL(N);
1361   case ISD::SDIV:               return visitSDIV(N);
1362   case ISD::UDIV:               return visitUDIV(N);
1363   case ISD::SREM:
1364   case ISD::UREM:               return visitREM(N);
1365   case ISD::MULHU:              return visitMULHU(N);
1366   case ISD::MULHS:              return visitMULHS(N);
1367   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1368   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1369   case ISD::SMULO:              return visitSMULO(N);
1370   case ISD::UMULO:              return visitUMULO(N);
1371   case ISD::SMIN:
1372   case ISD::SMAX:
1373   case ISD::UMIN:
1374   case ISD::UMAX:               return visitIMINMAX(N);
1375   case ISD::AND:                return visitAND(N);
1376   case ISD::OR:                 return visitOR(N);
1377   case ISD::XOR:                return visitXOR(N);
1378   case ISD::SHL:                return visitSHL(N);
1379   case ISD::SRA:                return visitSRA(N);
1380   case ISD::SRL:                return visitSRL(N);
1381   case ISD::ROTR:
1382   case ISD::ROTL:               return visitRotate(N);
1383   case ISD::BSWAP:              return visitBSWAP(N);
1384   case ISD::CTLZ:               return visitCTLZ(N);
1385   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1386   case ISD::CTTZ:               return visitCTTZ(N);
1387   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1388   case ISD::CTPOP:              return visitCTPOP(N);
1389   case ISD::SELECT:             return visitSELECT(N);
1390   case ISD::VSELECT:            return visitVSELECT(N);
1391   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1392   case ISD::SETCC:              return visitSETCC(N);
1393   case ISD::SETCCE:             return visitSETCCE(N);
1394   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1395   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1396   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1397   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1398   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1399   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1400   case ISD::BITCAST:            return visitBITCAST(N);
1401   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1402   case ISD::FADD:               return visitFADD(N);
1403   case ISD::FSUB:               return visitFSUB(N);
1404   case ISD::FMUL:               return visitFMUL(N);
1405   case ISD::FMA:                return visitFMA(N);
1406   case ISD::FDIV:               return visitFDIV(N);
1407   case ISD::FREM:               return visitFREM(N);
1408   case ISD::FSQRT:              return visitFSQRT(N);
1409   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1410   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1411   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1412   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1413   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1414   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1415   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1416   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1417   case ISD::FNEG:               return visitFNEG(N);
1418   case ISD::FABS:               return visitFABS(N);
1419   case ISD::FFLOOR:             return visitFFLOOR(N);
1420   case ISD::FMINNUM:            return visitFMINNUM(N);
1421   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1422   case ISD::FCEIL:              return visitFCEIL(N);
1423   case ISD::FTRUNC:             return visitFTRUNC(N);
1424   case ISD::BRCOND:             return visitBRCOND(N);
1425   case ISD::BR_CC:              return visitBR_CC(N);
1426   case ISD::LOAD:               return visitLOAD(N);
1427   case ISD::STORE:              return visitSTORE(N);
1428   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1429   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1430   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1431   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1432   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1433   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1434   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1435   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1436   case ISD::MGATHER:            return visitMGATHER(N);
1437   case ISD::MLOAD:              return visitMLOAD(N);
1438   case ISD::MSCATTER:           return visitMSCATTER(N);
1439   case ISD::MSTORE:             return visitMSTORE(N);
1440   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1441   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1442   }
1443   return SDValue();
1444 }
1445 
1446 SDValue DAGCombiner::combine(SDNode *N) {
1447   SDValue RV = visit(N);
1448 
1449   // If nothing happened, try a target-specific DAG combine.
1450   if (!RV.getNode()) {
1451     assert(N->getOpcode() != ISD::DELETED_NODE &&
1452            "Node was deleted but visit returned NULL!");
1453 
1454     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1455         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1456 
1457       // Expose the DAG combiner to the target combiner impls.
1458       TargetLowering::DAGCombinerInfo
1459         DagCombineInfo(DAG, Level, false, this);
1460 
1461       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1462     }
1463   }
1464 
1465   // If nothing happened still, try promoting the operation.
1466   if (!RV.getNode()) {
1467     switch (N->getOpcode()) {
1468     default: break;
1469     case ISD::ADD:
1470     case ISD::SUB:
1471     case ISD::MUL:
1472     case ISD::AND:
1473     case ISD::OR:
1474     case ISD::XOR:
1475       RV = PromoteIntBinOp(SDValue(N, 0));
1476       break;
1477     case ISD::SHL:
1478     case ISD::SRA:
1479     case ISD::SRL:
1480       RV = PromoteIntShiftOp(SDValue(N, 0));
1481       break;
1482     case ISD::SIGN_EXTEND:
1483     case ISD::ZERO_EXTEND:
1484     case ISD::ANY_EXTEND:
1485       RV = PromoteExtend(SDValue(N, 0));
1486       break;
1487     case ISD::LOAD:
1488       if (PromoteLoad(SDValue(N, 0)))
1489         RV = SDValue(N, 0);
1490       break;
1491     }
1492   }
1493 
1494   // If N is a commutative binary node, try commuting it to enable more
1495   // sdisel CSE.
1496   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1497       N->getNumValues() == 1) {
1498     SDValue N0 = N->getOperand(0);
1499     SDValue N1 = N->getOperand(1);
1500 
1501     // Constant operands are canonicalized to RHS.
1502     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1503       SDValue Ops[] = {N1, N0};
1504       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1505                                             N->getFlags());
1506       if (CSENode)
1507         return SDValue(CSENode, 0);
1508     }
1509   }
1510 
1511   return RV;
1512 }
1513 
1514 /// Given a node, return its input chain if it has one, otherwise return a null
1515 /// sd operand.
1516 static SDValue getInputChainForNode(SDNode *N) {
1517   if (unsigned NumOps = N->getNumOperands()) {
1518     if (N->getOperand(0).getValueType() == MVT::Other)
1519       return N->getOperand(0);
1520     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1521       return N->getOperand(NumOps-1);
1522     for (unsigned i = 1; i < NumOps-1; ++i)
1523       if (N->getOperand(i).getValueType() == MVT::Other)
1524         return N->getOperand(i);
1525   }
1526   return SDValue();
1527 }
1528 
1529 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1530   // If N has two operands, where one has an input chain equal to the other,
1531   // the 'other' chain is redundant.
1532   if (N->getNumOperands() == 2) {
1533     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1534       return N->getOperand(0);
1535     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1536       return N->getOperand(1);
1537   }
1538 
1539   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1540   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1541   SmallPtrSet<SDNode*, 16> SeenOps;
1542   bool Changed = false;             // If we should replace this token factor.
1543 
1544   // Start out with this token factor.
1545   TFs.push_back(N);
1546 
1547   // Iterate through token factors.  The TFs grows when new token factors are
1548   // encountered.
1549   for (unsigned i = 0; i < TFs.size(); ++i) {
1550     SDNode *TF = TFs[i];
1551 
1552     // Check each of the operands.
1553     for (const SDValue &Op : TF->op_values()) {
1554 
1555       switch (Op.getOpcode()) {
1556       case ISD::EntryToken:
1557         // Entry tokens don't need to be added to the list. They are
1558         // redundant.
1559         Changed = true;
1560         break;
1561 
1562       case ISD::TokenFactor:
1563         if (Op.hasOneUse() &&
1564             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1565           // Queue up for processing.
1566           TFs.push_back(Op.getNode());
1567           // Clean up in case the token factor is removed.
1568           AddToWorklist(Op.getNode());
1569           Changed = true;
1570           break;
1571         }
1572         // Fall thru
1573 
1574       default:
1575         // Only add if it isn't already in the list.
1576         if (SeenOps.insert(Op.getNode()).second)
1577           Ops.push_back(Op);
1578         else
1579           Changed = true;
1580         break;
1581       }
1582     }
1583   }
1584 
1585   SDValue Result;
1586 
1587   // If we've changed things around then replace token factor.
1588   if (Changed) {
1589     if (Ops.empty()) {
1590       // The entry token is the only possible outcome.
1591       Result = DAG.getEntryNode();
1592     } else {
1593       // New and improved token factor.
1594       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1595     }
1596 
1597     // Add users to worklist if AA is enabled, since it may introduce
1598     // a lot of new chained token factors while removing memory deps.
1599     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1600       : DAG.getSubtarget().useAA();
1601     return CombineTo(N, Result, UseAA /*add to worklist*/);
1602   }
1603 
1604   return Result;
1605 }
1606 
1607 /// MERGE_VALUES can always be eliminated.
1608 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1609   WorklistRemover DeadNodes(*this);
1610   // Replacing results may cause a different MERGE_VALUES to suddenly
1611   // be CSE'd with N, and carry its uses with it. Iterate until no
1612   // uses remain, to ensure that the node can be safely deleted.
1613   // First add the users of this node to the work list so that they
1614   // can be tried again once they have new operands.
1615   AddUsersToWorklist(N);
1616   do {
1617     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1618       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1619   } while (!N->use_empty());
1620   deleteAndRecombine(N);
1621   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1622 }
1623 
1624 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1625 /// ContantSDNode pointer else nullptr.
1626 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1627   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1628   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1629 }
1630 
1631 SDValue DAGCombiner::visitADD(SDNode *N) {
1632   SDValue N0 = N->getOperand(0);
1633   SDValue N1 = N->getOperand(1);
1634   EVT VT = N0.getValueType();
1635 
1636   // fold vector ops
1637   if (VT.isVector()) {
1638     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1639       return FoldedVOp;
1640 
1641     // fold (add x, 0) -> x, vector edition
1642     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1643       return N0;
1644     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1645       return N1;
1646   }
1647 
1648   // fold (add x, undef) -> undef
1649   if (N0.getOpcode() == ISD::UNDEF)
1650     return N0;
1651   if (N1.getOpcode() == ISD::UNDEF)
1652     return N1;
1653   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1654     // canonicalize constant to RHS
1655     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1656       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1657     // fold (add c1, c2) -> c1+c2
1658     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1659                                       N0.getNode(), N1.getNode());
1660   }
1661   // fold (add x, 0) -> x
1662   if (isNullConstant(N1))
1663     return N0;
1664   // fold ((c1-A)+c2) -> (c1+c2)-A
1665   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1666     if (N0.getOpcode() == ISD::SUB)
1667       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1668         SDLoc DL(N);
1669         return DAG.getNode(ISD::SUB, DL, VT,
1670                            DAG.getConstant(N1C->getAPIntValue()+
1671                                            N0C->getAPIntValue(), DL, VT),
1672                            N0.getOperand(1));
1673       }
1674   }
1675   // reassociate add
1676   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1677     return RADD;
1678   // fold ((0-A) + B) -> B-A
1679   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1680     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1681   // fold (A + (0-B)) -> A-B
1682   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1683     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1684   // fold (A+(B-A)) -> B
1685   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1686     return N1.getOperand(0);
1687   // fold ((B-A)+A) -> B
1688   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1689     return N0.getOperand(0);
1690   // fold (A+(B-(A+C))) to (B-C)
1691   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1692       N0 == N1.getOperand(1).getOperand(0))
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1694                        N1.getOperand(1).getOperand(1));
1695   // fold (A+(B-(C+A))) to (B-C)
1696   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1697       N0 == N1.getOperand(1).getOperand(1))
1698     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1699                        N1.getOperand(1).getOperand(0));
1700   // fold (A+((B-A)+or-C)) to (B+or-C)
1701   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1702       N1.getOperand(0).getOpcode() == ISD::SUB &&
1703       N0 == N1.getOperand(0).getOperand(1))
1704     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1705                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1706 
1707   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1708   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1709     SDValue N00 = N0.getOperand(0);
1710     SDValue N01 = N0.getOperand(1);
1711     SDValue N10 = N1.getOperand(0);
1712     SDValue N11 = N1.getOperand(1);
1713 
1714     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1715       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1716                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1717                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1718   }
1719 
1720   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1721     return SDValue(N, 0);
1722 
1723   // fold (a+b) -> (a|b) iff a and b share no bits.
1724   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) &&
1725       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1726     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1727 
1728   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1729   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1730       isNullConstant(N1.getOperand(0).getOperand(0)))
1731     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1732                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1733                                    N1.getOperand(0).getOperand(1),
1734                                    N1.getOperand(1)));
1735   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1736       isNullConstant(N0.getOperand(0).getOperand(0)))
1737     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1738                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1739                                    N0.getOperand(0).getOperand(1),
1740                                    N0.getOperand(1)));
1741 
1742   if (N1.getOpcode() == ISD::AND) {
1743     SDValue AndOp0 = N1.getOperand(0);
1744     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1745     unsigned DestBits = VT.getScalarType().getSizeInBits();
1746 
1747     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1748     // and similar xforms where the inner op is either ~0 or 0.
1749     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1750       SDLoc DL(N);
1751       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1752     }
1753   }
1754 
1755   // add (sext i1), X -> sub X, (zext i1)
1756   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1757       N0.getOperand(0).getValueType() == MVT::i1 &&
1758       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1759     SDLoc DL(N);
1760     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1761     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1762   }
1763 
1764   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1765   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1766     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1767     if (TN->getVT() == MVT::i1) {
1768       SDLoc DL(N);
1769       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1770                                  DAG.getConstant(1, DL, VT));
1771       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1772     }
1773   }
1774 
1775   return SDValue();
1776 }
1777 
1778 SDValue DAGCombiner::visitADDC(SDNode *N) {
1779   SDValue N0 = N->getOperand(0);
1780   SDValue N1 = N->getOperand(1);
1781   EVT VT = N0.getValueType();
1782 
1783   // If the flag result is dead, turn this into an ADD.
1784   if (!N->hasAnyUseOfValue(1))
1785     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1786                      DAG.getNode(ISD::CARRY_FALSE,
1787                                  SDLoc(N), MVT::Glue));
1788 
1789   // canonicalize constant to RHS.
1790   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1791   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1792   if (N0C && !N1C)
1793     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1794 
1795   // fold (addc x, 0) -> x + no carry out
1796   if (isNullConstant(N1))
1797     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1798                                         SDLoc(N), MVT::Glue));
1799 
1800   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1801   APInt LHSZero, LHSOne;
1802   APInt RHSZero, RHSOne;
1803   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1804 
1805   if (LHSZero.getBoolValue()) {
1806     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1807 
1808     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1809     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1810     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1811       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1812                        DAG.getNode(ISD::CARRY_FALSE,
1813                                    SDLoc(N), MVT::Glue));
1814   }
1815 
1816   return SDValue();
1817 }
1818 
1819 SDValue DAGCombiner::visitADDE(SDNode *N) {
1820   SDValue N0 = N->getOperand(0);
1821   SDValue N1 = N->getOperand(1);
1822   SDValue CarryIn = N->getOperand(2);
1823 
1824   // canonicalize constant to RHS
1825   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1826   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1827   if (N0C && !N1C)
1828     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1829                        N1, N0, CarryIn);
1830 
1831   // fold (adde x, y, false) -> (addc x, y)
1832   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1833     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1834 
1835   return SDValue();
1836 }
1837 
1838 // Since it may not be valid to emit a fold to zero for vector initializers
1839 // check if we can before folding.
1840 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1841                              SelectionDAG &DAG,
1842                              bool LegalOperations, bool LegalTypes) {
1843   if (!VT.isVector())
1844     return DAG.getConstant(0, DL, VT);
1845   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1846     return DAG.getConstant(0, DL, VT);
1847   return SDValue();
1848 }
1849 
1850 SDValue DAGCombiner::visitSUB(SDNode *N) {
1851   SDValue N0 = N->getOperand(0);
1852   SDValue N1 = N->getOperand(1);
1853   EVT VT = N0.getValueType();
1854 
1855   // fold vector ops
1856   if (VT.isVector()) {
1857     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1858       return FoldedVOp;
1859 
1860     // fold (sub x, 0) -> x, vector edition
1861     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1862       return N0;
1863   }
1864 
1865   // fold (sub x, x) -> 0
1866   // FIXME: Refactor this and xor and other similar operations together.
1867   if (N0 == N1)
1868     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1869   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1870       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1871     // fold (sub c1, c2) -> c1-c2
1872     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT,
1873                                       N0.getNode(), N1.getNode());
1874   }
1875   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1876   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1877   // fold (sub x, c) -> (add x, -c)
1878   if (N1C) {
1879     SDLoc DL(N);
1880     return DAG.getNode(ISD::ADD, DL, VT, N0,
1881                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1882   }
1883   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1884   if (isAllOnesConstant(N0))
1885     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1886   // fold A-(A-B) -> B
1887   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1888     return N1.getOperand(1);
1889   // fold (A+B)-A -> B
1890   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1891     return N0.getOperand(1);
1892   // fold (A+B)-B -> A
1893   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1894     return N0.getOperand(0);
1895   // fold C2-(A+C1) -> (C2-C1)-A
1896   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1897     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1898   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1899     SDLoc DL(N);
1900     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1901                                    DL, VT);
1902     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1903                        N1.getOperand(0));
1904   }
1905   // fold ((A+(B+or-C))-B) -> A+or-C
1906   if (N0.getOpcode() == ISD::ADD &&
1907       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1908        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1909       N0.getOperand(1).getOperand(0) == N1)
1910     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1911                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1912   // fold ((A+(C+B))-B) -> A+C
1913   if (N0.getOpcode() == ISD::ADD &&
1914       N0.getOperand(1).getOpcode() == ISD::ADD &&
1915       N0.getOperand(1).getOperand(1) == N1)
1916     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1917                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1918   // fold ((A-(B-C))-C) -> A-B
1919   if (N0.getOpcode() == ISD::SUB &&
1920       N0.getOperand(1).getOpcode() == ISD::SUB &&
1921       N0.getOperand(1).getOperand(1) == N1)
1922     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1923                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1924 
1925   // If either operand of a sub is undef, the result is undef
1926   if (N0.getOpcode() == ISD::UNDEF)
1927     return N0;
1928   if (N1.getOpcode() == ISD::UNDEF)
1929     return N1;
1930 
1931   // If the relocation model supports it, consider symbol offsets.
1932   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1933     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1934       // fold (sub Sym, c) -> Sym-c
1935       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1936         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1937                                     GA->getOffset() -
1938                                       (uint64_t)N1C->getSExtValue());
1939       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1940       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1941         if (GA->getGlobal() == GB->getGlobal())
1942           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1943                                  SDLoc(N), VT);
1944     }
1945 
1946   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1947   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1948     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1949     if (TN->getVT() == MVT::i1) {
1950       SDLoc DL(N);
1951       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1952                                  DAG.getConstant(1, DL, VT));
1953       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1954     }
1955   }
1956 
1957   return SDValue();
1958 }
1959 
1960 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1961   SDValue N0 = N->getOperand(0);
1962   SDValue N1 = N->getOperand(1);
1963   EVT VT = N0.getValueType();
1964   SDLoc DL(N);
1965 
1966   // If the flag result is dead, turn this into an SUB.
1967   if (!N->hasAnyUseOfValue(1))
1968     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1969                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1970 
1971   // fold (subc x, x) -> 0 + no borrow
1972   if (N0 == N1)
1973     return CombineTo(N, DAG.getConstant(0, DL, VT),
1974                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1975 
1976   // fold (subc x, 0) -> x + no borrow
1977   if (isNullConstant(N1))
1978     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1979 
1980   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1981   if (isAllOnesConstant(N0))
1982     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1983                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1984 
1985   return SDValue();
1986 }
1987 
1988 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1989   SDValue N0 = N->getOperand(0);
1990   SDValue N1 = N->getOperand(1);
1991   SDValue CarryIn = N->getOperand(2);
1992 
1993   // fold (sube x, y, false) -> (subc x, y)
1994   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1995     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1996 
1997   return SDValue();
1998 }
1999 
2000 SDValue DAGCombiner::visitMUL(SDNode *N) {
2001   SDValue N0 = N->getOperand(0);
2002   SDValue N1 = N->getOperand(1);
2003   EVT VT = N0.getValueType();
2004 
2005   // fold (mul x, undef) -> 0
2006   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2007     return DAG.getConstant(0, SDLoc(N), VT);
2008 
2009   bool N0IsConst = false;
2010   bool N1IsConst = false;
2011   bool N1IsOpaqueConst = false;
2012   bool N0IsOpaqueConst = false;
2013   APInt ConstValue0, ConstValue1;
2014   // fold vector ops
2015   if (VT.isVector()) {
2016     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2017       return FoldedVOp;
2018 
2019     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2020     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2021   } else {
2022     N0IsConst = isa<ConstantSDNode>(N0);
2023     if (N0IsConst) {
2024       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2025       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2026     }
2027     N1IsConst = isa<ConstantSDNode>(N1);
2028     if (N1IsConst) {
2029       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2030       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2031     }
2032   }
2033 
2034   // fold (mul c1, c2) -> c1*c2
2035   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2036     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2037                                       N0.getNode(), N1.getNode());
2038 
2039   // canonicalize constant to RHS (vector doesn't have to splat)
2040   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2041      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2042     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2043   // fold (mul x, 0) -> 0
2044   if (N1IsConst && ConstValue1 == 0)
2045     return N1;
2046   // We require a splat of the entire scalar bit width for non-contiguous
2047   // bit patterns.
2048   bool IsFullSplat =
2049     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2050   // fold (mul x, 1) -> x
2051   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2052     return N0;
2053   // fold (mul x, -1) -> 0-x
2054   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2055     SDLoc DL(N);
2056     return DAG.getNode(ISD::SUB, DL, VT,
2057                        DAG.getConstant(0, DL, VT), N0);
2058   }
2059   // fold (mul x, (1 << c)) -> x << c
2060   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2061       IsFullSplat) {
2062     SDLoc DL(N);
2063     return DAG.getNode(ISD::SHL, DL, VT, N0,
2064                        DAG.getConstant(ConstValue1.logBase2(), DL,
2065                                        getShiftAmountTy(N0.getValueType())));
2066   }
2067   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2068   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2069       IsFullSplat) {
2070     unsigned Log2Val = (-ConstValue1).logBase2();
2071     SDLoc DL(N);
2072     // FIXME: If the input is something that is easily negated (e.g. a
2073     // single-use add), we should put the negate there.
2074     return DAG.getNode(ISD::SUB, DL, VT,
2075                        DAG.getConstant(0, DL, VT),
2076                        DAG.getNode(ISD::SHL, DL, VT, N0,
2077                             DAG.getConstant(Log2Val, DL,
2078                                       getShiftAmountTy(N0.getValueType()))));
2079   }
2080 
2081   APInt Val;
2082   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2083   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2084       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2085                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2086     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2087                              N1, N0.getOperand(1));
2088     AddToWorklist(C3.getNode());
2089     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2090                        N0.getOperand(0), C3);
2091   }
2092 
2093   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2094   // use.
2095   {
2096     SDValue Sh(nullptr,0), Y(nullptr,0);
2097     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2098     if (N0.getOpcode() == ISD::SHL &&
2099         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2100                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2101         N0.getNode()->hasOneUse()) {
2102       Sh = N0; Y = N1;
2103     } else if (N1.getOpcode() == ISD::SHL &&
2104                isa<ConstantSDNode>(N1.getOperand(1)) &&
2105                N1.getNode()->hasOneUse()) {
2106       Sh = N1; Y = N0;
2107     }
2108 
2109     if (Sh.getNode()) {
2110       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2111                                 Sh.getOperand(0), Y);
2112       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2113                          Mul, Sh.getOperand(1));
2114     }
2115   }
2116 
2117   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2118   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2119       N0.getOpcode() == ISD::ADD &&
2120       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2121       isMulAddWithConstProfitable(N, N0, N1))
2122       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2123                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2124                                      N0.getOperand(0), N1),
2125                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2126                                      N0.getOperand(1), N1));
2127 
2128   // reassociate mul
2129   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2130     return RMUL;
2131 
2132   return SDValue();
2133 }
2134 
2135 /// Return true if divmod libcall is available.
2136 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2137                                      const TargetLowering &TLI) {
2138   RTLIB::Libcall LC;
2139   switch (Node->getSimpleValueType(0).SimpleTy) {
2140   default: return false; // No libcall for vector types.
2141   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2142   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2143   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2144   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2145   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2146   }
2147 
2148   return TLI.getLibcallName(LC) != nullptr;
2149 }
2150 
2151 /// Issue divrem if both quotient and remainder are needed.
2152 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2153   if (Node->use_empty())
2154     return SDValue(); // This is a dead node, leave it alone.
2155 
2156   EVT VT = Node->getValueType(0);
2157   if (!TLI.isTypeLegal(VT))
2158     return SDValue();
2159 
2160   unsigned Opcode = Node->getOpcode();
2161   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2162 
2163   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2164   // If DIVREM is going to get expanded into a libcall,
2165   // but there is no libcall available, then don't combine.
2166   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2167       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2168     return SDValue();
2169 
2170   // If div is legal, it's better to do the normal expansion
2171   unsigned OtherOpcode = 0;
2172   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2173     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2174     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2175       return SDValue();
2176   } else {
2177     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2178     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2179       return SDValue();
2180   }
2181 
2182   SDValue Op0 = Node->getOperand(0);
2183   SDValue Op1 = Node->getOperand(1);
2184   SDValue combined;
2185   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2186          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2187     SDNode *User = *UI;
2188     if (User == Node || User->use_empty())
2189       continue;
2190     // Convert the other matching node(s), too;
2191     // otherwise, the DIVREM may get target-legalized into something
2192     // target-specific that we won't be able to recognize.
2193     unsigned UserOpc = User->getOpcode();
2194     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2195         User->getOperand(0) == Op0 &&
2196         User->getOperand(1) == Op1) {
2197       if (!combined) {
2198         if (UserOpc == OtherOpcode) {
2199           SDVTList VTs = DAG.getVTList(VT, VT);
2200           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2201         } else if (UserOpc == DivRemOpc) {
2202           combined = SDValue(User, 0);
2203         } else {
2204           assert(UserOpc == Opcode);
2205           continue;
2206         }
2207       }
2208       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2209         CombineTo(User, combined);
2210       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2211         CombineTo(User, combined.getValue(1));
2212     }
2213   }
2214   return combined;
2215 }
2216 
2217 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2218   SDValue N0 = N->getOperand(0);
2219   SDValue N1 = N->getOperand(1);
2220   EVT VT = N->getValueType(0);
2221 
2222   // fold vector ops
2223   if (VT.isVector())
2224     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2225       return FoldedVOp;
2226 
2227   SDLoc DL(N);
2228 
2229   // fold (sdiv c1, c2) -> c1/c2
2230   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2231   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2232   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2233     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2234   // fold (sdiv X, 1) -> X
2235   if (N1C && N1C->isOne())
2236     return N0;
2237   // fold (sdiv X, -1) -> 0-X
2238   if (N1C && N1C->isAllOnesValue())
2239     return DAG.getNode(ISD::SUB, DL, VT,
2240                        DAG.getConstant(0, DL, VT), N0);
2241 
2242   // If we know the sign bits of both operands are zero, strength reduce to a
2243   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2244   if (!VT.isVector()) {
2245     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2246       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2247   }
2248 
2249   // fold (sdiv X, pow2) -> simple ops after legalize
2250   // FIXME: We check for the exact bit here because the generic lowering gives
2251   // better results in that case. The target-specific lowering should learn how
2252   // to handle exact sdivs efficiently.
2253   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2254       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2255       (N1C->getAPIntValue().isPowerOf2() ||
2256        (-N1C->getAPIntValue()).isPowerOf2())) {
2257     // Target-specific implementation of sdiv x, pow2.
2258     if (SDValue Res = BuildSDIVPow2(N))
2259       return Res;
2260 
2261     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2262 
2263     // Splat the sign bit into the register
2264     SDValue SGN =
2265         DAG.getNode(ISD::SRA, DL, VT, N0,
2266                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2267                                     getShiftAmountTy(N0.getValueType())));
2268     AddToWorklist(SGN.getNode());
2269 
2270     // Add (N0 < 0) ? abs2 - 1 : 0;
2271     SDValue SRL =
2272         DAG.getNode(ISD::SRL, DL, VT, SGN,
2273                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2274                                     getShiftAmountTy(SGN.getValueType())));
2275     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2276     AddToWorklist(SRL.getNode());
2277     AddToWorklist(ADD.getNode());    // Divide by pow2
2278     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2279                   DAG.getConstant(lg2, DL,
2280                                   getShiftAmountTy(ADD.getValueType())));
2281 
2282     // If we're dividing by a positive value, we're done.  Otherwise, we must
2283     // negate the result.
2284     if (N1C->getAPIntValue().isNonNegative())
2285       return SRA;
2286 
2287     AddToWorklist(SRA.getNode());
2288     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2289   }
2290 
2291   // If integer divide is expensive and we satisfy the requirements, emit an
2292   // alternate sequence.  Targets may check function attributes for size/speed
2293   // trade-offs.
2294   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2295   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2296     if (SDValue Op = BuildSDIV(N))
2297       return Op;
2298 
2299   // sdiv, srem -> sdivrem
2300   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2301   // Otherwise, we break the simplification logic in visitREM().
2302   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2303     if (SDValue DivRem = useDivRem(N))
2304         return DivRem;
2305 
2306   // undef / X -> 0
2307   if (N0.getOpcode() == ISD::UNDEF)
2308     return DAG.getConstant(0, DL, VT);
2309   // X / undef -> undef
2310   if (N1.getOpcode() == ISD::UNDEF)
2311     return N1;
2312 
2313   return SDValue();
2314 }
2315 
2316 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2317   SDValue N0 = N->getOperand(0);
2318   SDValue N1 = N->getOperand(1);
2319   EVT VT = N->getValueType(0);
2320 
2321   // fold vector ops
2322   if (VT.isVector())
2323     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2324       return FoldedVOp;
2325 
2326   SDLoc DL(N);
2327 
2328   // fold (udiv c1, c2) -> c1/c2
2329   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2330   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2331   if (N0C && N1C)
2332     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2333                                                     N0C, N1C))
2334       return Folded;
2335   // fold (udiv x, (1 << c)) -> x >>u c
2336   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2337     return DAG.getNode(ISD::SRL, DL, VT, N0,
2338                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2339                                        getShiftAmountTy(N0.getValueType())));
2340 
2341   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2342   if (N1.getOpcode() == ISD::SHL) {
2343     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2344       if (SHC->getAPIntValue().isPowerOf2()) {
2345         EVT ADDVT = N1.getOperand(1).getValueType();
2346         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2347                                   N1.getOperand(1),
2348                                   DAG.getConstant(SHC->getAPIntValue()
2349                                                                   .logBase2(),
2350                                                   DL, ADDVT));
2351         AddToWorklist(Add.getNode());
2352         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2353       }
2354     }
2355   }
2356 
2357   // fold (udiv x, c) -> alternate
2358   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2359   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2360     if (SDValue Op = BuildUDIV(N))
2361       return Op;
2362 
2363   // sdiv, srem -> sdivrem
2364   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2365   // Otherwise, we break the simplification logic in visitREM().
2366   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2367     if (SDValue DivRem = useDivRem(N))
2368         return DivRem;
2369 
2370   // undef / X -> 0
2371   if (N0.getOpcode() == ISD::UNDEF)
2372     return DAG.getConstant(0, DL, VT);
2373   // X / undef -> undef
2374   if (N1.getOpcode() == ISD::UNDEF)
2375     return N1;
2376 
2377   return SDValue();
2378 }
2379 
2380 // handles ISD::SREM and ISD::UREM
2381 SDValue DAGCombiner::visitREM(SDNode *N) {
2382   unsigned Opcode = N->getOpcode();
2383   SDValue N0 = N->getOperand(0);
2384   SDValue N1 = N->getOperand(1);
2385   EVT VT = N->getValueType(0);
2386   bool isSigned = (Opcode == ISD::SREM);
2387   SDLoc DL(N);
2388 
2389   // fold (rem c1, c2) -> c1%c2
2390   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2391   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2392   if (N0C && N1C)
2393     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2394       return Folded;
2395 
2396   if (isSigned) {
2397     // If we know the sign bits of both operands are zero, strength reduce to a
2398     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2399     if (!VT.isVector()) {
2400       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2401         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2402     }
2403   } else {
2404     // fold (urem x, pow2) -> (and x, pow2-1)
2405     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2406         N1C->getAPIntValue().isPowerOf2()) {
2407       return DAG.getNode(ISD::AND, DL, VT, N0,
2408                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2409     }
2410     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2411     if (N1.getOpcode() == ISD::SHL) {
2412       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2413         if (SHC->getAPIntValue().isPowerOf2()) {
2414           SDValue Add =
2415             DAG.getNode(ISD::ADD, DL, VT, N1,
2416                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2417                                  VT));
2418           AddToWorklist(Add.getNode());
2419           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2420         }
2421       }
2422     }
2423   }
2424 
2425   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2426 
2427   // If X/C can be simplified by the division-by-constant logic, lower
2428   // X%C to the equivalent of X-X/C*C.
2429   // To avoid mangling nodes, this simplification requires that the combine()
2430   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2431   // against this by skipping the simplification if isIntDivCheap().  When
2432   // div is not cheap, combine will not return a DIVREM.  Regardless,
2433   // checking cheapness here makes sense since the simplification results in
2434   // fatter code.
2435   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2436     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2437     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2438     AddToWorklist(Div.getNode());
2439     SDValue OptimizedDiv = combine(Div.getNode());
2440     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2441       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2442              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2443       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2444       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2445       AddToWorklist(Mul.getNode());
2446       return Sub;
2447     }
2448   }
2449 
2450   // sdiv, srem -> sdivrem
2451   if (SDValue DivRem = useDivRem(N))
2452     return DivRem.getValue(1);
2453 
2454   // undef % X -> 0
2455   if (N0.getOpcode() == ISD::UNDEF)
2456     return DAG.getConstant(0, DL, VT);
2457   // X % undef -> undef
2458   if (N1.getOpcode() == ISD::UNDEF)
2459     return N1;
2460 
2461   return SDValue();
2462 }
2463 
2464 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2465   SDValue N0 = N->getOperand(0);
2466   SDValue N1 = N->getOperand(1);
2467   EVT VT = N->getValueType(0);
2468   SDLoc DL(N);
2469 
2470   // fold (mulhs x, 0) -> 0
2471   if (isNullConstant(N1))
2472     return N1;
2473   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2474   if (isOneConstant(N1)) {
2475     SDLoc DL(N);
2476     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2477                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2478                                        DL,
2479                                        getShiftAmountTy(N0.getValueType())));
2480   }
2481   // fold (mulhs x, undef) -> 0
2482   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2483     return DAG.getConstant(0, SDLoc(N), VT);
2484 
2485   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2486   // plus a shift.
2487   if (VT.isSimple() && !VT.isVector()) {
2488     MVT Simple = VT.getSimpleVT();
2489     unsigned SimpleSize = Simple.getSizeInBits();
2490     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2491     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2492       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2493       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2494       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2495       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2496             DAG.getConstant(SimpleSize, DL,
2497                             getShiftAmountTy(N1.getValueType())));
2498       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2499     }
2500   }
2501 
2502   return SDValue();
2503 }
2504 
2505 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2506   SDValue N0 = N->getOperand(0);
2507   SDValue N1 = N->getOperand(1);
2508   EVT VT = N->getValueType(0);
2509   SDLoc DL(N);
2510 
2511   // fold (mulhu x, 0) -> 0
2512   if (isNullConstant(N1))
2513     return N1;
2514   // fold (mulhu x, 1) -> 0
2515   if (isOneConstant(N1))
2516     return DAG.getConstant(0, DL, N0.getValueType());
2517   // fold (mulhu x, undef) -> 0
2518   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2519     return DAG.getConstant(0, DL, VT);
2520 
2521   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2522   // plus a shift.
2523   if (VT.isSimple() && !VT.isVector()) {
2524     MVT Simple = VT.getSimpleVT();
2525     unsigned SimpleSize = Simple.getSizeInBits();
2526     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2527     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2528       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2529       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2530       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2531       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2532             DAG.getConstant(SimpleSize, DL,
2533                             getShiftAmountTy(N1.getValueType())));
2534       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2535     }
2536   }
2537 
2538   return SDValue();
2539 }
2540 
2541 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2542 /// give the opcodes for the two computations that are being performed. Return
2543 /// true if a simplification was made.
2544 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2545                                                 unsigned HiOp) {
2546   // If the high half is not needed, just compute the low half.
2547   bool HiExists = N->hasAnyUseOfValue(1);
2548   if (!HiExists &&
2549       (!LegalOperations ||
2550        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2551     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2552     return CombineTo(N, Res, Res);
2553   }
2554 
2555   // If the low half is not needed, just compute the high half.
2556   bool LoExists = N->hasAnyUseOfValue(0);
2557   if (!LoExists &&
2558       (!LegalOperations ||
2559        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2560     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2561     return CombineTo(N, Res, Res);
2562   }
2563 
2564   // If both halves are used, return as it is.
2565   if (LoExists && HiExists)
2566     return SDValue();
2567 
2568   // If the two computed results can be simplified separately, separate them.
2569   if (LoExists) {
2570     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2571     AddToWorklist(Lo.getNode());
2572     SDValue LoOpt = combine(Lo.getNode());
2573     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2574         (!LegalOperations ||
2575          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2576       return CombineTo(N, LoOpt, LoOpt);
2577   }
2578 
2579   if (HiExists) {
2580     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2581     AddToWorklist(Hi.getNode());
2582     SDValue HiOpt = combine(Hi.getNode());
2583     if (HiOpt.getNode() && HiOpt != Hi &&
2584         (!LegalOperations ||
2585          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2586       return CombineTo(N, HiOpt, HiOpt);
2587   }
2588 
2589   return SDValue();
2590 }
2591 
2592 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2593   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2594     return Res;
2595 
2596   EVT VT = N->getValueType(0);
2597   SDLoc DL(N);
2598 
2599   // If the type is twice as wide is legal, transform the mulhu to a wider
2600   // multiply plus a shift.
2601   if (VT.isSimple() && !VT.isVector()) {
2602     MVT Simple = VT.getSimpleVT();
2603     unsigned SimpleSize = Simple.getSizeInBits();
2604     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2605     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2606       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2607       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2608       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2609       // Compute the high part as N1.
2610       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2611             DAG.getConstant(SimpleSize, DL,
2612                             getShiftAmountTy(Lo.getValueType())));
2613       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2614       // Compute the low part as N0.
2615       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2616       return CombineTo(N, Lo, Hi);
2617     }
2618   }
2619 
2620   return SDValue();
2621 }
2622 
2623 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2624   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2625     return Res;
2626 
2627   EVT VT = N->getValueType(0);
2628   SDLoc DL(N);
2629 
2630   // If the type is twice as wide is legal, transform the mulhu to a wider
2631   // multiply plus a shift.
2632   if (VT.isSimple() && !VT.isVector()) {
2633     MVT Simple = VT.getSimpleVT();
2634     unsigned SimpleSize = Simple.getSizeInBits();
2635     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2636     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2637       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2638       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2639       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2640       // Compute the high part as N1.
2641       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2642             DAG.getConstant(SimpleSize, DL,
2643                             getShiftAmountTy(Lo.getValueType())));
2644       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2645       // Compute the low part as N0.
2646       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2647       return CombineTo(N, Lo, Hi);
2648     }
2649   }
2650 
2651   return SDValue();
2652 }
2653 
2654 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2655   // (smulo x, 2) -> (saddo x, x)
2656   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2657     if (C2->getAPIntValue() == 2)
2658       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2659                          N->getOperand(0), N->getOperand(0));
2660 
2661   return SDValue();
2662 }
2663 
2664 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2665   // (umulo x, 2) -> (uaddo x, x)
2666   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2667     if (C2->getAPIntValue() == 2)
2668       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2669                          N->getOperand(0), N->getOperand(0));
2670 
2671   return SDValue();
2672 }
2673 
2674 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2675   SDValue N0 = N->getOperand(0);
2676   SDValue N1 = N->getOperand(1);
2677   EVT VT = N0.getValueType();
2678 
2679   // fold vector ops
2680   if (VT.isVector())
2681     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2682       return FoldedVOp;
2683 
2684   // fold (add c1, c2) -> c1+c2
2685   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2686   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2687   if (N0C && N1C)
2688     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2689 
2690   // canonicalize constant to RHS
2691   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2692      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2693     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2694 
2695   return SDValue();
2696 }
2697 
2698 /// If this is a binary operator with two operands of the same opcode, try to
2699 /// simplify it.
2700 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2701   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2702   EVT VT = N0.getValueType();
2703   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2704 
2705   // Bail early if none of these transforms apply.
2706   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2707 
2708   // For each of OP in AND/OR/XOR:
2709   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2710   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2711   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2712   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2713   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2714   //
2715   // do not sink logical op inside of a vector extend, since it may combine
2716   // into a vsetcc.
2717   EVT Op0VT = N0.getOperand(0).getValueType();
2718   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2719        N0.getOpcode() == ISD::SIGN_EXTEND ||
2720        N0.getOpcode() == ISD::BSWAP ||
2721        // Avoid infinite looping with PromoteIntBinOp.
2722        (N0.getOpcode() == ISD::ANY_EXTEND &&
2723         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2724        (N0.getOpcode() == ISD::TRUNCATE &&
2725         (!TLI.isZExtFree(VT, Op0VT) ||
2726          !TLI.isTruncateFree(Op0VT, VT)) &&
2727         TLI.isTypeLegal(Op0VT))) &&
2728       !VT.isVector() &&
2729       Op0VT == N1.getOperand(0).getValueType() &&
2730       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2731     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2732                                  N0.getOperand(0).getValueType(),
2733                                  N0.getOperand(0), N1.getOperand(0));
2734     AddToWorklist(ORNode.getNode());
2735     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2736   }
2737 
2738   // For each of OP in SHL/SRL/SRA/AND...
2739   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2740   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2741   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2742   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2743        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2744       N0.getOperand(1) == N1.getOperand(1)) {
2745     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2746                                  N0.getOperand(0).getValueType(),
2747                                  N0.getOperand(0), N1.getOperand(0));
2748     AddToWorklist(ORNode.getNode());
2749     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2750                        ORNode, N0.getOperand(1));
2751   }
2752 
2753   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2754   // Only perform this optimization after type legalization and before
2755   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2756   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2757   // we don't want to undo this promotion.
2758   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2759   // on scalars.
2760   if ((N0.getOpcode() == ISD::BITCAST ||
2761        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2762       Level == AfterLegalizeTypes) {
2763     SDValue In0 = N0.getOperand(0);
2764     SDValue In1 = N1.getOperand(0);
2765     EVT In0Ty = In0.getValueType();
2766     EVT In1Ty = In1.getValueType();
2767     SDLoc DL(N);
2768     // If both incoming values are integers, and the original types are the
2769     // same.
2770     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2771       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2772       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2773       AddToWorklist(Op.getNode());
2774       return BC;
2775     }
2776   }
2777 
2778   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2779   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2780   // If both shuffles use the same mask, and both shuffle within a single
2781   // vector, then it is worthwhile to move the swizzle after the operation.
2782   // The type-legalizer generates this pattern when loading illegal
2783   // vector types from memory. In many cases this allows additional shuffle
2784   // optimizations.
2785   // There are other cases where moving the shuffle after the xor/and/or
2786   // is profitable even if shuffles don't perform a swizzle.
2787   // If both shuffles use the same mask, and both shuffles have the same first
2788   // or second operand, then it might still be profitable to move the shuffle
2789   // after the xor/and/or operation.
2790   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2791     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2792     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2793 
2794     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2795            "Inputs to shuffles are not the same type");
2796 
2797     // Check that both shuffles use the same mask. The masks are known to be of
2798     // the same length because the result vector type is the same.
2799     // Check also that shuffles have only one use to avoid introducing extra
2800     // instructions.
2801     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2802         SVN0->getMask().equals(SVN1->getMask())) {
2803       SDValue ShOp = N0->getOperand(1);
2804 
2805       // Don't try to fold this node if it requires introducing a
2806       // build vector of all zeros that might be illegal at this stage.
2807       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2808         if (!LegalTypes)
2809           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2810         else
2811           ShOp = SDValue();
2812       }
2813 
2814       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2815       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2816       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2817       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2818         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2819                                       N0->getOperand(0), N1->getOperand(0));
2820         AddToWorklist(NewNode.getNode());
2821         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2822                                     &SVN0->getMask()[0]);
2823       }
2824 
2825       // Don't try to fold this node if it requires introducing a
2826       // build vector of all zeros that might be illegal at this stage.
2827       ShOp = N0->getOperand(0);
2828       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2829         if (!LegalTypes)
2830           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2831         else
2832           ShOp = SDValue();
2833       }
2834 
2835       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2836       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2837       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2838       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2839         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2840                                       N0->getOperand(1), N1->getOperand(1));
2841         AddToWorklist(NewNode.getNode());
2842         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2843                                     &SVN0->getMask()[0]);
2844       }
2845     }
2846   }
2847 
2848   return SDValue();
2849 }
2850 
2851 /// This contains all DAGCombine rules which reduce two values combined by
2852 /// an And operation to a single value. This makes them reusable in the context
2853 /// of visitSELECT(). Rules involving constants are not included as
2854 /// visitSELECT() already handles those cases.
2855 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2856                                   SDNode *LocReference) {
2857   EVT VT = N1.getValueType();
2858 
2859   // fold (and x, undef) -> 0
2860   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2861     return DAG.getConstant(0, SDLoc(LocReference), VT);
2862   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2863   SDValue LL, LR, RL, RR, CC0, CC1;
2864   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2865     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2866     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2867 
2868     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2869         LL.getValueType().isInteger()) {
2870       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2871       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2872         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2873                                      LR.getValueType(), LL, RL);
2874         AddToWorklist(ORNode.getNode());
2875         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2876       }
2877       if (isAllOnesConstant(LR)) {
2878         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2879         if (Op1 == ISD::SETEQ) {
2880           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2881                                         LR.getValueType(), LL, RL);
2882           AddToWorklist(ANDNode.getNode());
2883           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2884         }
2885         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2886         if (Op1 == ISD::SETGT) {
2887           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2888                                        LR.getValueType(), LL, RL);
2889           AddToWorklist(ORNode.getNode());
2890           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2891         }
2892       }
2893     }
2894     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2895     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2896         Op0 == Op1 && LL.getValueType().isInteger() &&
2897       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2898                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2899       SDLoc DL(N0);
2900       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2901                                     LL, DAG.getConstant(1, DL,
2902                                                         LL.getValueType()));
2903       AddToWorklist(ADDNode.getNode());
2904       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2905                           DAG.getConstant(2, DL, LL.getValueType()),
2906                           ISD::SETUGE);
2907     }
2908     // canonicalize equivalent to ll == rl
2909     if (LL == RR && LR == RL) {
2910       Op1 = ISD::getSetCCSwappedOperands(Op1);
2911       std::swap(RL, RR);
2912     }
2913     if (LL == RL && LR == RR) {
2914       bool isInteger = LL.getValueType().isInteger();
2915       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2916       if (Result != ISD::SETCC_INVALID &&
2917           (!LegalOperations ||
2918            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2919             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2920         EVT CCVT = getSetCCResultType(LL.getValueType());
2921         if (N0.getValueType() == CCVT ||
2922             (!LegalOperations && N0.getValueType() == MVT::i1))
2923           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2924                               LL, LR, Result);
2925       }
2926     }
2927   }
2928 
2929   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2930       VT.getSizeInBits() <= 64) {
2931     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2932       APInt ADDC = ADDI->getAPIntValue();
2933       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2934         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2935         // immediate for an add, but it is legal if its top c2 bits are set,
2936         // transform the ADD so the immediate doesn't need to be materialized
2937         // in a register.
2938         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2939           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2940                                              SRLI->getZExtValue());
2941           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2942             ADDC |= Mask;
2943             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2944               SDLoc DL(N0);
2945               SDValue NewAdd =
2946                 DAG.getNode(ISD::ADD, DL, VT,
2947                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2948               CombineTo(N0.getNode(), NewAdd);
2949               // Return N so it doesn't get rechecked!
2950               return SDValue(LocReference, 0);
2951             }
2952           }
2953         }
2954       }
2955     }
2956   }
2957 
2958   return SDValue();
2959 }
2960 
2961 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
2962                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
2963                                    bool &NarrowLoad) {
2964   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
2965 
2966   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
2967     return false;
2968 
2969   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2970   LoadedVT = LoadN->getMemoryVT();
2971 
2972   if (ExtVT == LoadedVT &&
2973       (!LegalOperations ||
2974        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
2975     // ZEXTLOAD will match without needing to change the size of the value being
2976     // loaded.
2977     NarrowLoad = false;
2978     return true;
2979   }
2980 
2981   // Do not change the width of a volatile load.
2982   if (LoadN->isVolatile())
2983     return false;
2984 
2985   // Do not generate loads of non-round integer types since these can
2986   // be expensive (and would be wrong if the type is not byte sized).
2987   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
2988     return false;
2989 
2990   if (LegalOperations &&
2991       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
2992     return false;
2993 
2994   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
2995     return false;
2996 
2997   NarrowLoad = true;
2998   return true;
2999 }
3000 
3001 SDValue DAGCombiner::visitAND(SDNode *N) {
3002   SDValue N0 = N->getOperand(0);
3003   SDValue N1 = N->getOperand(1);
3004   EVT VT = N1.getValueType();
3005 
3006   // fold vector ops
3007   if (VT.isVector()) {
3008     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3009       return FoldedVOp;
3010 
3011     // fold (and x, 0) -> 0, vector edition
3012     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3013       // do not return N0, because undef node may exist in N0
3014       return DAG.getConstant(
3015           APInt::getNullValue(
3016               N0.getValueType().getScalarType().getSizeInBits()),
3017           SDLoc(N), N0.getValueType());
3018     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3019       // do not return N1, because undef node may exist in N1
3020       return DAG.getConstant(
3021           APInt::getNullValue(
3022               N1.getValueType().getScalarType().getSizeInBits()),
3023           SDLoc(N), N1.getValueType());
3024 
3025     // fold (and x, -1) -> x, vector edition
3026     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3027       return N1;
3028     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3029       return N0;
3030   }
3031 
3032   // fold (and c1, c2) -> c1&c2
3033   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3034   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3035   if (N0C && N1C && !N1C->isOpaque())
3036     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3037   // canonicalize constant to RHS
3038   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3039      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3040     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3041   // fold (and x, -1) -> x
3042   if (isAllOnesConstant(N1))
3043     return N0;
3044   // if (and x, c) is known to be zero, return 0
3045   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3046   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3047                                    APInt::getAllOnesValue(BitWidth)))
3048     return DAG.getConstant(0, SDLoc(N), VT);
3049   // reassociate and
3050   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3051     return RAND;
3052   // fold (and (or x, C), D) -> D if (C & D) == D
3053   if (N1C && N0.getOpcode() == ISD::OR)
3054     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3055       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3056         return N1;
3057   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3058   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3059     SDValue N0Op0 = N0.getOperand(0);
3060     APInt Mask = ~N1C->getAPIntValue();
3061     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3062     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3063       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3064                                  N0.getValueType(), N0Op0);
3065 
3066       // Replace uses of the AND with uses of the Zero extend node.
3067       CombineTo(N, Zext);
3068 
3069       // We actually want to replace all uses of the any_extend with the
3070       // zero_extend, to avoid duplicating things.  This will later cause this
3071       // AND to be folded.
3072       CombineTo(N0.getNode(), Zext);
3073       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3074     }
3075   }
3076   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3077   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3078   // already be zero by virtue of the width of the base type of the load.
3079   //
3080   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3081   // more cases.
3082   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3083        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3084       N0.getOpcode() == ISD::LOAD) {
3085     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3086                                          N0 : N0.getOperand(0) );
3087 
3088     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3089     // This can be a pure constant or a vector splat, in which case we treat the
3090     // vector as a scalar and use the splat value.
3091     APInt Constant = APInt::getNullValue(1);
3092     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3093       Constant = C->getAPIntValue();
3094     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3095       APInt SplatValue, SplatUndef;
3096       unsigned SplatBitSize;
3097       bool HasAnyUndefs;
3098       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3099                                              SplatBitSize, HasAnyUndefs);
3100       if (IsSplat) {
3101         // Undef bits can contribute to a possible optimisation if set, so
3102         // set them.
3103         SplatValue |= SplatUndef;
3104 
3105         // The splat value may be something like "0x00FFFFFF", which means 0 for
3106         // the first vector value and FF for the rest, repeating. We need a mask
3107         // that will apply equally to all members of the vector, so AND all the
3108         // lanes of the constant together.
3109         EVT VT = Vector->getValueType(0);
3110         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3111 
3112         // If the splat value has been compressed to a bitlength lower
3113         // than the size of the vector lane, we need to re-expand it to
3114         // the lane size.
3115         if (BitWidth > SplatBitSize)
3116           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3117                SplatBitSize < BitWidth;
3118                SplatBitSize = SplatBitSize * 2)
3119             SplatValue |= SplatValue.shl(SplatBitSize);
3120 
3121         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3122         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3123         if (SplatBitSize % BitWidth == 0) {
3124           Constant = APInt::getAllOnesValue(BitWidth);
3125           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3126             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3127         }
3128       }
3129     }
3130 
3131     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3132     // actually legal and isn't going to get expanded, else this is a false
3133     // optimisation.
3134     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3135                                                     Load->getValueType(0),
3136                                                     Load->getMemoryVT());
3137 
3138     // Resize the constant to the same size as the original memory access before
3139     // extension. If it is still the AllOnesValue then this AND is completely
3140     // unneeded.
3141     Constant =
3142       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3143 
3144     bool B;
3145     switch (Load->getExtensionType()) {
3146     default: B = false; break;
3147     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3148     case ISD::ZEXTLOAD:
3149     case ISD::NON_EXTLOAD: B = true; break;
3150     }
3151 
3152     if (B && Constant.isAllOnesValue()) {
3153       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3154       // preserve semantics once we get rid of the AND.
3155       SDValue NewLoad(Load, 0);
3156       if (Load->getExtensionType() == ISD::EXTLOAD) {
3157         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3158                               Load->getValueType(0), SDLoc(Load),
3159                               Load->getChain(), Load->getBasePtr(),
3160                               Load->getOffset(), Load->getMemoryVT(),
3161                               Load->getMemOperand());
3162         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3163         if (Load->getNumValues() == 3) {
3164           // PRE/POST_INC loads have 3 values.
3165           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3166                            NewLoad.getValue(2) };
3167           CombineTo(Load, To, 3, true);
3168         } else {
3169           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3170         }
3171       }
3172 
3173       // Fold the AND away, taking care not to fold to the old load node if we
3174       // replaced it.
3175       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3176 
3177       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3178     }
3179   }
3180 
3181   // fold (and (load x), 255) -> (zextload x, i8)
3182   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3183   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3184   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3185               (N0.getOpcode() == ISD::ANY_EXTEND &&
3186                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3187     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3188     LoadSDNode *LN0 = HasAnyExt
3189       ? cast<LoadSDNode>(N0.getOperand(0))
3190       : cast<LoadSDNode>(N0);
3191     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3192         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3193       auto NarrowLoad = false;
3194       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3195       EVT ExtVT, LoadedVT;
3196       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3197                            NarrowLoad)) {
3198         if (!NarrowLoad) {
3199           SDValue NewLoad =
3200             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3201                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3202                            LN0->getMemOperand());
3203           AddToWorklist(N);
3204           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3205           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3206         } else {
3207           EVT PtrType = LN0->getOperand(1).getValueType();
3208 
3209           unsigned Alignment = LN0->getAlignment();
3210           SDValue NewPtr = LN0->getBasePtr();
3211 
3212           // For big endian targets, we need to add an offset to the pointer
3213           // to load the correct bytes.  For little endian systems, we merely
3214           // need to read fewer bytes from the same pointer.
3215           if (DAG.getDataLayout().isBigEndian()) {
3216             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3217             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3218             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3219             SDLoc DL(LN0);
3220             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3221                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3222             Alignment = MinAlign(Alignment, PtrOff);
3223           }
3224 
3225           AddToWorklist(NewPtr.getNode());
3226 
3227           SDValue Load =
3228             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3229                            LN0->getChain(), NewPtr,
3230                            LN0->getPointerInfo(),
3231                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3232                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3233           AddToWorklist(N);
3234           CombineTo(LN0, Load, Load.getValue(1));
3235           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3236         }
3237       }
3238     }
3239   }
3240 
3241   if (SDValue Combined = visitANDLike(N0, N1, N))
3242     return Combined;
3243 
3244   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3245   if (N0.getOpcode() == N1.getOpcode())
3246     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3247       return Tmp;
3248 
3249   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3250   // fold (and (sra)) -> (and (srl)) when possible.
3251   if (!VT.isVector() &&
3252       SimplifyDemandedBits(SDValue(N, 0)))
3253     return SDValue(N, 0);
3254 
3255   // fold (zext_inreg (extload x)) -> (zextload x)
3256   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3257     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3258     EVT MemVT = LN0->getMemoryVT();
3259     // If we zero all the possible extended bits, then we can turn this into
3260     // a zextload if we are running before legalize or the operation is legal.
3261     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3262     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3263                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3264         ((!LegalOperations && !LN0->isVolatile()) ||
3265          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3266       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3267                                        LN0->getChain(), LN0->getBasePtr(),
3268                                        MemVT, LN0->getMemOperand());
3269       AddToWorklist(N);
3270       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3271       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3272     }
3273   }
3274   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3275   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3276       N0.hasOneUse()) {
3277     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3278     EVT MemVT = LN0->getMemoryVT();
3279     // If we zero all the possible extended bits, then we can turn this into
3280     // a zextload if we are running before legalize or the operation is legal.
3281     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3282     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3283                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3284         ((!LegalOperations && !LN0->isVolatile()) ||
3285          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3286       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3287                                        LN0->getChain(), LN0->getBasePtr(),
3288                                        MemVT, LN0->getMemOperand());
3289       AddToWorklist(N);
3290       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3291       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3292     }
3293   }
3294   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3295   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3296     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3297                                            N0.getOperand(1), false))
3298       return BSwap;
3299   }
3300 
3301   return SDValue();
3302 }
3303 
3304 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3305 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3306                                         bool DemandHighBits) {
3307   if (!LegalOperations)
3308     return SDValue();
3309 
3310   EVT VT = N->getValueType(0);
3311   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3312     return SDValue();
3313   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3314     return SDValue();
3315 
3316   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3317   bool LookPassAnd0 = false;
3318   bool LookPassAnd1 = false;
3319   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3320       std::swap(N0, N1);
3321   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3322       std::swap(N0, N1);
3323   if (N0.getOpcode() == ISD::AND) {
3324     if (!N0.getNode()->hasOneUse())
3325       return SDValue();
3326     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3327     if (!N01C || N01C->getZExtValue() != 0xFF00)
3328       return SDValue();
3329     N0 = N0.getOperand(0);
3330     LookPassAnd0 = true;
3331   }
3332 
3333   if (N1.getOpcode() == ISD::AND) {
3334     if (!N1.getNode()->hasOneUse())
3335       return SDValue();
3336     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3337     if (!N11C || N11C->getZExtValue() != 0xFF)
3338       return SDValue();
3339     N1 = N1.getOperand(0);
3340     LookPassAnd1 = true;
3341   }
3342 
3343   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3344     std::swap(N0, N1);
3345   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3346     return SDValue();
3347   if (!N0.getNode()->hasOneUse() ||
3348       !N1.getNode()->hasOneUse())
3349     return SDValue();
3350 
3351   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3352   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3353   if (!N01C || !N11C)
3354     return SDValue();
3355   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3356     return SDValue();
3357 
3358   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3359   SDValue N00 = N0->getOperand(0);
3360   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3361     if (!N00.getNode()->hasOneUse())
3362       return SDValue();
3363     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3364     if (!N001C || N001C->getZExtValue() != 0xFF)
3365       return SDValue();
3366     N00 = N00.getOperand(0);
3367     LookPassAnd0 = true;
3368   }
3369 
3370   SDValue N10 = N1->getOperand(0);
3371   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3372     if (!N10.getNode()->hasOneUse())
3373       return SDValue();
3374     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3375     if (!N101C || N101C->getZExtValue() != 0xFF00)
3376       return SDValue();
3377     N10 = N10.getOperand(0);
3378     LookPassAnd1 = true;
3379   }
3380 
3381   if (N00 != N10)
3382     return SDValue();
3383 
3384   // Make sure everything beyond the low halfword gets set to zero since the SRL
3385   // 16 will clear the top bits.
3386   unsigned OpSizeInBits = VT.getSizeInBits();
3387   if (DemandHighBits && OpSizeInBits > 16) {
3388     // If the left-shift isn't masked out then the only way this is a bswap is
3389     // if all bits beyond the low 8 are 0. In that case the entire pattern
3390     // reduces to a left shift anyway: leave it for other parts of the combiner.
3391     if (!LookPassAnd0)
3392       return SDValue();
3393 
3394     // However, if the right shift isn't masked out then it might be because
3395     // it's not needed. See if we can spot that too.
3396     if (!LookPassAnd1 &&
3397         !DAG.MaskedValueIsZero(
3398             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3399       return SDValue();
3400   }
3401 
3402   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3403   if (OpSizeInBits > 16) {
3404     SDLoc DL(N);
3405     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3406                       DAG.getConstant(OpSizeInBits - 16, DL,
3407                                       getShiftAmountTy(VT)));
3408   }
3409   return Res;
3410 }
3411 
3412 /// Return true if the specified node is an element that makes up a 32-bit
3413 /// packed halfword byteswap.
3414 /// ((x & 0x000000ff) << 8) |
3415 /// ((x & 0x0000ff00) >> 8) |
3416 /// ((x & 0x00ff0000) << 8) |
3417 /// ((x & 0xff000000) >> 8)
3418 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3419   if (!N.getNode()->hasOneUse())
3420     return false;
3421 
3422   unsigned Opc = N.getOpcode();
3423   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3424     return false;
3425 
3426   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3427   if (!N1C)
3428     return false;
3429 
3430   unsigned Num;
3431   switch (N1C->getZExtValue()) {
3432   default:
3433     return false;
3434   case 0xFF:       Num = 0; break;
3435   case 0xFF00:     Num = 1; break;
3436   case 0xFF0000:   Num = 2; break;
3437   case 0xFF000000: Num = 3; break;
3438   }
3439 
3440   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3441   SDValue N0 = N.getOperand(0);
3442   if (Opc == ISD::AND) {
3443     if (Num == 0 || Num == 2) {
3444       // (x >> 8) & 0xff
3445       // (x >> 8) & 0xff0000
3446       if (N0.getOpcode() != ISD::SRL)
3447         return false;
3448       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3449       if (!C || C->getZExtValue() != 8)
3450         return false;
3451     } else {
3452       // (x << 8) & 0xff00
3453       // (x << 8) & 0xff000000
3454       if (N0.getOpcode() != ISD::SHL)
3455         return false;
3456       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3457       if (!C || C->getZExtValue() != 8)
3458         return false;
3459     }
3460   } else if (Opc == ISD::SHL) {
3461     // (x & 0xff) << 8
3462     // (x & 0xff0000) << 8
3463     if (Num != 0 && Num != 2)
3464       return false;
3465     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3466     if (!C || C->getZExtValue() != 8)
3467       return false;
3468   } else { // Opc == ISD::SRL
3469     // (x & 0xff00) >> 8
3470     // (x & 0xff000000) >> 8
3471     if (Num != 1 && Num != 3)
3472       return false;
3473     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3474     if (!C || C->getZExtValue() != 8)
3475       return false;
3476   }
3477 
3478   if (Parts[Num])
3479     return false;
3480 
3481   Parts[Num] = N0.getOperand(0).getNode();
3482   return true;
3483 }
3484 
3485 /// Match a 32-bit packed halfword bswap. That is
3486 /// ((x & 0x000000ff) << 8) |
3487 /// ((x & 0x0000ff00) >> 8) |
3488 /// ((x & 0x00ff0000) << 8) |
3489 /// ((x & 0xff000000) >> 8)
3490 /// => (rotl (bswap x), 16)
3491 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3492   if (!LegalOperations)
3493     return SDValue();
3494 
3495   EVT VT = N->getValueType(0);
3496   if (VT != MVT::i32)
3497     return SDValue();
3498   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3499     return SDValue();
3500 
3501   // Look for either
3502   // (or (or (and), (and)), (or (and), (and)))
3503   // (or (or (or (and), (and)), (and)), (and))
3504   if (N0.getOpcode() != ISD::OR)
3505     return SDValue();
3506   SDValue N00 = N0.getOperand(0);
3507   SDValue N01 = N0.getOperand(1);
3508   SDNode *Parts[4] = {};
3509 
3510   if (N1.getOpcode() == ISD::OR &&
3511       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3512     // (or (or (and), (and)), (or (and), (and)))
3513     SDValue N000 = N00.getOperand(0);
3514     if (!isBSwapHWordElement(N000, Parts))
3515       return SDValue();
3516 
3517     SDValue N001 = N00.getOperand(1);
3518     if (!isBSwapHWordElement(N001, Parts))
3519       return SDValue();
3520     SDValue N010 = N01.getOperand(0);
3521     if (!isBSwapHWordElement(N010, Parts))
3522       return SDValue();
3523     SDValue N011 = N01.getOperand(1);
3524     if (!isBSwapHWordElement(N011, Parts))
3525       return SDValue();
3526   } else {
3527     // (or (or (or (and), (and)), (and)), (and))
3528     if (!isBSwapHWordElement(N1, Parts))
3529       return SDValue();
3530     if (!isBSwapHWordElement(N01, Parts))
3531       return SDValue();
3532     if (N00.getOpcode() != ISD::OR)
3533       return SDValue();
3534     SDValue N000 = N00.getOperand(0);
3535     if (!isBSwapHWordElement(N000, Parts))
3536       return SDValue();
3537     SDValue N001 = N00.getOperand(1);
3538     if (!isBSwapHWordElement(N001, Parts))
3539       return SDValue();
3540   }
3541 
3542   // Make sure the parts are all coming from the same node.
3543   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3544     return SDValue();
3545 
3546   SDLoc DL(N);
3547   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3548                               SDValue(Parts[0], 0));
3549 
3550   // Result of the bswap should be rotated by 16. If it's not legal, then
3551   // do  (x << 16) | (x >> 16).
3552   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3553   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3554     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3555   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3556     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3557   return DAG.getNode(ISD::OR, DL, VT,
3558                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3559                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3560 }
3561 
3562 /// This contains all DAGCombine rules which reduce two values combined by
3563 /// an Or operation to a single value \see visitANDLike().
3564 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3565   EVT VT = N1.getValueType();
3566   // fold (or x, undef) -> -1
3567   if (!LegalOperations &&
3568       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3569     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3570     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3571                            SDLoc(LocReference), VT);
3572   }
3573   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3574   SDValue LL, LR, RL, RR, CC0, CC1;
3575   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3576     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3577     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3578 
3579     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3580       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3581       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3582       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3583         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3584                                      LR.getValueType(), LL, RL);
3585         AddToWorklist(ORNode.getNode());
3586         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3587       }
3588       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3589       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3590       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3591         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3592                                       LR.getValueType(), LL, RL);
3593         AddToWorklist(ANDNode.getNode());
3594         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3595       }
3596     }
3597     // canonicalize equivalent to ll == rl
3598     if (LL == RR && LR == RL) {
3599       Op1 = ISD::getSetCCSwappedOperands(Op1);
3600       std::swap(RL, RR);
3601     }
3602     if (LL == RL && LR == RR) {
3603       bool isInteger = LL.getValueType().isInteger();
3604       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3605       if (Result != ISD::SETCC_INVALID &&
3606           (!LegalOperations ||
3607            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3608             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3609         EVT CCVT = getSetCCResultType(LL.getValueType());
3610         if (N0.getValueType() == CCVT ||
3611             (!LegalOperations && N0.getValueType() == MVT::i1))
3612           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3613                               LL, LR, Result);
3614       }
3615     }
3616   }
3617 
3618   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3619   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3620       // Don't increase # computations.
3621       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3622     // We can only do this xform if we know that bits from X that are set in C2
3623     // but not in C1 are already zero.  Likewise for Y.
3624     if (const ConstantSDNode *N0O1C =
3625         getAsNonOpaqueConstant(N0.getOperand(1))) {
3626       if (const ConstantSDNode *N1O1C =
3627           getAsNonOpaqueConstant(N1.getOperand(1))) {
3628         // We can only do this xform if we know that bits from X that are set in
3629         // C2 but not in C1 are already zero.  Likewise for Y.
3630         const APInt &LHSMask = N0O1C->getAPIntValue();
3631         const APInt &RHSMask = N1O1C->getAPIntValue();
3632 
3633         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3634             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3635           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3636                                   N0.getOperand(0), N1.getOperand(0));
3637           SDLoc DL(LocReference);
3638           return DAG.getNode(ISD::AND, DL, VT, X,
3639                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3640         }
3641       }
3642     }
3643   }
3644 
3645   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3646   if (N0.getOpcode() == ISD::AND &&
3647       N1.getOpcode() == ISD::AND &&
3648       N0.getOperand(0) == N1.getOperand(0) &&
3649       // Don't increase # computations.
3650       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3651     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3652                             N0.getOperand(1), N1.getOperand(1));
3653     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3654   }
3655 
3656   return SDValue();
3657 }
3658 
3659 SDValue DAGCombiner::visitOR(SDNode *N) {
3660   SDValue N0 = N->getOperand(0);
3661   SDValue N1 = N->getOperand(1);
3662   EVT VT = N1.getValueType();
3663 
3664   // fold vector ops
3665   if (VT.isVector()) {
3666     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3667       return FoldedVOp;
3668 
3669     // fold (or x, 0) -> x, vector edition
3670     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3671       return N1;
3672     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3673       return N0;
3674 
3675     // fold (or x, -1) -> -1, vector edition
3676     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3677       // do not return N0, because undef node may exist in N0
3678       return DAG.getConstant(
3679           APInt::getAllOnesValue(
3680               N0.getValueType().getScalarType().getSizeInBits()),
3681           SDLoc(N), N0.getValueType());
3682     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3683       // do not return N1, because undef node may exist in N1
3684       return DAG.getConstant(
3685           APInt::getAllOnesValue(
3686               N1.getValueType().getScalarType().getSizeInBits()),
3687           SDLoc(N), N1.getValueType());
3688 
3689     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3690     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3691     // Do this only if the resulting shuffle is legal.
3692     if (isa<ShuffleVectorSDNode>(N0) &&
3693         isa<ShuffleVectorSDNode>(N1) &&
3694         // Avoid folding a node with illegal type.
3695         TLI.isTypeLegal(VT) &&
3696         N0->getOperand(1) == N1->getOperand(1) &&
3697         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3698       bool CanFold = true;
3699       unsigned NumElts = VT.getVectorNumElements();
3700       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3701       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3702       // We construct two shuffle masks:
3703       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3704       // and N1 as the second operand.
3705       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3706       // and N0 as the second operand.
3707       // We do this because OR is commutable and therefore there might be
3708       // two ways to fold this node into a shuffle.
3709       SmallVector<int,4> Mask1;
3710       SmallVector<int,4> Mask2;
3711 
3712       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3713         int M0 = SV0->getMaskElt(i);
3714         int M1 = SV1->getMaskElt(i);
3715 
3716         // Both shuffle indexes are undef. Propagate Undef.
3717         if (M0 < 0 && M1 < 0) {
3718           Mask1.push_back(M0);
3719           Mask2.push_back(M0);
3720           continue;
3721         }
3722 
3723         if (M0 < 0 || M1 < 0 ||
3724             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3725             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3726           CanFold = false;
3727           break;
3728         }
3729 
3730         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3731         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3732       }
3733 
3734       if (CanFold) {
3735         // Fold this sequence only if the resulting shuffle is 'legal'.
3736         if (TLI.isShuffleMaskLegal(Mask1, VT))
3737           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3738                                       N1->getOperand(0), &Mask1[0]);
3739         if (TLI.isShuffleMaskLegal(Mask2, VT))
3740           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3741                                       N0->getOperand(0), &Mask2[0]);
3742       }
3743     }
3744   }
3745 
3746   // fold (or c1, c2) -> c1|c2
3747   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3748   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3749   if (N0C && N1C && !N1C->isOpaque())
3750     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3751   // canonicalize constant to RHS
3752   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3753      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3754     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3755   // fold (or x, 0) -> x
3756   if (isNullConstant(N1))
3757     return N0;
3758   // fold (or x, -1) -> -1
3759   if (isAllOnesConstant(N1))
3760     return N1;
3761   // fold (or x, c) -> c iff (x & ~c) == 0
3762   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3763     return N1;
3764 
3765   if (SDValue Combined = visitORLike(N0, N1, N))
3766     return Combined;
3767 
3768   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3769   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3770     return BSwap;
3771   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3772     return BSwap;
3773 
3774   // reassociate or
3775   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3776     return ROR;
3777   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3778   // iff (c1 & c2) == 0.
3779   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3780              isa<ConstantSDNode>(N0.getOperand(1))) {
3781     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3782     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3783       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3784                                                    N1C, C1))
3785         return DAG.getNode(
3786             ISD::AND, SDLoc(N), VT,
3787             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3788       return SDValue();
3789     }
3790   }
3791   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3792   if (N0.getOpcode() == N1.getOpcode())
3793     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3794       return Tmp;
3795 
3796   // See if this is some rotate idiom.
3797   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3798     return SDValue(Rot, 0);
3799 
3800   // Simplify the operands using demanded-bits information.
3801   if (!VT.isVector() &&
3802       SimplifyDemandedBits(SDValue(N, 0)))
3803     return SDValue(N, 0);
3804 
3805   return SDValue();
3806 }
3807 
3808 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3809 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3810   if (Op.getOpcode() == ISD::AND) {
3811     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3812       Mask = Op.getOperand(1);
3813       Op = Op.getOperand(0);
3814     } else {
3815       return false;
3816     }
3817   }
3818 
3819   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3820     Shift = Op;
3821     return true;
3822   }
3823 
3824   return false;
3825 }
3826 
3827 // Return true if we can prove that, whenever Neg and Pos are both in the
3828 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3829 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3830 //
3831 //     (or (shift1 X, Neg), (shift2 X, Pos))
3832 //
3833 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3834 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3835 // to consider shift amounts with defined behavior.
3836 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3837   // If EltSize is a power of 2 then:
3838   //
3839   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3840   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3841   //
3842   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3843   // for the stronger condition:
3844   //
3845   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3846   //
3847   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3848   // we can just replace Neg with Neg' for the rest of the function.
3849   //
3850   // In other cases we check for the even stronger condition:
3851   //
3852   //     Neg == EltSize - Pos                                    [B]
3853   //
3854   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3855   // behavior if Pos == 0 (and consequently Neg == EltSize).
3856   //
3857   // We could actually use [A] whenever EltSize is a power of 2, but the
3858   // only extra cases that it would match are those uninteresting ones
3859   // where Neg and Pos are never in range at the same time.  E.g. for
3860   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3861   // as well as (sub 32, Pos), but:
3862   //
3863   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3864   //
3865   // always invokes undefined behavior for 32-bit X.
3866   //
3867   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3868   unsigned MaskLoBits = 0;
3869   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3870     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3871       if (NegC->getAPIntValue() == EltSize - 1) {
3872         Neg = Neg.getOperand(0);
3873         MaskLoBits = Log2_64(EltSize);
3874       }
3875     }
3876   }
3877 
3878   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3879   if (Neg.getOpcode() != ISD::SUB)
3880     return false;
3881   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3882   if (!NegC)
3883     return false;
3884   SDValue NegOp1 = Neg.getOperand(1);
3885 
3886   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3887   // Pos'.  The truncation is redundant for the purpose of the equality.
3888   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3889     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3890       if (PosC->getAPIntValue() == EltSize - 1)
3891         Pos = Pos.getOperand(0);
3892 
3893   // The condition we need is now:
3894   //
3895   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3896   //
3897   // If NegOp1 == Pos then we need:
3898   //
3899   //              EltSize & Mask == NegC & Mask
3900   //
3901   // (because "x & Mask" is a truncation and distributes through subtraction).
3902   APInt Width;
3903   if (Pos == NegOp1)
3904     Width = NegC->getAPIntValue();
3905 
3906   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3907   // Then the condition we want to prove becomes:
3908   //
3909   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3910   //
3911   // which, again because "x & Mask" is a truncation, becomes:
3912   //
3913   //                NegC & Mask == (EltSize - PosC) & Mask
3914   //             EltSize & Mask == (NegC + PosC) & Mask
3915   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3916     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3917       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3918     else
3919       return false;
3920   } else
3921     return false;
3922 
3923   // Now we just need to check that EltSize & Mask == Width & Mask.
3924   if (MaskLoBits)
3925     // EltSize & Mask is 0 since Mask is EltSize - 1.
3926     return Width.getLoBits(MaskLoBits) == 0;
3927   return Width == EltSize;
3928 }
3929 
3930 // A subroutine of MatchRotate used once we have found an OR of two opposite
3931 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3932 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3933 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3934 // Neg with outer conversions stripped away.
3935 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3936                                        SDValue Neg, SDValue InnerPos,
3937                                        SDValue InnerNeg, unsigned PosOpcode,
3938                                        unsigned NegOpcode, SDLoc DL) {
3939   // fold (or (shl x, (*ext y)),
3940   //          (srl x, (*ext (sub 32, y)))) ->
3941   //   (rotl x, y) or (rotr x, (sub 32, y))
3942   //
3943   // fold (or (shl x, (*ext (sub 32, y))),
3944   //          (srl x, (*ext y))) ->
3945   //   (rotr x, y) or (rotl x, (sub 32, y))
3946   EVT VT = Shifted.getValueType();
3947   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3948     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3949     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3950                        HasPos ? Pos : Neg).getNode();
3951   }
3952 
3953   return nullptr;
3954 }
3955 
3956 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3957 // idioms for rotate, and if the target supports rotation instructions, generate
3958 // a rot[lr].
3959 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3960   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3961   EVT VT = LHS.getValueType();
3962   if (!TLI.isTypeLegal(VT)) return nullptr;
3963 
3964   // The target must have at least one rotate flavor.
3965   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3966   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3967   if (!HasROTL && !HasROTR) return nullptr;
3968 
3969   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3970   SDValue LHSShift;   // The shift.
3971   SDValue LHSMask;    // AND value if any.
3972   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3973     return nullptr; // Not part of a rotate.
3974 
3975   SDValue RHSShift;   // The shift.
3976   SDValue RHSMask;    // AND value if any.
3977   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3978     return nullptr; // Not part of a rotate.
3979 
3980   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3981     return nullptr;   // Not shifting the same value.
3982 
3983   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3984     return nullptr;   // Shifts must disagree.
3985 
3986   // Canonicalize shl to left side in a shl/srl pair.
3987   if (RHSShift.getOpcode() == ISD::SHL) {
3988     std::swap(LHS, RHS);
3989     std::swap(LHSShift, RHSShift);
3990     std::swap(LHSMask, RHSMask);
3991   }
3992 
3993   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3994   SDValue LHSShiftArg = LHSShift.getOperand(0);
3995   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3996   SDValue RHSShiftArg = RHSShift.getOperand(0);
3997   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3998 
3999   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4000   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4001   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4002     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4003     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4004     if ((LShVal + RShVal) != EltSizeInBits)
4005       return nullptr;
4006 
4007     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4008                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4009 
4010     // If there is an AND of either shifted operand, apply it to the result.
4011     if (LHSMask.getNode() || RHSMask.getNode()) {
4012       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4013       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4014 
4015       if (LHSMask.getNode()) {
4016         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4017         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4018                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4019                                        DAG.getConstant(RHSBits, DL, VT)));
4020       }
4021       if (RHSMask.getNode()) {
4022         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4023         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4024                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4025                                        DAG.getConstant(LHSBits, DL, VT)));
4026       }
4027 
4028       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4029     }
4030 
4031     return Rot.getNode();
4032   }
4033 
4034   // If there is a mask here, and we have a variable shift, we can't be sure
4035   // that we're masking out the right stuff.
4036   if (LHSMask.getNode() || RHSMask.getNode())
4037     return nullptr;
4038 
4039   // If the shift amount is sign/zext/any-extended just peel it off.
4040   SDValue LExtOp0 = LHSShiftAmt;
4041   SDValue RExtOp0 = RHSShiftAmt;
4042   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4043        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4044        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4045        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4046       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4047        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4048        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4049        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4050     LExtOp0 = LHSShiftAmt.getOperand(0);
4051     RExtOp0 = RHSShiftAmt.getOperand(0);
4052   }
4053 
4054   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4055                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4056   if (TryL)
4057     return TryL;
4058 
4059   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4060                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4061   if (TryR)
4062     return TryR;
4063 
4064   return nullptr;
4065 }
4066 
4067 SDValue DAGCombiner::visitXOR(SDNode *N) {
4068   SDValue N0 = N->getOperand(0);
4069   SDValue N1 = N->getOperand(1);
4070   EVT VT = N0.getValueType();
4071 
4072   // fold vector ops
4073   if (VT.isVector()) {
4074     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4075       return FoldedVOp;
4076 
4077     // fold (xor x, 0) -> x, vector edition
4078     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4079       return N1;
4080     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4081       return N0;
4082   }
4083 
4084   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4085   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4086     return DAG.getConstant(0, SDLoc(N), VT);
4087   // fold (xor x, undef) -> undef
4088   if (N0.getOpcode() == ISD::UNDEF)
4089     return N0;
4090   if (N1.getOpcode() == ISD::UNDEF)
4091     return N1;
4092   // fold (xor c1, c2) -> c1^c2
4093   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4094   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4095   if (N0C && N1C)
4096     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4097   // canonicalize constant to RHS
4098   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4099      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4100     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4101   // fold (xor x, 0) -> x
4102   if (isNullConstant(N1))
4103     return N0;
4104   // reassociate xor
4105   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4106     return RXOR;
4107 
4108   // fold !(x cc y) -> (x !cc y)
4109   SDValue LHS, RHS, CC;
4110   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4111     bool isInt = LHS.getValueType().isInteger();
4112     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4113                                                isInt);
4114 
4115     if (!LegalOperations ||
4116         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4117       switch (N0.getOpcode()) {
4118       default:
4119         llvm_unreachable("Unhandled SetCC Equivalent!");
4120       case ISD::SETCC:
4121         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4122       case ISD::SELECT_CC:
4123         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4124                                N0.getOperand(3), NotCC);
4125       }
4126     }
4127   }
4128 
4129   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4130   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4131       N0.getNode()->hasOneUse() &&
4132       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4133     SDValue V = N0.getOperand(0);
4134     SDLoc DL(N0);
4135     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4136                     DAG.getConstant(1, DL, V.getValueType()));
4137     AddToWorklist(V.getNode());
4138     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4139   }
4140 
4141   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4142   if (isOneConstant(N1) && VT == MVT::i1 &&
4143       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4144     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4145     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4146       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4147       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4148       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4149       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4150       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4151     }
4152   }
4153   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4154   if (isAllOnesConstant(N1) &&
4155       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4156     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4157     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4158       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4159       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4160       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4161       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4162       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4163     }
4164   }
4165   // fold (xor (and x, y), y) -> (and (not x), y)
4166   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4167       N0->getOperand(1) == N1) {
4168     SDValue X = N0->getOperand(0);
4169     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4170     AddToWorklist(NotX.getNode());
4171     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4172   }
4173   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4174   if (N1C && N0.getOpcode() == ISD::XOR) {
4175     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4176       SDLoc DL(N);
4177       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4178                          DAG.getConstant(N1C->getAPIntValue() ^
4179                                          N00C->getAPIntValue(), DL, VT));
4180     }
4181     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4182       SDLoc DL(N);
4183       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4184                          DAG.getConstant(N1C->getAPIntValue() ^
4185                                          N01C->getAPIntValue(), DL, VT));
4186     }
4187   }
4188   // fold (xor x, x) -> 0
4189   if (N0 == N1)
4190     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4191 
4192   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4193   // Here is a concrete example of this equivalence:
4194   // i16   x ==  14
4195   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4196   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4197   //
4198   // =>
4199   //
4200   // i16     ~1      == 0b1111111111111110
4201   // i16 rol(~1, 14) == 0b1011111111111111
4202   //
4203   // Some additional tips to help conceptualize this transform:
4204   // - Try to see the operation as placing a single zero in a value of all ones.
4205   // - There exists no value for x which would allow the result to contain zero.
4206   // - Values of x larger than the bitwidth are undefined and do not require a
4207   //   consistent result.
4208   // - Pushing the zero left requires shifting one bits in from the right.
4209   // A rotate left of ~1 is a nice way of achieving the desired result.
4210   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4211       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4212     SDLoc DL(N);
4213     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4214                        N0.getOperand(1));
4215   }
4216 
4217   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4218   if (N0.getOpcode() == N1.getOpcode())
4219     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4220       return Tmp;
4221 
4222   // Simplify the expression using non-local knowledge.
4223   if (!VT.isVector() &&
4224       SimplifyDemandedBits(SDValue(N, 0)))
4225     return SDValue(N, 0);
4226 
4227   return SDValue();
4228 }
4229 
4230 /// Handle transforms common to the three shifts, when the shift amount is a
4231 /// constant.
4232 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4233   SDNode *LHS = N->getOperand(0).getNode();
4234   if (!LHS->hasOneUse()) return SDValue();
4235 
4236   // We want to pull some binops through shifts, so that we have (and (shift))
4237   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4238   // thing happens with address calculations, so it's important to canonicalize
4239   // it.
4240   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4241 
4242   switch (LHS->getOpcode()) {
4243   default: return SDValue();
4244   case ISD::OR:
4245   case ISD::XOR:
4246     HighBitSet = false; // We can only transform sra if the high bit is clear.
4247     break;
4248   case ISD::AND:
4249     HighBitSet = true;  // We can only transform sra if the high bit is set.
4250     break;
4251   case ISD::ADD:
4252     if (N->getOpcode() != ISD::SHL)
4253       return SDValue(); // only shl(add) not sr[al](add).
4254     HighBitSet = false; // We can only transform sra if the high bit is clear.
4255     break;
4256   }
4257 
4258   // We require the RHS of the binop to be a constant and not opaque as well.
4259   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4260   if (!BinOpCst) return SDValue();
4261 
4262   // FIXME: disable this unless the input to the binop is a shift by a constant.
4263   // If it is not a shift, it pessimizes some common cases like:
4264   //
4265   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4266   //    int bar(int *X, int i) { return X[i & 255]; }
4267   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4268   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4269        BinOpLHSVal->getOpcode() != ISD::SRA &&
4270        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4271       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4272     return SDValue();
4273 
4274   EVT VT = N->getValueType(0);
4275 
4276   // If this is a signed shift right, and the high bit is modified by the
4277   // logical operation, do not perform the transformation. The highBitSet
4278   // boolean indicates the value of the high bit of the constant which would
4279   // cause it to be modified for this operation.
4280   if (N->getOpcode() == ISD::SRA) {
4281     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4282     if (BinOpRHSSignSet != HighBitSet)
4283       return SDValue();
4284   }
4285 
4286   if (!TLI.isDesirableToCommuteWithShift(LHS))
4287     return SDValue();
4288 
4289   // Fold the constants, shifting the binop RHS by the shift amount.
4290   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4291                                N->getValueType(0),
4292                                LHS->getOperand(1), N->getOperand(1));
4293   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4294 
4295   // Create the new shift.
4296   SDValue NewShift = DAG.getNode(N->getOpcode(),
4297                                  SDLoc(LHS->getOperand(0)),
4298                                  VT, LHS->getOperand(0), N->getOperand(1));
4299 
4300   // Create the new binop.
4301   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4302 }
4303 
4304 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4305   assert(N->getOpcode() == ISD::TRUNCATE);
4306   assert(N->getOperand(0).getOpcode() == ISD::AND);
4307 
4308   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4309   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4310     SDValue N01 = N->getOperand(0).getOperand(1);
4311 
4312     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4313       if (!N01C->isOpaque()) {
4314         EVT TruncVT = N->getValueType(0);
4315         SDValue N00 = N->getOperand(0).getOperand(0);
4316         APInt TruncC = N01C->getAPIntValue();
4317         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4318         SDLoc DL(N);
4319 
4320         return DAG.getNode(ISD::AND, DL, TruncVT,
4321                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4322                            DAG.getConstant(TruncC, DL, TruncVT));
4323       }
4324     }
4325   }
4326 
4327   return SDValue();
4328 }
4329 
4330 SDValue DAGCombiner::visitRotate(SDNode *N) {
4331   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4332   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4333       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4334     if (SDValue NewOp1 =
4335             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4336       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4337                          N->getOperand(0), NewOp1);
4338   }
4339   return SDValue();
4340 }
4341 
4342 SDValue DAGCombiner::visitSHL(SDNode *N) {
4343   SDValue N0 = N->getOperand(0);
4344   SDValue N1 = N->getOperand(1);
4345   EVT VT = N0.getValueType();
4346   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4347 
4348   // fold vector ops
4349   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4350   if (VT.isVector()) {
4351     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4352       return FoldedVOp;
4353 
4354     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4355     // If setcc produces all-one true value then:
4356     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4357     if (N1CV && N1CV->isConstant()) {
4358       if (N0.getOpcode() == ISD::AND) {
4359         SDValue N00 = N0->getOperand(0);
4360         SDValue N01 = N0->getOperand(1);
4361         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4362 
4363         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4364             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4365                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4366           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4367                                                      N01CV, N1CV))
4368             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4369         }
4370       } else {
4371         N1C = isConstOrConstSplat(N1);
4372       }
4373     }
4374   }
4375 
4376   // fold (shl c1, c2) -> c1<<c2
4377   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4378   if (N0C && N1C && !N1C->isOpaque())
4379     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4380   // fold (shl 0, x) -> 0
4381   if (isNullConstant(N0))
4382     return N0;
4383   // fold (shl x, c >= size(x)) -> undef
4384   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4385     return DAG.getUNDEF(VT);
4386   // fold (shl x, 0) -> x
4387   if (N1C && N1C->isNullValue())
4388     return N0;
4389   // fold (shl undef, x) -> 0
4390   if (N0.getOpcode() == ISD::UNDEF)
4391     return DAG.getConstant(0, SDLoc(N), VT);
4392   // if (shl x, c) is known to be zero, return 0
4393   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4394                             APInt::getAllOnesValue(OpSizeInBits)))
4395     return DAG.getConstant(0, SDLoc(N), VT);
4396   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4397   if (N1.getOpcode() == ISD::TRUNCATE &&
4398       N1.getOperand(0).getOpcode() == ISD::AND) {
4399     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4400       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4401   }
4402 
4403   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4404     return SDValue(N, 0);
4405 
4406   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4407   if (N1C && N0.getOpcode() == ISD::SHL) {
4408     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4409       uint64_t c1 = N0C1->getZExtValue();
4410       uint64_t c2 = N1C->getZExtValue();
4411       SDLoc DL(N);
4412       if (c1 + c2 >= OpSizeInBits)
4413         return DAG.getConstant(0, DL, VT);
4414       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4415                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4416     }
4417   }
4418 
4419   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4420   // For this to be valid, the second form must not preserve any of the bits
4421   // that are shifted out by the inner shift in the first form.  This means
4422   // the outer shift size must be >= the number of bits added by the ext.
4423   // As a corollary, we don't care what kind of ext it is.
4424   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4425               N0.getOpcode() == ISD::ANY_EXTEND ||
4426               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4427       N0.getOperand(0).getOpcode() == ISD::SHL) {
4428     SDValue N0Op0 = N0.getOperand(0);
4429     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4430       uint64_t c1 = N0Op0C1->getZExtValue();
4431       uint64_t c2 = N1C->getZExtValue();
4432       EVT InnerShiftVT = N0Op0.getValueType();
4433       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4434       if (c2 >= OpSizeInBits - InnerShiftSize) {
4435         SDLoc DL(N0);
4436         if (c1 + c2 >= OpSizeInBits)
4437           return DAG.getConstant(0, DL, VT);
4438         return DAG.getNode(ISD::SHL, DL, VT,
4439                            DAG.getNode(N0.getOpcode(), DL, VT,
4440                                        N0Op0->getOperand(0)),
4441                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4442       }
4443     }
4444   }
4445 
4446   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4447   // Only fold this if the inner zext has no other uses to avoid increasing
4448   // the total number of instructions.
4449   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4450       N0.getOperand(0).getOpcode() == ISD::SRL) {
4451     SDValue N0Op0 = N0.getOperand(0);
4452     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4453       uint64_t c1 = N0Op0C1->getZExtValue();
4454       if (c1 < VT.getScalarSizeInBits()) {
4455         uint64_t c2 = N1C->getZExtValue();
4456         if (c1 == c2) {
4457           SDValue NewOp0 = N0.getOperand(0);
4458           EVT CountVT = NewOp0.getOperand(1).getValueType();
4459           SDLoc DL(N);
4460           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4461                                        NewOp0,
4462                                        DAG.getConstant(c2, DL, CountVT));
4463           AddToWorklist(NewSHL.getNode());
4464           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4465         }
4466       }
4467     }
4468   }
4469 
4470   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4471   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4472   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4473       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4474     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4475       uint64_t C1 = N0C1->getZExtValue();
4476       uint64_t C2 = N1C->getZExtValue();
4477       SDLoc DL(N);
4478       if (C1 <= C2)
4479         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4480                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4481       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4482                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4483     }
4484   }
4485 
4486   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4487   //                               (and (srl x, (sub c1, c2), MASK)
4488   // Only fold this if the inner shift has no other uses -- if it does, folding
4489   // this will increase the total number of instructions.
4490   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4491     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4492       uint64_t c1 = N0C1->getZExtValue();
4493       if (c1 < OpSizeInBits) {
4494         uint64_t c2 = N1C->getZExtValue();
4495         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4496         SDValue Shift;
4497         if (c2 > c1) {
4498           Mask = Mask.shl(c2 - c1);
4499           SDLoc DL(N);
4500           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4501                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4502         } else {
4503           Mask = Mask.lshr(c1 - c2);
4504           SDLoc DL(N);
4505           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4506                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4507         }
4508         SDLoc DL(N0);
4509         return DAG.getNode(ISD::AND, DL, VT, Shift,
4510                            DAG.getConstant(Mask, DL, VT));
4511       }
4512     }
4513   }
4514   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4515   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4516     unsigned BitSize = VT.getScalarSizeInBits();
4517     SDLoc DL(N);
4518     SDValue HiBitsMask =
4519       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4520                                             BitSize - N1C->getZExtValue()),
4521                       DL, VT);
4522     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4523                        HiBitsMask);
4524   }
4525 
4526   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4527   // Variant of version done on multiply, except mul by a power of 2 is turned
4528   // into a shift.
4529   APInt Val;
4530   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4531       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4532        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4533     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4534     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4535     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4536   }
4537 
4538   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4539   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4540     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4541       if (SDValue Folded =
4542               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4543         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4544     }
4545   }
4546 
4547   if (N1C && !N1C->isOpaque())
4548     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4549       return NewSHL;
4550 
4551   return SDValue();
4552 }
4553 
4554 SDValue DAGCombiner::visitSRA(SDNode *N) {
4555   SDValue N0 = N->getOperand(0);
4556   SDValue N1 = N->getOperand(1);
4557   EVT VT = N0.getValueType();
4558   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4559 
4560   // fold vector ops
4561   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4562   if (VT.isVector()) {
4563     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4564       return FoldedVOp;
4565 
4566     N1C = isConstOrConstSplat(N1);
4567   }
4568 
4569   // fold (sra c1, c2) -> (sra c1, c2)
4570   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4571   if (N0C && N1C && !N1C->isOpaque())
4572     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4573   // fold (sra 0, x) -> 0
4574   if (isNullConstant(N0))
4575     return N0;
4576   // fold (sra -1, x) -> -1
4577   if (isAllOnesConstant(N0))
4578     return N0;
4579   // fold (sra x, (setge c, size(x))) -> undef
4580   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4581     return DAG.getUNDEF(VT);
4582   // fold (sra x, 0) -> x
4583   if (N1C && N1C->isNullValue())
4584     return N0;
4585   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4586   // sext_inreg.
4587   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4588     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4589     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4590     if (VT.isVector())
4591       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4592                                ExtVT, VT.getVectorNumElements());
4593     if ((!LegalOperations ||
4594          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4595       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4596                          N0.getOperand(0), DAG.getValueType(ExtVT));
4597   }
4598 
4599   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4600   if (N1C && N0.getOpcode() == ISD::SRA) {
4601     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4602       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4603       if (Sum >= OpSizeInBits)
4604         Sum = OpSizeInBits - 1;
4605       SDLoc DL(N);
4606       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4607                          DAG.getConstant(Sum, DL, N1.getValueType()));
4608     }
4609   }
4610 
4611   // fold (sra (shl X, m), (sub result_size, n))
4612   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4613   // result_size - n != m.
4614   // If truncate is free for the target sext(shl) is likely to result in better
4615   // code.
4616   if (N0.getOpcode() == ISD::SHL && N1C) {
4617     // Get the two constanst of the shifts, CN0 = m, CN = n.
4618     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4619     if (N01C) {
4620       LLVMContext &Ctx = *DAG.getContext();
4621       // Determine what the truncate's result bitsize and type would be.
4622       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4623 
4624       if (VT.isVector())
4625         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4626 
4627       // Determine the residual right-shift amount.
4628       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4629 
4630       // If the shift is not a no-op (in which case this should be just a sign
4631       // extend already), the truncated to type is legal, sign_extend is legal
4632       // on that type, and the truncate to that type is both legal and free,
4633       // perform the transform.
4634       if ((ShiftAmt > 0) &&
4635           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4636           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4637           TLI.isTruncateFree(VT, TruncVT)) {
4638 
4639         SDLoc DL(N);
4640         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4641             getShiftAmountTy(N0.getOperand(0).getValueType()));
4642         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4643                                     N0.getOperand(0), Amt);
4644         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4645                                     Shift);
4646         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4647                            N->getValueType(0), Trunc);
4648       }
4649     }
4650   }
4651 
4652   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4653   if (N1.getOpcode() == ISD::TRUNCATE &&
4654       N1.getOperand(0).getOpcode() == ISD::AND) {
4655     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4656       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4657   }
4658 
4659   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4660   //      if c1 is equal to the number of bits the trunc removes
4661   if (N0.getOpcode() == ISD::TRUNCATE &&
4662       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4663        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4664       N0.getOperand(0).hasOneUse() &&
4665       N0.getOperand(0).getOperand(1).hasOneUse() &&
4666       N1C) {
4667     SDValue N0Op0 = N0.getOperand(0);
4668     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4669       unsigned LargeShiftVal = LargeShift->getZExtValue();
4670       EVT LargeVT = N0Op0.getValueType();
4671 
4672       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4673         SDLoc DL(N);
4674         SDValue Amt =
4675           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4676                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4677         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4678                                   N0Op0.getOperand(0), Amt);
4679         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4680       }
4681     }
4682   }
4683 
4684   // Simplify, based on bits shifted out of the LHS.
4685   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4686     return SDValue(N, 0);
4687 
4688 
4689   // If the sign bit is known to be zero, switch this to a SRL.
4690   if (DAG.SignBitIsZero(N0))
4691     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4692 
4693   if (N1C && !N1C->isOpaque())
4694     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4695       return NewSRA;
4696 
4697   return SDValue();
4698 }
4699 
4700 SDValue DAGCombiner::visitSRL(SDNode *N) {
4701   SDValue N0 = N->getOperand(0);
4702   SDValue N1 = N->getOperand(1);
4703   EVT VT = N0.getValueType();
4704   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4705 
4706   // fold vector ops
4707   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4708   if (VT.isVector()) {
4709     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4710       return FoldedVOp;
4711 
4712     N1C = isConstOrConstSplat(N1);
4713   }
4714 
4715   // fold (srl c1, c2) -> c1 >>u c2
4716   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4717   if (N0C && N1C && !N1C->isOpaque())
4718     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4719   // fold (srl 0, x) -> 0
4720   if (isNullConstant(N0))
4721     return N0;
4722   // fold (srl x, c >= size(x)) -> undef
4723   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4724     return DAG.getUNDEF(VT);
4725   // fold (srl x, 0) -> x
4726   if (N1C && N1C->isNullValue())
4727     return N0;
4728   // if (srl x, c) is known to be zero, return 0
4729   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4730                                    APInt::getAllOnesValue(OpSizeInBits)))
4731     return DAG.getConstant(0, SDLoc(N), VT);
4732 
4733   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4734   if (N1C && N0.getOpcode() == ISD::SRL) {
4735     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4736       uint64_t c1 = N01C->getZExtValue();
4737       uint64_t c2 = N1C->getZExtValue();
4738       SDLoc DL(N);
4739       if (c1 + c2 >= OpSizeInBits)
4740         return DAG.getConstant(0, DL, VT);
4741       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4742                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4743     }
4744   }
4745 
4746   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4747   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4748       N0.getOperand(0).getOpcode() == ISD::SRL &&
4749       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4750     uint64_t c1 =
4751       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4752     uint64_t c2 = N1C->getZExtValue();
4753     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4754     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4755     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4756     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4757     if (c1 + OpSizeInBits == InnerShiftSize) {
4758       SDLoc DL(N0);
4759       if (c1 + c2 >= InnerShiftSize)
4760         return DAG.getConstant(0, DL, VT);
4761       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4762                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4763                                      N0.getOperand(0)->getOperand(0),
4764                                      DAG.getConstant(c1 + c2, DL,
4765                                                      ShiftCountVT)));
4766     }
4767   }
4768 
4769   // fold (srl (shl x, c), c) -> (and x, cst2)
4770   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4771     unsigned BitSize = N0.getScalarValueSizeInBits();
4772     if (BitSize <= 64) {
4773       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4774       SDLoc DL(N);
4775       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4776                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4777     }
4778   }
4779 
4780   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4781   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4782     // Shifting in all undef bits?
4783     EVT SmallVT = N0.getOperand(0).getValueType();
4784     unsigned BitSize = SmallVT.getScalarSizeInBits();
4785     if (N1C->getZExtValue() >= BitSize)
4786       return DAG.getUNDEF(VT);
4787 
4788     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4789       uint64_t ShiftAmt = N1C->getZExtValue();
4790       SDLoc DL0(N0);
4791       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4792                                        N0.getOperand(0),
4793                           DAG.getConstant(ShiftAmt, DL0,
4794                                           getShiftAmountTy(SmallVT)));
4795       AddToWorklist(SmallShift.getNode());
4796       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4797       SDLoc DL(N);
4798       return DAG.getNode(ISD::AND, DL, VT,
4799                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4800                          DAG.getConstant(Mask, DL, VT));
4801     }
4802   }
4803 
4804   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4805   // bit, which is unmodified by sra.
4806   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4807     if (N0.getOpcode() == ISD::SRA)
4808       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4809   }
4810 
4811   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4812   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4813       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4814     APInt KnownZero, KnownOne;
4815     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4816 
4817     // If any of the input bits are KnownOne, then the input couldn't be all
4818     // zeros, thus the result of the srl will always be zero.
4819     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4820 
4821     // If all of the bits input the to ctlz node are known to be zero, then
4822     // the result of the ctlz is "32" and the result of the shift is one.
4823     APInt UnknownBits = ~KnownZero;
4824     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4825 
4826     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4827     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4828       // Okay, we know that only that the single bit specified by UnknownBits
4829       // could be set on input to the CTLZ node. If this bit is set, the SRL
4830       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4831       // to an SRL/XOR pair, which is likely to simplify more.
4832       unsigned ShAmt = UnknownBits.countTrailingZeros();
4833       SDValue Op = N0.getOperand(0);
4834 
4835       if (ShAmt) {
4836         SDLoc DL(N0);
4837         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4838                   DAG.getConstant(ShAmt, DL,
4839                                   getShiftAmountTy(Op.getValueType())));
4840         AddToWorklist(Op.getNode());
4841       }
4842 
4843       SDLoc DL(N);
4844       return DAG.getNode(ISD::XOR, DL, VT,
4845                          Op, DAG.getConstant(1, DL, VT));
4846     }
4847   }
4848 
4849   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4850   if (N1.getOpcode() == ISD::TRUNCATE &&
4851       N1.getOperand(0).getOpcode() == ISD::AND) {
4852     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4853       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4854   }
4855 
4856   // fold operands of srl based on knowledge that the low bits are not
4857   // demanded.
4858   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4859     return SDValue(N, 0);
4860 
4861   if (N1C && !N1C->isOpaque())
4862     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4863       return NewSRL;
4864 
4865   // Attempt to convert a srl of a load into a narrower zero-extending load.
4866   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4867     return NarrowLoad;
4868 
4869   // Here is a common situation. We want to optimize:
4870   //
4871   //   %a = ...
4872   //   %b = and i32 %a, 2
4873   //   %c = srl i32 %b, 1
4874   //   brcond i32 %c ...
4875   //
4876   // into
4877   //
4878   //   %a = ...
4879   //   %b = and %a, 2
4880   //   %c = setcc eq %b, 0
4881   //   brcond %c ...
4882   //
4883   // However when after the source operand of SRL is optimized into AND, the SRL
4884   // itself may not be optimized further. Look for it and add the BRCOND into
4885   // the worklist.
4886   if (N->hasOneUse()) {
4887     SDNode *Use = *N->use_begin();
4888     if (Use->getOpcode() == ISD::BRCOND)
4889       AddToWorklist(Use);
4890     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4891       // Also look pass the truncate.
4892       Use = *Use->use_begin();
4893       if (Use->getOpcode() == ISD::BRCOND)
4894         AddToWorklist(Use);
4895     }
4896   }
4897 
4898   return SDValue();
4899 }
4900 
4901 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4902   SDValue N0 = N->getOperand(0);
4903   EVT VT = N->getValueType(0);
4904 
4905   // fold (bswap c1) -> c2
4906   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4907     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4908   // fold (bswap (bswap x)) -> x
4909   if (N0.getOpcode() == ISD::BSWAP)
4910     return N0->getOperand(0);
4911   return SDValue();
4912 }
4913 
4914 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4915   SDValue N0 = N->getOperand(0);
4916   EVT VT = N->getValueType(0);
4917 
4918   // fold (ctlz c1) -> c2
4919   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4920     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4921   return SDValue();
4922 }
4923 
4924 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4925   SDValue N0 = N->getOperand(0);
4926   EVT VT = N->getValueType(0);
4927 
4928   // fold (ctlz_zero_undef c1) -> c2
4929   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4930     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4931   return SDValue();
4932 }
4933 
4934 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4935   SDValue N0 = N->getOperand(0);
4936   EVT VT = N->getValueType(0);
4937 
4938   // fold (cttz c1) -> c2
4939   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4940     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4941   return SDValue();
4942 }
4943 
4944 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4945   SDValue N0 = N->getOperand(0);
4946   EVT VT = N->getValueType(0);
4947 
4948   // fold (cttz_zero_undef c1) -> c2
4949   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4950     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4951   return SDValue();
4952 }
4953 
4954 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4955   SDValue N0 = N->getOperand(0);
4956   EVT VT = N->getValueType(0);
4957 
4958   // fold (ctpop c1) -> c2
4959   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4960     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4961   return SDValue();
4962 }
4963 
4964 
4965 /// \brief Generate Min/Max node
4966 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4967                                    SDValue True, SDValue False,
4968                                    ISD::CondCode CC, const TargetLowering &TLI,
4969                                    SelectionDAG &DAG) {
4970   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4971     return SDValue();
4972 
4973   switch (CC) {
4974   case ISD::SETOLT:
4975   case ISD::SETOLE:
4976   case ISD::SETLT:
4977   case ISD::SETLE:
4978   case ISD::SETULT:
4979   case ISD::SETULE: {
4980     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4981     if (TLI.isOperationLegal(Opcode, VT))
4982       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4983     return SDValue();
4984   }
4985   case ISD::SETOGT:
4986   case ISD::SETOGE:
4987   case ISD::SETGT:
4988   case ISD::SETGE:
4989   case ISD::SETUGT:
4990   case ISD::SETUGE: {
4991     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4992     if (TLI.isOperationLegal(Opcode, VT))
4993       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4994     return SDValue();
4995   }
4996   default:
4997     return SDValue();
4998   }
4999 }
5000 
5001 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5002   SDValue N0 = N->getOperand(0);
5003   SDValue N1 = N->getOperand(1);
5004   SDValue N2 = N->getOperand(2);
5005   EVT VT = N->getValueType(0);
5006   EVT VT0 = N0.getValueType();
5007 
5008   // fold (select C, X, X) -> X
5009   if (N1 == N2)
5010     return N1;
5011   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5012     // fold (select true, X, Y) -> X
5013     // fold (select false, X, Y) -> Y
5014     return !N0C->isNullValue() ? N1 : N2;
5015   }
5016   // fold (select C, 1, X) -> (or C, X)
5017   if (VT == MVT::i1 && isOneConstant(N1))
5018     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5019   // fold (select C, 0, 1) -> (xor C, 1)
5020   // We can't do this reliably if integer based booleans have different contents
5021   // to floating point based booleans. This is because we can't tell whether we
5022   // have an integer-based boolean or a floating-point-based boolean unless we
5023   // can find the SETCC that produced it and inspect its operands. This is
5024   // fairly easy if C is the SETCC node, but it can potentially be
5025   // undiscoverable (or not reasonably discoverable). For example, it could be
5026   // in another basic block or it could require searching a complicated
5027   // expression.
5028   if (VT.isInteger() &&
5029       (VT0 == MVT::i1 || (VT0.isInteger() &&
5030                           TLI.getBooleanContents(false, false) ==
5031                               TLI.getBooleanContents(false, true) &&
5032                           TLI.getBooleanContents(false, false) ==
5033                               TargetLowering::ZeroOrOneBooleanContent)) &&
5034       isNullConstant(N1) && isOneConstant(N2)) {
5035     SDValue XORNode;
5036     if (VT == VT0) {
5037       SDLoc DL(N);
5038       return DAG.getNode(ISD::XOR, DL, VT0,
5039                          N0, DAG.getConstant(1, DL, VT0));
5040     }
5041     SDLoc DL0(N0);
5042     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5043                           N0, DAG.getConstant(1, DL0, VT0));
5044     AddToWorklist(XORNode.getNode());
5045     if (VT.bitsGT(VT0))
5046       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5047     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5048   }
5049   // fold (select C, 0, X) -> (and (not C), X)
5050   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5051     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5052     AddToWorklist(NOTNode.getNode());
5053     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5054   }
5055   // fold (select C, X, 1) -> (or (not C), X)
5056   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5057     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5058     AddToWorklist(NOTNode.getNode());
5059     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5060   }
5061   // fold (select C, X, 0) -> (and C, X)
5062   if (VT == MVT::i1 && isNullConstant(N2))
5063     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5064   // fold (select X, X, Y) -> (or X, Y)
5065   // fold (select X, 1, Y) -> (or X, Y)
5066   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5067     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5068   // fold (select X, Y, X) -> (and X, Y)
5069   // fold (select X, Y, 0) -> (and X, Y)
5070   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5071     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5072 
5073   // If we can fold this based on the true/false value, do so.
5074   if (SimplifySelectOps(N, N1, N2))
5075     return SDValue(N, 0);  // Don't revisit N.
5076 
5077   if (VT0 == MVT::i1) {
5078     // The code in this block deals with the following 2 equivalences:
5079     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5080     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5081     // The target can specify its prefered form with the
5082     // shouldNormalizeToSelectSequence() callback. However we always transform
5083     // to the right anyway if we find the inner select exists in the DAG anyway
5084     // and we always transform to the left side if we know that we can further
5085     // optimize the combination of the conditions.
5086     bool normalizeToSequence
5087       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5088     // select (and Cond0, Cond1), X, Y
5089     //   -> select Cond0, (select Cond1, X, Y), Y
5090     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5091       SDValue Cond0 = N0->getOperand(0);
5092       SDValue Cond1 = N0->getOperand(1);
5093       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5094                                         N1.getValueType(), Cond1, N1, N2);
5095       if (normalizeToSequence || !InnerSelect.use_empty())
5096         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5097                            InnerSelect, N2);
5098     }
5099     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5100     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5101       SDValue Cond0 = N0->getOperand(0);
5102       SDValue Cond1 = N0->getOperand(1);
5103       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5104                                         N1.getValueType(), Cond1, N1, N2);
5105       if (normalizeToSequence || !InnerSelect.use_empty())
5106         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5107                            InnerSelect);
5108     }
5109 
5110     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5111     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5112       SDValue N1_0 = N1->getOperand(0);
5113       SDValue N1_1 = N1->getOperand(1);
5114       SDValue N1_2 = N1->getOperand(2);
5115       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5116         // Create the actual and node if we can generate good code for it.
5117         if (!normalizeToSequence) {
5118           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5119                                     N0, N1_0);
5120           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5121                              N1_1, N2);
5122         }
5123         // Otherwise see if we can optimize the "and" to a better pattern.
5124         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5125           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5126                              N1_1, N2);
5127       }
5128     }
5129     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5130     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5131       SDValue N2_0 = N2->getOperand(0);
5132       SDValue N2_1 = N2->getOperand(1);
5133       SDValue N2_2 = N2->getOperand(2);
5134       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5135         // Create the actual or node if we can generate good code for it.
5136         if (!normalizeToSequence) {
5137           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5138                                    N0, N2_0);
5139           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5140                              N1, N2_2);
5141         }
5142         // Otherwise see if we can optimize to a better pattern.
5143         if (SDValue Combined = visitORLike(N0, N2_0, N))
5144           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5145                              N1, N2_2);
5146       }
5147     }
5148   }
5149 
5150   // fold selects based on a setcc into other things, such as min/max/abs
5151   if (N0.getOpcode() == ISD::SETCC) {
5152     // select x, y (fcmp lt x, y) -> fminnum x, y
5153     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5154     //
5155     // This is OK if we don't care about what happens if either operand is a
5156     // NaN.
5157     //
5158 
5159     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5160     // no signed zeros as well as no nans.
5161     const TargetOptions &Options = DAG.getTarget().Options;
5162     if (Options.UnsafeFPMath &&
5163         VT.isFloatingPoint() && N0.hasOneUse() &&
5164         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5165       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5166 
5167       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5168                                                 N0.getOperand(1), N1, N2, CC,
5169                                                 TLI, DAG))
5170         return FMinMax;
5171     }
5172 
5173     if ((!LegalOperations &&
5174          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5175         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5176       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5177                          N0.getOperand(0), N0.getOperand(1),
5178                          N1, N2, N0.getOperand(2));
5179     return SimplifySelect(SDLoc(N), N0, N1, N2);
5180   }
5181 
5182   return SDValue();
5183 }
5184 
5185 static
5186 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5187   SDLoc DL(N);
5188   EVT LoVT, HiVT;
5189   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5190 
5191   // Split the inputs.
5192   SDValue Lo, Hi, LL, LH, RL, RH;
5193   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5194   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5195 
5196   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5197   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5198 
5199   return std::make_pair(Lo, Hi);
5200 }
5201 
5202 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5203 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5204 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5205   SDLoc dl(N);
5206   SDValue Cond = N->getOperand(0);
5207   SDValue LHS = N->getOperand(1);
5208   SDValue RHS = N->getOperand(2);
5209   EVT VT = N->getValueType(0);
5210   int NumElems = VT.getVectorNumElements();
5211   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5212          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5213          Cond.getOpcode() == ISD::BUILD_VECTOR);
5214 
5215   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5216   // binary ones here.
5217   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5218     return SDValue();
5219 
5220   // We're sure we have an even number of elements due to the
5221   // concat_vectors we have as arguments to vselect.
5222   // Skip BV elements until we find one that's not an UNDEF
5223   // After we find an UNDEF element, keep looping until we get to half the
5224   // length of the BV and see if all the non-undef nodes are the same.
5225   ConstantSDNode *BottomHalf = nullptr;
5226   for (int i = 0; i < NumElems / 2; ++i) {
5227     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5228       continue;
5229 
5230     if (BottomHalf == nullptr)
5231       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5232     else if (Cond->getOperand(i).getNode() != BottomHalf)
5233       return SDValue();
5234   }
5235 
5236   // Do the same for the second half of the BuildVector
5237   ConstantSDNode *TopHalf = nullptr;
5238   for (int i = NumElems / 2; i < NumElems; ++i) {
5239     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5240       continue;
5241 
5242     if (TopHalf == nullptr)
5243       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5244     else if (Cond->getOperand(i).getNode() != TopHalf)
5245       return SDValue();
5246   }
5247 
5248   assert(TopHalf && BottomHalf &&
5249          "One half of the selector was all UNDEFs and the other was all the "
5250          "same value. This should have been addressed before this function.");
5251   return DAG.getNode(
5252       ISD::CONCAT_VECTORS, dl, VT,
5253       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5254       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5255 }
5256 
5257 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5258 
5259   if (Level >= AfterLegalizeTypes)
5260     return SDValue();
5261 
5262   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5263   SDValue Mask = MSC->getMask();
5264   SDValue Data  = MSC->getValue();
5265   SDLoc DL(N);
5266 
5267   // If the MSCATTER data type requires splitting and the mask is provided by a
5268   // SETCC, then split both nodes and its operands before legalization. This
5269   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5270   // and enables future optimizations (e.g. min/max pattern matching on X86).
5271   if (Mask.getOpcode() != ISD::SETCC)
5272     return SDValue();
5273 
5274   // Check if any splitting is required.
5275   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5276       TargetLowering::TypeSplitVector)
5277     return SDValue();
5278   SDValue MaskLo, MaskHi, Lo, Hi;
5279   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5280 
5281   EVT LoVT, HiVT;
5282   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5283 
5284   SDValue Chain = MSC->getChain();
5285 
5286   EVT MemoryVT = MSC->getMemoryVT();
5287   unsigned Alignment = MSC->getOriginalAlignment();
5288 
5289   EVT LoMemVT, HiMemVT;
5290   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5291 
5292   SDValue DataLo, DataHi;
5293   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5294 
5295   SDValue BasePtr = MSC->getBasePtr();
5296   SDValue IndexLo, IndexHi;
5297   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5298 
5299   MachineMemOperand *MMO = DAG.getMachineFunction().
5300     getMachineMemOperand(MSC->getPointerInfo(),
5301                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5302                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5303 
5304   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5305   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5306                             DL, OpsLo, MMO);
5307 
5308   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5309   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5310                             DL, OpsHi, MMO);
5311 
5312   AddToWorklist(Lo.getNode());
5313   AddToWorklist(Hi.getNode());
5314 
5315   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5316 }
5317 
5318 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5319 
5320   if (Level >= AfterLegalizeTypes)
5321     return SDValue();
5322 
5323   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5324   SDValue Mask = MST->getMask();
5325   SDValue Data  = MST->getValue();
5326   SDLoc DL(N);
5327 
5328   // If the MSTORE data type requires splitting and the mask is provided by a
5329   // SETCC, then split both nodes and its operands before legalization. This
5330   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5331   // and enables future optimizations (e.g. min/max pattern matching on X86).
5332   if (Mask.getOpcode() == ISD::SETCC) {
5333 
5334     // Check if any splitting is required.
5335     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5336         TargetLowering::TypeSplitVector)
5337       return SDValue();
5338 
5339     SDValue MaskLo, MaskHi, Lo, Hi;
5340     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5341 
5342     EVT LoVT, HiVT;
5343     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5344 
5345     SDValue Chain = MST->getChain();
5346     SDValue Ptr   = MST->getBasePtr();
5347 
5348     EVT MemoryVT = MST->getMemoryVT();
5349     unsigned Alignment = MST->getOriginalAlignment();
5350 
5351     // if Alignment is equal to the vector size,
5352     // take the half of it for the second part
5353     unsigned SecondHalfAlignment =
5354       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5355          Alignment/2 : Alignment;
5356 
5357     EVT LoMemVT, HiMemVT;
5358     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5359 
5360     SDValue DataLo, DataHi;
5361     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5362 
5363     MachineMemOperand *MMO = DAG.getMachineFunction().
5364       getMachineMemOperand(MST->getPointerInfo(),
5365                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5366                            Alignment, MST->getAAInfo(), MST->getRanges());
5367 
5368     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5369                             MST->isTruncatingStore());
5370 
5371     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5372     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5373                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5374 
5375     MMO = DAG.getMachineFunction().
5376       getMachineMemOperand(MST->getPointerInfo(),
5377                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5378                            SecondHalfAlignment, MST->getAAInfo(),
5379                            MST->getRanges());
5380 
5381     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5382                             MST->isTruncatingStore());
5383 
5384     AddToWorklist(Lo.getNode());
5385     AddToWorklist(Hi.getNode());
5386 
5387     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5388   }
5389   return SDValue();
5390 }
5391 
5392 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5393 
5394   if (Level >= AfterLegalizeTypes)
5395     return SDValue();
5396 
5397   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5398   SDValue Mask = MGT->getMask();
5399   SDLoc DL(N);
5400 
5401   // If the MGATHER result requires splitting and the mask is provided by a
5402   // SETCC, then split both nodes and its operands before legalization. This
5403   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5404   // and enables future optimizations (e.g. min/max pattern matching on X86).
5405 
5406   if (Mask.getOpcode() != ISD::SETCC)
5407     return SDValue();
5408 
5409   EVT VT = N->getValueType(0);
5410 
5411   // Check if any splitting is required.
5412   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5413       TargetLowering::TypeSplitVector)
5414     return SDValue();
5415 
5416   SDValue MaskLo, MaskHi, Lo, Hi;
5417   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5418 
5419   SDValue Src0 = MGT->getValue();
5420   SDValue Src0Lo, Src0Hi;
5421   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5422 
5423   EVT LoVT, HiVT;
5424   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5425 
5426   SDValue Chain = MGT->getChain();
5427   EVT MemoryVT = MGT->getMemoryVT();
5428   unsigned Alignment = MGT->getOriginalAlignment();
5429 
5430   EVT LoMemVT, HiMemVT;
5431   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5432 
5433   SDValue BasePtr = MGT->getBasePtr();
5434   SDValue Index = MGT->getIndex();
5435   SDValue IndexLo, IndexHi;
5436   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5437 
5438   MachineMemOperand *MMO = DAG.getMachineFunction().
5439     getMachineMemOperand(MGT->getPointerInfo(),
5440                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5441                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5442 
5443   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5444   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5445                             MMO);
5446 
5447   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5448   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5449                             MMO);
5450 
5451   AddToWorklist(Lo.getNode());
5452   AddToWorklist(Hi.getNode());
5453 
5454   // Build a factor node to remember that this load is independent of the
5455   // other one.
5456   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5457                       Hi.getValue(1));
5458 
5459   // Legalized the chain result - switch anything that used the old chain to
5460   // use the new one.
5461   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5462 
5463   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5464 
5465   SDValue RetOps[] = { GatherRes, Chain };
5466   return DAG.getMergeValues(RetOps, DL);
5467 }
5468 
5469 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5470 
5471   if (Level >= AfterLegalizeTypes)
5472     return SDValue();
5473 
5474   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5475   SDValue Mask = MLD->getMask();
5476   SDLoc DL(N);
5477 
5478   // If the MLOAD result requires splitting and the mask is provided by a
5479   // SETCC, then split both nodes and its operands before legalization. This
5480   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5481   // and enables future optimizations (e.g. min/max pattern matching on X86).
5482 
5483   if (Mask.getOpcode() == ISD::SETCC) {
5484     EVT VT = N->getValueType(0);
5485 
5486     // Check if any splitting is required.
5487     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5488         TargetLowering::TypeSplitVector)
5489       return SDValue();
5490 
5491     SDValue MaskLo, MaskHi, Lo, Hi;
5492     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5493 
5494     SDValue Src0 = MLD->getSrc0();
5495     SDValue Src0Lo, Src0Hi;
5496     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5497 
5498     EVT LoVT, HiVT;
5499     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5500 
5501     SDValue Chain = MLD->getChain();
5502     SDValue Ptr   = MLD->getBasePtr();
5503     EVT MemoryVT = MLD->getMemoryVT();
5504     unsigned Alignment = MLD->getOriginalAlignment();
5505 
5506     // if Alignment is equal to the vector size,
5507     // take the half of it for the second part
5508     unsigned SecondHalfAlignment =
5509       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5510          Alignment/2 : Alignment;
5511 
5512     EVT LoMemVT, HiMemVT;
5513     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5514 
5515     MachineMemOperand *MMO = DAG.getMachineFunction().
5516     getMachineMemOperand(MLD->getPointerInfo(),
5517                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5518                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5519 
5520     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5521                            ISD::NON_EXTLOAD);
5522 
5523     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5524     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5525                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5526 
5527     MMO = DAG.getMachineFunction().
5528     getMachineMemOperand(MLD->getPointerInfo(),
5529                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5530                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5531 
5532     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5533                            ISD::NON_EXTLOAD);
5534 
5535     AddToWorklist(Lo.getNode());
5536     AddToWorklist(Hi.getNode());
5537 
5538     // Build a factor node to remember that this load is independent of the
5539     // other one.
5540     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5541                         Hi.getValue(1));
5542 
5543     // Legalized the chain result - switch anything that used the old chain to
5544     // use the new one.
5545     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5546 
5547     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5548 
5549     SDValue RetOps[] = { LoadRes, Chain };
5550     return DAG.getMergeValues(RetOps, DL);
5551   }
5552   return SDValue();
5553 }
5554 
5555 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5556   SDValue N0 = N->getOperand(0);
5557   SDValue N1 = N->getOperand(1);
5558   SDValue N2 = N->getOperand(2);
5559   SDLoc DL(N);
5560 
5561   // Canonicalize integer abs.
5562   // vselect (setg[te] X,  0),  X, -X ->
5563   // vselect (setgt    X, -1),  X, -X ->
5564   // vselect (setl[te] X,  0), -X,  X ->
5565   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5566   if (N0.getOpcode() == ISD::SETCC) {
5567     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5568     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5569     bool isAbs = false;
5570     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5571 
5572     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5573          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5574         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5575       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5576     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5577              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5578       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5579 
5580     if (isAbs) {
5581       EVT VT = LHS.getValueType();
5582       SDValue Shift = DAG.getNode(
5583           ISD::SRA, DL, VT, LHS,
5584           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5585       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5586       AddToWorklist(Shift.getNode());
5587       AddToWorklist(Add.getNode());
5588       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5589     }
5590   }
5591 
5592   if (SimplifySelectOps(N, N1, N2))
5593     return SDValue(N, 0);  // Don't revisit N.
5594 
5595   // If the VSELECT result requires splitting and the mask is provided by a
5596   // SETCC, then split both nodes and its operands before legalization. This
5597   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5598   // and enables future optimizations (e.g. min/max pattern matching on X86).
5599   if (N0.getOpcode() == ISD::SETCC) {
5600     EVT VT = N->getValueType(0);
5601 
5602     // Check if any splitting is required.
5603     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5604         TargetLowering::TypeSplitVector)
5605       return SDValue();
5606 
5607     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5608     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5609     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5610     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5611 
5612     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5613     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5614 
5615     // Add the new VSELECT nodes to the work list in case they need to be split
5616     // again.
5617     AddToWorklist(Lo.getNode());
5618     AddToWorklist(Hi.getNode());
5619 
5620     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5621   }
5622 
5623   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5624   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5625     return N1;
5626   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5627   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5628     return N2;
5629 
5630   // The ConvertSelectToConcatVector function is assuming both the above
5631   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5632   // and addressed.
5633   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5634       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5635       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5636     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5637       return CV;
5638   }
5639 
5640   return SDValue();
5641 }
5642 
5643 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5644   SDValue N0 = N->getOperand(0);
5645   SDValue N1 = N->getOperand(1);
5646   SDValue N2 = N->getOperand(2);
5647   SDValue N3 = N->getOperand(3);
5648   SDValue N4 = N->getOperand(4);
5649   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5650 
5651   // fold select_cc lhs, rhs, x, x, cc -> x
5652   if (N2 == N3)
5653     return N2;
5654 
5655   // Determine if the condition we're dealing with is constant
5656   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5657                                   CC, SDLoc(N), false)) {
5658     AddToWorklist(SCC.getNode());
5659 
5660     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5661       if (!SCCC->isNullValue())
5662         return N2;    // cond always true -> true val
5663       else
5664         return N3;    // cond always false -> false val
5665     } else if (SCC->getOpcode() == ISD::UNDEF) {
5666       // When the condition is UNDEF, just return the first operand. This is
5667       // coherent the DAG creation, no setcc node is created in this case
5668       return N2;
5669     } else if (SCC.getOpcode() == ISD::SETCC) {
5670       // Fold to a simpler select_cc
5671       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5672                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5673                          SCC.getOperand(2));
5674     }
5675   }
5676 
5677   // If we can fold this based on the true/false value, do so.
5678   if (SimplifySelectOps(N, N2, N3))
5679     return SDValue(N, 0);  // Don't revisit N.
5680 
5681   // fold select_cc into other things, such as min/max/abs
5682   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5683 }
5684 
5685 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5686   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5687                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5688                        SDLoc(N));
5689 }
5690 
5691 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5692   SDValue LHS = N->getOperand(0);
5693   SDValue RHS = N->getOperand(1);
5694   SDValue Carry = N->getOperand(2);
5695   SDValue Cond = N->getOperand(3);
5696 
5697   // If Carry is false, fold to a regular SETCC.
5698   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5699     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5700 
5701   return SDValue();
5702 }
5703 
5704 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5705 /// a build_vector of constants.
5706 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5707 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5708 /// Vector extends are not folded if operations are legal; this is to
5709 /// avoid introducing illegal build_vector dag nodes.
5710 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5711                                          SelectionDAG &DAG, bool LegalTypes,
5712                                          bool LegalOperations) {
5713   unsigned Opcode = N->getOpcode();
5714   SDValue N0 = N->getOperand(0);
5715   EVT VT = N->getValueType(0);
5716 
5717   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5718          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5719          && "Expected EXTEND dag node in input!");
5720 
5721   // fold (sext c1) -> c1
5722   // fold (zext c1) -> c1
5723   // fold (aext c1) -> c1
5724   if (isa<ConstantSDNode>(N0))
5725     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5726 
5727   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5728   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5729   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5730   EVT SVT = VT.getScalarType();
5731   if (!(VT.isVector() &&
5732       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5733       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5734     return nullptr;
5735 
5736   // We can fold this node into a build_vector.
5737   unsigned VTBits = SVT.getSizeInBits();
5738   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5739   SmallVector<SDValue, 8> Elts;
5740   unsigned NumElts = VT.getVectorNumElements();
5741   SDLoc DL(N);
5742 
5743   for (unsigned i=0; i != NumElts; ++i) {
5744     SDValue Op = N0->getOperand(i);
5745     if (Op->getOpcode() == ISD::UNDEF) {
5746       Elts.push_back(DAG.getUNDEF(SVT));
5747       continue;
5748     }
5749 
5750     SDLoc DL(Op);
5751     // Get the constant value and if needed trunc it to the size of the type.
5752     // Nodes like build_vector might have constants wider than the scalar type.
5753     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5754     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5755       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5756     else
5757       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5758   }
5759 
5760   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5761 }
5762 
5763 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5764 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5765 // transformation. Returns true if extension are possible and the above
5766 // mentioned transformation is profitable.
5767 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5768                                     unsigned ExtOpc,
5769                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5770                                     const TargetLowering &TLI) {
5771   bool HasCopyToRegUses = false;
5772   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5773   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5774                             UE = N0.getNode()->use_end();
5775        UI != UE; ++UI) {
5776     SDNode *User = *UI;
5777     if (User == N)
5778       continue;
5779     if (UI.getUse().getResNo() != N0.getResNo())
5780       continue;
5781     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5782     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5783       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5784       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5785         // Sign bits will be lost after a zext.
5786         return false;
5787       bool Add = false;
5788       for (unsigned i = 0; i != 2; ++i) {
5789         SDValue UseOp = User->getOperand(i);
5790         if (UseOp == N0)
5791           continue;
5792         if (!isa<ConstantSDNode>(UseOp))
5793           return false;
5794         Add = true;
5795       }
5796       if (Add)
5797         ExtendNodes.push_back(User);
5798       continue;
5799     }
5800     // If truncates aren't free and there are users we can't
5801     // extend, it isn't worthwhile.
5802     if (!isTruncFree)
5803       return false;
5804     // Remember if this value is live-out.
5805     if (User->getOpcode() == ISD::CopyToReg)
5806       HasCopyToRegUses = true;
5807   }
5808 
5809   if (HasCopyToRegUses) {
5810     bool BothLiveOut = false;
5811     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5812          UI != UE; ++UI) {
5813       SDUse &Use = UI.getUse();
5814       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5815         BothLiveOut = true;
5816         break;
5817       }
5818     }
5819     if (BothLiveOut)
5820       // Both unextended and extended values are live out. There had better be
5821       // a good reason for the transformation.
5822       return ExtendNodes.size();
5823   }
5824   return true;
5825 }
5826 
5827 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5828                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5829                                   ISD::NodeType ExtType) {
5830   // Extend SetCC uses if necessary.
5831   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5832     SDNode *SetCC = SetCCs[i];
5833     SmallVector<SDValue, 4> Ops;
5834 
5835     for (unsigned j = 0; j != 2; ++j) {
5836       SDValue SOp = SetCC->getOperand(j);
5837       if (SOp == Trunc)
5838         Ops.push_back(ExtLoad);
5839       else
5840         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5841     }
5842 
5843     Ops.push_back(SetCC->getOperand(2));
5844     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5845   }
5846 }
5847 
5848 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5849 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5850   SDValue N0 = N->getOperand(0);
5851   EVT DstVT = N->getValueType(0);
5852   EVT SrcVT = N0.getValueType();
5853 
5854   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5855           N->getOpcode() == ISD::ZERO_EXTEND) &&
5856          "Unexpected node type (not an extend)!");
5857 
5858   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5859   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5860   //   (v8i32 (sext (v8i16 (load x))))
5861   // into:
5862   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5863   //                          (v4i32 (sextload (x + 16)))))
5864   // Where uses of the original load, i.e.:
5865   //   (v8i16 (load x))
5866   // are replaced with:
5867   //   (v8i16 (truncate
5868   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5869   //                            (v4i32 (sextload (x + 16)))))))
5870   //
5871   // This combine is only applicable to illegal, but splittable, vectors.
5872   // All legal types, and illegal non-vector types, are handled elsewhere.
5873   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5874   //
5875   if (N0->getOpcode() != ISD::LOAD)
5876     return SDValue();
5877 
5878   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5879 
5880   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5881       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5882       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5883     return SDValue();
5884 
5885   SmallVector<SDNode *, 4> SetCCs;
5886   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5887     return SDValue();
5888 
5889   ISD::LoadExtType ExtType =
5890       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5891 
5892   // Try to split the vector types to get down to legal types.
5893   EVT SplitSrcVT = SrcVT;
5894   EVT SplitDstVT = DstVT;
5895   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5896          SplitSrcVT.getVectorNumElements() > 1) {
5897     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5898     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5899   }
5900 
5901   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5902     return SDValue();
5903 
5904   SDLoc DL(N);
5905   const unsigned NumSplits =
5906       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5907   const unsigned Stride = SplitSrcVT.getStoreSize();
5908   SmallVector<SDValue, 4> Loads;
5909   SmallVector<SDValue, 4> Chains;
5910 
5911   SDValue BasePtr = LN0->getBasePtr();
5912   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5913     const unsigned Offset = Idx * Stride;
5914     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5915 
5916     SDValue SplitLoad = DAG.getExtLoad(
5917         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5918         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5919         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5920         Align, LN0->getAAInfo());
5921 
5922     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5923                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5924 
5925     Loads.push_back(SplitLoad.getValue(0));
5926     Chains.push_back(SplitLoad.getValue(1));
5927   }
5928 
5929   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5930   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5931 
5932   CombineTo(N, NewValue);
5933 
5934   // Replace uses of the original load (before extension)
5935   // with a truncate of the concatenated sextloaded vectors.
5936   SDValue Trunc =
5937       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5938   CombineTo(N0.getNode(), Trunc, NewChain);
5939   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5940                   (ISD::NodeType)N->getOpcode());
5941   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5942 }
5943 
5944 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5945   SDValue N0 = N->getOperand(0);
5946   EVT VT = N->getValueType(0);
5947 
5948   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5949                                               LegalOperations))
5950     return SDValue(Res, 0);
5951 
5952   // fold (sext (sext x)) -> (sext x)
5953   // fold (sext (aext x)) -> (sext x)
5954   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5955     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5956                        N0.getOperand(0));
5957 
5958   if (N0.getOpcode() == ISD::TRUNCATE) {
5959     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5960     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5961     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5962       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5963       if (NarrowLoad.getNode() != N0.getNode()) {
5964         CombineTo(N0.getNode(), NarrowLoad);
5965         // CombineTo deleted the truncate, if needed, but not what's under it.
5966         AddToWorklist(oye);
5967       }
5968       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5969     }
5970 
5971     // See if the value being truncated is already sign extended.  If so, just
5972     // eliminate the trunc/sext pair.
5973     SDValue Op = N0.getOperand(0);
5974     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5975     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5976     unsigned DestBits = VT.getScalarType().getSizeInBits();
5977     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5978 
5979     if (OpBits == DestBits) {
5980       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5981       // bits, it is already ready.
5982       if (NumSignBits > DestBits-MidBits)
5983         return Op;
5984     } else if (OpBits < DestBits) {
5985       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5986       // bits, just sext from i32.
5987       if (NumSignBits > OpBits-MidBits)
5988         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5989     } else {
5990       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5991       // bits, just truncate to i32.
5992       if (NumSignBits > OpBits-MidBits)
5993         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5994     }
5995 
5996     // fold (sext (truncate x)) -> (sextinreg x).
5997     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5998                                                  N0.getValueType())) {
5999       if (OpBits < DestBits)
6000         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6001       else if (OpBits > DestBits)
6002         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6003       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6004                          DAG.getValueType(N0.getValueType()));
6005     }
6006   }
6007 
6008   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6009   // Only generate vector extloads when 1) they're legal, and 2) they are
6010   // deemed desirable by the target.
6011   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6012       ((!LegalOperations && !VT.isVector() &&
6013         !cast<LoadSDNode>(N0)->isVolatile()) ||
6014        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6015     bool DoXform = true;
6016     SmallVector<SDNode*, 4> SetCCs;
6017     if (!N0.hasOneUse())
6018       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6019     if (VT.isVector())
6020       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6021     if (DoXform) {
6022       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6023       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6024                                        LN0->getChain(),
6025                                        LN0->getBasePtr(), N0.getValueType(),
6026                                        LN0->getMemOperand());
6027       CombineTo(N, ExtLoad);
6028       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6029                                   N0.getValueType(), ExtLoad);
6030       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6031       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6032                       ISD::SIGN_EXTEND);
6033       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6034     }
6035   }
6036 
6037   // fold (sext (load x)) to multiple smaller sextloads.
6038   // Only on illegal but splittable vectors.
6039   if (SDValue ExtLoad = CombineExtLoad(N))
6040     return ExtLoad;
6041 
6042   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6043   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6044   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6045       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6046     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6047     EVT MemVT = LN0->getMemoryVT();
6048     if ((!LegalOperations && !LN0->isVolatile()) ||
6049         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6050       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6051                                        LN0->getChain(),
6052                                        LN0->getBasePtr(), MemVT,
6053                                        LN0->getMemOperand());
6054       CombineTo(N, ExtLoad);
6055       CombineTo(N0.getNode(),
6056                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6057                             N0.getValueType(), ExtLoad),
6058                 ExtLoad.getValue(1));
6059       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6060     }
6061   }
6062 
6063   // fold (sext (and/or/xor (load x), cst)) ->
6064   //      (and/or/xor (sextload x), (sext cst))
6065   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6066        N0.getOpcode() == ISD::XOR) &&
6067       isa<LoadSDNode>(N0.getOperand(0)) &&
6068       N0.getOperand(1).getOpcode() == ISD::Constant &&
6069       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6070       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6071     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6072     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6073       bool DoXform = true;
6074       SmallVector<SDNode*, 4> SetCCs;
6075       if (!N0.hasOneUse())
6076         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6077                                           SetCCs, TLI);
6078       if (DoXform) {
6079         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6080                                          LN0->getChain(), LN0->getBasePtr(),
6081                                          LN0->getMemoryVT(),
6082                                          LN0->getMemOperand());
6083         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6084         Mask = Mask.sext(VT.getSizeInBits());
6085         SDLoc DL(N);
6086         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6087                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6088         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6089                                     SDLoc(N0.getOperand(0)),
6090                                     N0.getOperand(0).getValueType(), ExtLoad);
6091         CombineTo(N, And);
6092         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6093         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6094                         ISD::SIGN_EXTEND);
6095         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6096       }
6097     }
6098   }
6099 
6100   if (N0.getOpcode() == ISD::SETCC) {
6101     EVT N0VT = N0.getOperand(0).getValueType();
6102     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6103     // Only do this before legalize for now.
6104     if (VT.isVector() && !LegalOperations &&
6105         TLI.getBooleanContents(N0VT) ==
6106             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6107       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6108       // of the same size as the compared operands. Only optimize sext(setcc())
6109       // if this is the case.
6110       EVT SVT = getSetCCResultType(N0VT);
6111 
6112       // We know that the # elements of the results is the same as the
6113       // # elements of the compare (and the # elements of the compare result
6114       // for that matter).  Check to see that they are the same size.  If so,
6115       // we know that the element size of the sext'd result matches the
6116       // element size of the compare operands.
6117       if (VT.getSizeInBits() == SVT.getSizeInBits())
6118         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6119                              N0.getOperand(1),
6120                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6121 
6122       // If the desired elements are smaller or larger than the source
6123       // elements we can use a matching integer vector type and then
6124       // truncate/sign extend
6125       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6126       if (SVT == MatchingVectorType) {
6127         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6128                                N0.getOperand(0), N0.getOperand(1),
6129                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6130         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6131       }
6132     }
6133 
6134     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6135     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6136     SDLoc DL(N);
6137     SDValue NegOne =
6138       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6139     if (SDValue SCC = SimplifySelectCC(
6140             DL, N0.getOperand(0), N0.getOperand(1), NegOne,
6141             DAG.getConstant(0, DL, VT),
6142             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6143       return SCC;
6144 
6145     if (!VT.isVector()) {
6146       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6147       if (!LegalOperations ||
6148           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6149         SDLoc DL(N);
6150         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6151         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6152                                      N0.getOperand(0), N0.getOperand(1), CC);
6153         return DAG.getSelect(DL, VT, SetCC,
6154                              NegOne, DAG.getConstant(0, DL, VT));
6155       }
6156     }
6157   }
6158 
6159   // fold (sext x) -> (zext x) if the sign bit is known zero.
6160   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6161       DAG.SignBitIsZero(N0))
6162     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6163 
6164   return SDValue();
6165 }
6166 
6167 // isTruncateOf - If N is a truncate of some other value, return true, record
6168 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6169 // This function computes KnownZero to avoid a duplicated call to
6170 // computeKnownBits in the caller.
6171 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6172                          APInt &KnownZero) {
6173   APInt KnownOne;
6174   if (N->getOpcode() == ISD::TRUNCATE) {
6175     Op = N->getOperand(0);
6176     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6177     return true;
6178   }
6179 
6180   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6181       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6182     return false;
6183 
6184   SDValue Op0 = N->getOperand(0);
6185   SDValue Op1 = N->getOperand(1);
6186   assert(Op0.getValueType() == Op1.getValueType());
6187 
6188   if (isNullConstant(Op0))
6189     Op = Op1;
6190   else if (isNullConstant(Op1))
6191     Op = Op0;
6192   else
6193     return false;
6194 
6195   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6196 
6197   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6198     return false;
6199 
6200   return true;
6201 }
6202 
6203 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6204   SDValue N0 = N->getOperand(0);
6205   EVT VT = N->getValueType(0);
6206 
6207   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6208                                               LegalOperations))
6209     return SDValue(Res, 0);
6210 
6211   // fold (zext (zext x)) -> (zext x)
6212   // fold (zext (aext x)) -> (zext x)
6213   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6214     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6215                        N0.getOperand(0));
6216 
6217   // fold (zext (truncate x)) -> (zext x) or
6218   //      (zext (truncate x)) -> (truncate x)
6219   // This is valid when the truncated bits of x are already zero.
6220   // FIXME: We should extend this to work for vectors too.
6221   SDValue Op;
6222   APInt KnownZero;
6223   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6224     APInt TruncatedBits =
6225       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6226       APInt(Op.getValueSizeInBits(), 0) :
6227       APInt::getBitsSet(Op.getValueSizeInBits(),
6228                         N0.getValueSizeInBits(),
6229                         std::min(Op.getValueSizeInBits(),
6230                                  VT.getSizeInBits()));
6231     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6232       if (VT.bitsGT(Op.getValueType()))
6233         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6234       if (VT.bitsLT(Op.getValueType()))
6235         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6236 
6237       return Op;
6238     }
6239   }
6240 
6241   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6242   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6243   if (N0.getOpcode() == ISD::TRUNCATE) {
6244     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6245       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6246       if (NarrowLoad.getNode() != N0.getNode()) {
6247         CombineTo(N0.getNode(), NarrowLoad);
6248         // CombineTo deleted the truncate, if needed, but not what's under it.
6249         AddToWorklist(oye);
6250       }
6251       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6252     }
6253   }
6254 
6255   // fold (zext (truncate x)) -> (and x, mask)
6256   if (N0.getOpcode() == ISD::TRUNCATE) {
6257     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6258     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6259     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6260       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6261       if (NarrowLoad.getNode() != N0.getNode()) {
6262         CombineTo(N0.getNode(), NarrowLoad);
6263         // CombineTo deleted the truncate, if needed, but not what's under it.
6264         AddToWorklist(oye);
6265       }
6266       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6267     }
6268 
6269     EVT SrcVT = N0.getOperand(0).getValueType();
6270     EVT MinVT = N0.getValueType();
6271 
6272     // Try to mask before the extension to avoid having to generate a larger mask,
6273     // possibly over several sub-vectors.
6274     if (SrcVT.bitsLT(VT)) {
6275       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6276                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6277         SDValue Op = N0.getOperand(0);
6278         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6279         AddToWorklist(Op.getNode());
6280         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6281       }
6282     }
6283 
6284     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6285       SDValue Op = N0.getOperand(0);
6286       if (SrcVT.bitsLT(VT)) {
6287         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6288         AddToWorklist(Op.getNode());
6289       } else if (SrcVT.bitsGT(VT)) {
6290         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6291         AddToWorklist(Op.getNode());
6292       }
6293       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6294     }
6295   }
6296 
6297   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6298   // if either of the casts is not free.
6299   if (N0.getOpcode() == ISD::AND &&
6300       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6301       N0.getOperand(1).getOpcode() == ISD::Constant &&
6302       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6303                            N0.getValueType()) ||
6304        !TLI.isZExtFree(N0.getValueType(), VT))) {
6305     SDValue X = N0.getOperand(0).getOperand(0);
6306     if (X.getValueType().bitsLT(VT)) {
6307       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6308     } else if (X.getValueType().bitsGT(VT)) {
6309       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6310     }
6311     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6312     Mask = Mask.zext(VT.getSizeInBits());
6313     SDLoc DL(N);
6314     return DAG.getNode(ISD::AND, DL, VT,
6315                        X, DAG.getConstant(Mask, DL, VT));
6316   }
6317 
6318   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6319   // Only generate vector extloads when 1) they're legal, and 2) they are
6320   // deemed desirable by the target.
6321   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6322       ((!LegalOperations && !VT.isVector() &&
6323         !cast<LoadSDNode>(N0)->isVolatile()) ||
6324        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6325     bool DoXform = true;
6326     SmallVector<SDNode*, 4> SetCCs;
6327     if (!N0.hasOneUse())
6328       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6329     if (VT.isVector())
6330       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6331     if (DoXform) {
6332       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6333       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6334                                        LN0->getChain(),
6335                                        LN0->getBasePtr(), N0.getValueType(),
6336                                        LN0->getMemOperand());
6337       CombineTo(N, ExtLoad);
6338       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6339                                   N0.getValueType(), ExtLoad);
6340       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6341 
6342       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6343                       ISD::ZERO_EXTEND);
6344       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6345     }
6346   }
6347 
6348   // fold (zext (load x)) to multiple smaller zextloads.
6349   // Only on illegal but splittable vectors.
6350   if (SDValue ExtLoad = CombineExtLoad(N))
6351     return ExtLoad;
6352 
6353   // fold (zext (and/or/xor (load x), cst)) ->
6354   //      (and/or/xor (zextload x), (zext cst))
6355   // Unless (and (load x) cst) will match as a zextload already and has
6356   // additional users.
6357   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6358        N0.getOpcode() == ISD::XOR) &&
6359       isa<LoadSDNode>(N0.getOperand(0)) &&
6360       N0.getOperand(1).getOpcode() == ISD::Constant &&
6361       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6362       (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) {
6363     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6364     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6365       bool DoXform = true;
6366       SmallVector<SDNode*, 4> SetCCs;
6367       if (!N0.hasOneUse()) {
6368         if (N0.getOpcode() == ISD::AND) {
6369           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6370           auto NarrowLoad = false;
6371           EVT LoadResultTy = AndC->getValueType(0);
6372           EVT ExtVT, LoadedVT;
6373           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6374                                NarrowLoad))
6375             DoXform = false;
6376         }
6377         if (DoXform)
6378           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6379                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6380       }
6381       if (DoXform) {
6382         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6383                                          LN0->getChain(), LN0->getBasePtr(),
6384                                          LN0->getMemoryVT(),
6385                                          LN0->getMemOperand());
6386         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6387         Mask = Mask.zext(VT.getSizeInBits());
6388         SDLoc DL(N);
6389         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6390                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6391         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6392                                     SDLoc(N0.getOperand(0)),
6393                                     N0.getOperand(0).getValueType(), ExtLoad);
6394         CombineTo(N, And);
6395         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6396         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6397                         ISD::ZERO_EXTEND);
6398         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6399       }
6400     }
6401   }
6402 
6403   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6404   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6405   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6406       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6407     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6408     EVT MemVT = LN0->getMemoryVT();
6409     if ((!LegalOperations && !LN0->isVolatile()) ||
6410         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6411       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6412                                        LN0->getChain(),
6413                                        LN0->getBasePtr(), MemVT,
6414                                        LN0->getMemOperand());
6415       CombineTo(N, ExtLoad);
6416       CombineTo(N0.getNode(),
6417                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6418                             ExtLoad),
6419                 ExtLoad.getValue(1));
6420       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6421     }
6422   }
6423 
6424   if (N0.getOpcode() == ISD::SETCC) {
6425     if (!LegalOperations && VT.isVector() &&
6426         N0.getValueType().getVectorElementType() == MVT::i1) {
6427       EVT N0VT = N0.getOperand(0).getValueType();
6428       if (getSetCCResultType(N0VT) == N0.getValueType())
6429         return SDValue();
6430 
6431       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6432       // Only do this before legalize for now.
6433       SDLoc DL(N);
6434       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6435       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6436         // We know that the # elements of the results is the same as the
6437         // # elements of the compare (and the # elements of the compare result
6438         // for that matter).  Check to see that they are the same size.  If so,
6439         // we know that the element size of the sext'd result matches the
6440         // element size of the compare operands.
6441         return DAG.getNode(ISD::AND, DL, VT,
6442                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6443                                          N0.getOperand(1),
6444                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6445                            VecOnes);
6446 
6447       // If the desired elements are smaller or larger than the source
6448       // elements we can use a matching integer vector type and then
6449       // truncate/sign extend
6450       EVT MatchingElementType =
6451         EVT::getIntegerVT(*DAG.getContext(),
6452                           N0VT.getScalarType().getSizeInBits());
6453       EVT MatchingVectorType =
6454         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6455                          N0VT.getVectorNumElements());
6456       SDValue VsetCC =
6457         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6458                       N0.getOperand(1),
6459                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6460       return DAG.getNode(ISD::AND, DL, VT,
6461                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6462                          VecOnes);
6463     }
6464 
6465     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6466     SDLoc DL(N);
6467     if (SDValue SCC = SimplifySelectCC(
6468             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6469             DAG.getConstant(0, DL, VT),
6470             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6471       return SCC;
6472   }
6473 
6474   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6475   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6476       isa<ConstantSDNode>(N0.getOperand(1)) &&
6477       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6478       N0.hasOneUse()) {
6479     SDValue ShAmt = N0.getOperand(1);
6480     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6481     if (N0.getOpcode() == ISD::SHL) {
6482       SDValue InnerZExt = N0.getOperand(0);
6483       // If the original shl may be shifting out bits, do not perform this
6484       // transformation.
6485       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6486         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6487       if (ShAmtVal > KnownZeroBits)
6488         return SDValue();
6489     }
6490 
6491     SDLoc DL(N);
6492 
6493     // Ensure that the shift amount is wide enough for the shifted value.
6494     if (VT.getSizeInBits() >= 256)
6495       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6496 
6497     return DAG.getNode(N0.getOpcode(), DL, VT,
6498                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6499                        ShAmt);
6500   }
6501 
6502   return SDValue();
6503 }
6504 
6505 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6506   SDValue N0 = N->getOperand(0);
6507   EVT VT = N->getValueType(0);
6508 
6509   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6510                                               LegalOperations))
6511     return SDValue(Res, 0);
6512 
6513   // fold (aext (aext x)) -> (aext x)
6514   // fold (aext (zext x)) -> (zext x)
6515   // fold (aext (sext x)) -> (sext x)
6516   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6517       N0.getOpcode() == ISD::ZERO_EXTEND ||
6518       N0.getOpcode() == ISD::SIGN_EXTEND)
6519     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6520 
6521   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6522   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6523   if (N0.getOpcode() == ISD::TRUNCATE) {
6524     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6525       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6526       if (NarrowLoad.getNode() != N0.getNode()) {
6527         CombineTo(N0.getNode(), NarrowLoad);
6528         // CombineTo deleted the truncate, if needed, but not what's under it.
6529         AddToWorklist(oye);
6530       }
6531       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6532     }
6533   }
6534 
6535   // fold (aext (truncate x))
6536   if (N0.getOpcode() == ISD::TRUNCATE) {
6537     SDValue TruncOp = N0.getOperand(0);
6538     if (TruncOp.getValueType() == VT)
6539       return TruncOp; // x iff x size == zext size.
6540     if (TruncOp.getValueType().bitsGT(VT))
6541       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6542     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6543   }
6544 
6545   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6546   // if the trunc is not free.
6547   if (N0.getOpcode() == ISD::AND &&
6548       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6549       N0.getOperand(1).getOpcode() == ISD::Constant &&
6550       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6551                           N0.getValueType())) {
6552     SDValue X = N0.getOperand(0).getOperand(0);
6553     if (X.getValueType().bitsLT(VT)) {
6554       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6555     } else if (X.getValueType().bitsGT(VT)) {
6556       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6557     }
6558     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6559     Mask = Mask.zext(VT.getSizeInBits());
6560     SDLoc DL(N);
6561     return DAG.getNode(ISD::AND, DL, VT,
6562                        X, DAG.getConstant(Mask, DL, VT));
6563   }
6564 
6565   // fold (aext (load x)) -> (aext (truncate (extload x)))
6566   // None of the supported targets knows how to perform load and any_ext
6567   // on vectors in one instruction.  We only perform this transformation on
6568   // scalars.
6569   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6570       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6571       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6572     bool DoXform = true;
6573     SmallVector<SDNode*, 4> SetCCs;
6574     if (!N0.hasOneUse())
6575       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6576     if (DoXform) {
6577       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6578       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6579                                        LN0->getChain(),
6580                                        LN0->getBasePtr(), N0.getValueType(),
6581                                        LN0->getMemOperand());
6582       CombineTo(N, ExtLoad);
6583       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6584                                   N0.getValueType(), ExtLoad);
6585       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6586       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6587                       ISD::ANY_EXTEND);
6588       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6589     }
6590   }
6591 
6592   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6593   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6594   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6595   if (N0.getOpcode() == ISD::LOAD &&
6596       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6597       N0.hasOneUse()) {
6598     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6599     ISD::LoadExtType ExtType = LN0->getExtensionType();
6600     EVT MemVT = LN0->getMemoryVT();
6601     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6602       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6603                                        VT, LN0->getChain(), LN0->getBasePtr(),
6604                                        MemVT, LN0->getMemOperand());
6605       CombineTo(N, ExtLoad);
6606       CombineTo(N0.getNode(),
6607                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6608                             N0.getValueType(), ExtLoad),
6609                 ExtLoad.getValue(1));
6610       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6611     }
6612   }
6613 
6614   if (N0.getOpcode() == ISD::SETCC) {
6615     // For vectors:
6616     // aext(setcc) -> vsetcc
6617     // aext(setcc) -> truncate(vsetcc)
6618     // aext(setcc) -> aext(vsetcc)
6619     // Only do this before legalize for now.
6620     if (VT.isVector() && !LegalOperations) {
6621       EVT N0VT = N0.getOperand(0).getValueType();
6622         // We know that the # elements of the results is the same as the
6623         // # elements of the compare (and the # elements of the compare result
6624         // for that matter).  Check to see that they are the same size.  If so,
6625         // we know that the element size of the sext'd result matches the
6626         // element size of the compare operands.
6627       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6628         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6629                              N0.getOperand(1),
6630                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6631       // If the desired elements are smaller or larger than the source
6632       // elements we can use a matching integer vector type and then
6633       // truncate/any extend
6634       else {
6635         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6636         SDValue VsetCC =
6637           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6638                         N0.getOperand(1),
6639                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6640         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6641       }
6642     }
6643 
6644     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6645     SDLoc DL(N);
6646     if (SDValue SCC = SimplifySelectCC(
6647             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6648             DAG.getConstant(0, DL, VT),
6649             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6650       return SCC;
6651   }
6652 
6653   return SDValue();
6654 }
6655 
6656 /// See if the specified operand can be simplified with the knowledge that only
6657 /// the bits specified by Mask are used.  If so, return the simpler operand,
6658 /// otherwise return a null SDValue.
6659 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6660   switch (V.getOpcode()) {
6661   default: break;
6662   case ISD::Constant: {
6663     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6664     assert(CV && "Const value should be ConstSDNode.");
6665     const APInt &CVal = CV->getAPIntValue();
6666     APInt NewVal = CVal & Mask;
6667     if (NewVal != CVal)
6668       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6669     break;
6670   }
6671   case ISD::OR:
6672   case ISD::XOR:
6673     // If the LHS or RHS don't contribute bits to the or, drop them.
6674     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6675       return V.getOperand(1);
6676     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6677       return V.getOperand(0);
6678     break;
6679   case ISD::SRL:
6680     // Only look at single-use SRLs.
6681     if (!V.getNode()->hasOneUse())
6682       break;
6683     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6684       // See if we can recursively simplify the LHS.
6685       unsigned Amt = RHSC->getZExtValue();
6686 
6687       // Watch out for shift count overflow though.
6688       if (Amt >= Mask.getBitWidth()) break;
6689       APInt NewMask = Mask << Amt;
6690       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6691         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6692                            SimplifyLHS, V.getOperand(1));
6693     }
6694   }
6695   return SDValue();
6696 }
6697 
6698 /// If the result of a wider load is shifted to right of N  bits and then
6699 /// truncated to a narrower type and where N is a multiple of number of bits of
6700 /// the narrower type, transform it to a narrower load from address + N / num of
6701 /// bits of new type. If the result is to be extended, also fold the extension
6702 /// to form a extending load.
6703 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6704   unsigned Opc = N->getOpcode();
6705 
6706   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6707   SDValue N0 = N->getOperand(0);
6708   EVT VT = N->getValueType(0);
6709   EVT ExtVT = VT;
6710 
6711   // This transformation isn't valid for vector loads.
6712   if (VT.isVector())
6713     return SDValue();
6714 
6715   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6716   // extended to VT.
6717   if (Opc == ISD::SIGN_EXTEND_INREG) {
6718     ExtType = ISD::SEXTLOAD;
6719     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6720   } else if (Opc == ISD::SRL) {
6721     // Another special-case: SRL is basically zero-extending a narrower value.
6722     ExtType = ISD::ZEXTLOAD;
6723     N0 = SDValue(N, 0);
6724     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6725     if (!N01) return SDValue();
6726     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6727                               VT.getSizeInBits() - N01->getZExtValue());
6728   }
6729   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6730     return SDValue();
6731 
6732   unsigned EVTBits = ExtVT.getSizeInBits();
6733 
6734   // Do not generate loads of non-round integer types since these can
6735   // be expensive (and would be wrong if the type is not byte sized).
6736   if (!ExtVT.isRound())
6737     return SDValue();
6738 
6739   unsigned ShAmt = 0;
6740   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6741     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6742       ShAmt = N01->getZExtValue();
6743       // Is the shift amount a multiple of size of VT?
6744       if ((ShAmt & (EVTBits-1)) == 0) {
6745         N0 = N0.getOperand(0);
6746         // Is the load width a multiple of size of VT?
6747         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6748           return SDValue();
6749       }
6750 
6751       // At this point, we must have a load or else we can't do the transform.
6752       if (!isa<LoadSDNode>(N0)) return SDValue();
6753 
6754       // Because a SRL must be assumed to *need* to zero-extend the high bits
6755       // (as opposed to anyext the high bits), we can't combine the zextload
6756       // lowering of SRL and an sextload.
6757       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6758         return SDValue();
6759 
6760       // If the shift amount is larger than the input type then we're not
6761       // accessing any of the loaded bytes.  If the load was a zextload/extload
6762       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6763       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6764         return SDValue();
6765     }
6766   }
6767 
6768   // If the load is shifted left (and the result isn't shifted back right),
6769   // we can fold the truncate through the shift.
6770   unsigned ShLeftAmt = 0;
6771   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6772       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6773     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6774       ShLeftAmt = N01->getZExtValue();
6775       N0 = N0.getOperand(0);
6776     }
6777   }
6778 
6779   // If we haven't found a load, we can't narrow it.  Don't transform one with
6780   // multiple uses, this would require adding a new load.
6781   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6782     return SDValue();
6783 
6784   // Don't change the width of a volatile load.
6785   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6786   if (LN0->isVolatile())
6787     return SDValue();
6788 
6789   // Verify that we are actually reducing a load width here.
6790   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6791     return SDValue();
6792 
6793   // For the transform to be legal, the load must produce only two values
6794   // (the value loaded and the chain).  Don't transform a pre-increment
6795   // load, for example, which produces an extra value.  Otherwise the
6796   // transformation is not equivalent, and the downstream logic to replace
6797   // uses gets things wrong.
6798   if (LN0->getNumValues() > 2)
6799     return SDValue();
6800 
6801   // If the load that we're shrinking is an extload and we're not just
6802   // discarding the extension we can't simply shrink the load. Bail.
6803   // TODO: It would be possible to merge the extensions in some cases.
6804   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6805       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6806     return SDValue();
6807 
6808   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6809     return SDValue();
6810 
6811   EVT PtrType = N0.getOperand(1).getValueType();
6812 
6813   if (PtrType == MVT::Untyped || PtrType.isExtended())
6814     // It's not possible to generate a constant of extended or untyped type.
6815     return SDValue();
6816 
6817   // For big endian targets, we need to adjust the offset to the pointer to
6818   // load the correct bytes.
6819   if (DAG.getDataLayout().isBigEndian()) {
6820     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6821     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6822     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6823   }
6824 
6825   uint64_t PtrOff = ShAmt / 8;
6826   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6827   SDLoc DL(LN0);
6828   // The original load itself didn't wrap, so an offset within it doesn't.
6829   SDNodeFlags Flags;
6830   Flags.setNoUnsignedWrap(true);
6831   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6832                                PtrType, LN0->getBasePtr(),
6833                                DAG.getConstant(PtrOff, DL, PtrType),
6834                                &Flags);
6835   AddToWorklist(NewPtr.getNode());
6836 
6837   SDValue Load;
6838   if (ExtType == ISD::NON_EXTLOAD)
6839     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6840                         LN0->getPointerInfo().getWithOffset(PtrOff),
6841                         LN0->isVolatile(), LN0->isNonTemporal(),
6842                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6843   else
6844     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6845                           LN0->getPointerInfo().getWithOffset(PtrOff),
6846                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6847                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6848 
6849   // Replace the old load's chain with the new load's chain.
6850   WorklistRemover DeadNodes(*this);
6851   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6852 
6853   // Shift the result left, if we've swallowed a left shift.
6854   SDValue Result = Load;
6855   if (ShLeftAmt != 0) {
6856     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6857     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6858       ShImmTy = VT;
6859     // If the shift amount is as large as the result size (but, presumably,
6860     // no larger than the source) then the useful bits of the result are
6861     // zero; we can't simply return the shortened shift, because the result
6862     // of that operation is undefined.
6863     SDLoc DL(N0);
6864     if (ShLeftAmt >= VT.getSizeInBits())
6865       Result = DAG.getConstant(0, DL, VT);
6866     else
6867       Result = DAG.getNode(ISD::SHL, DL, VT,
6868                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6869   }
6870 
6871   // Return the new loaded value.
6872   return Result;
6873 }
6874 
6875 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6876   SDValue N0 = N->getOperand(0);
6877   SDValue N1 = N->getOperand(1);
6878   EVT VT = N->getValueType(0);
6879   EVT EVT = cast<VTSDNode>(N1)->getVT();
6880   unsigned VTBits = VT.getScalarType().getSizeInBits();
6881   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6882 
6883   if (N0.isUndef())
6884     return DAG.getUNDEF(VT);
6885 
6886   // fold (sext_in_reg c1) -> c1
6887   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6888     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6889 
6890   // If the input is already sign extended, just drop the extension.
6891   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6892     return N0;
6893 
6894   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6895   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6896       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6897     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6898                        N0.getOperand(0), N1);
6899 
6900   // fold (sext_in_reg (sext x)) -> (sext x)
6901   // fold (sext_in_reg (aext x)) -> (sext x)
6902   // if x is small enough.
6903   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6904     SDValue N00 = N0.getOperand(0);
6905     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6906         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6907       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6908   }
6909 
6910   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6911   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6912     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6913 
6914   // fold operands of sext_in_reg based on knowledge that the top bits are not
6915   // demanded.
6916   if (SimplifyDemandedBits(SDValue(N, 0)))
6917     return SDValue(N, 0);
6918 
6919   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6920   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6921   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6922     return NarrowLoad;
6923 
6924   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6925   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6926   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6927   if (N0.getOpcode() == ISD::SRL) {
6928     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6929       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6930         // We can turn this into an SRA iff the input to the SRL is already sign
6931         // extended enough.
6932         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6933         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6934           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6935                              N0.getOperand(0), N0.getOperand(1));
6936       }
6937   }
6938 
6939   // fold (sext_inreg (extload x)) -> (sextload x)
6940   if (ISD::isEXTLoad(N0.getNode()) &&
6941       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6942       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6943       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6944        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6945     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6946     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6947                                      LN0->getChain(),
6948                                      LN0->getBasePtr(), EVT,
6949                                      LN0->getMemOperand());
6950     CombineTo(N, ExtLoad);
6951     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6952     AddToWorklist(ExtLoad.getNode());
6953     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6954   }
6955   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6956   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6957       N0.hasOneUse() &&
6958       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6959       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6960        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6961     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6962     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6963                                      LN0->getChain(),
6964                                      LN0->getBasePtr(), EVT,
6965                                      LN0->getMemOperand());
6966     CombineTo(N, ExtLoad);
6967     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6968     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6969   }
6970 
6971   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6972   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6973     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6974                                            N0.getOperand(1), false))
6975       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6976                          BSwap, N1);
6977   }
6978 
6979   return SDValue();
6980 }
6981 
6982 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6983   SDValue N0 = N->getOperand(0);
6984   EVT VT = N->getValueType(0);
6985 
6986   if (N0.getOpcode() == ISD::UNDEF)
6987     return DAG.getUNDEF(VT);
6988 
6989   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6990                                               LegalOperations))
6991     return SDValue(Res, 0);
6992 
6993   return SDValue();
6994 }
6995 
6996 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6997   SDValue N0 = N->getOperand(0);
6998   EVT VT = N->getValueType(0);
6999   bool isLE = DAG.getDataLayout().isLittleEndian();
7000 
7001   // noop truncate
7002   if (N0.getValueType() == N->getValueType(0))
7003     return N0;
7004   // fold (truncate c1) -> c1
7005   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7006     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7007   // fold (truncate (truncate x)) -> (truncate x)
7008   if (N0.getOpcode() == ISD::TRUNCATE)
7009     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7010   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7011   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7012       N0.getOpcode() == ISD::SIGN_EXTEND ||
7013       N0.getOpcode() == ISD::ANY_EXTEND) {
7014     // if the source is smaller than the dest, we still need an extend.
7015     if (N0.getOperand(0).getValueType().bitsLT(VT))
7016       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7017     // if the source is larger than the dest, than we just need the truncate.
7018     if (N0.getOperand(0).getValueType().bitsGT(VT))
7019       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7020     // if the source and dest are the same type, we can drop both the extend
7021     // and the truncate.
7022     return N0.getOperand(0);
7023   }
7024 
7025   // Fold extract-and-trunc into a narrow extract. For example:
7026   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7027   //   i32 y = TRUNCATE(i64 x)
7028   //        -- becomes --
7029   //   v16i8 b = BITCAST (v2i64 val)
7030   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7031   //
7032   // Note: We only run this optimization after type legalization (which often
7033   // creates this pattern) and before operation legalization after which
7034   // we need to be more careful about the vector instructions that we generate.
7035   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7036       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7037 
7038     EVT VecTy = N0.getOperand(0).getValueType();
7039     EVT ExTy = N0.getValueType();
7040     EVT TrTy = N->getValueType(0);
7041 
7042     unsigned NumElem = VecTy.getVectorNumElements();
7043     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7044 
7045     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7046     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7047 
7048     SDValue EltNo = N0->getOperand(1);
7049     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7050       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7051       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7052       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7053 
7054       SDLoc DL(N);
7055       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7056                          DAG.getBitcast(NVT, N0.getOperand(0)),
7057                          DAG.getConstant(Index, DL, IndexTy));
7058     }
7059   }
7060 
7061   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7062   if (N0.getOpcode() == ISD::SELECT) {
7063     EVT SrcVT = N0.getValueType();
7064     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7065         TLI.isTruncateFree(SrcVT, VT)) {
7066       SDLoc SL(N0);
7067       SDValue Cond = N0.getOperand(0);
7068       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7069       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7070       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7071     }
7072   }
7073 
7074   // Fold a series of buildvector, bitcast, and truncate if possible.
7075   // For example fold
7076   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7077   //   (2xi32 (buildvector x, y)).
7078   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7079       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7080       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7081       N0.getOperand(0).hasOneUse()) {
7082 
7083     SDValue BuildVect = N0.getOperand(0);
7084     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7085     EVT TruncVecEltTy = VT.getVectorElementType();
7086 
7087     // Check that the element types match.
7088     if (BuildVectEltTy == TruncVecEltTy) {
7089       // Now we only need to compute the offset of the truncated elements.
7090       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7091       unsigned TruncVecNumElts = VT.getVectorNumElements();
7092       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7093 
7094       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7095              "Invalid number of elements");
7096 
7097       SmallVector<SDValue, 8> Opnds;
7098       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7099         Opnds.push_back(BuildVect.getOperand(i));
7100 
7101       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7102     }
7103   }
7104 
7105   // See if we can simplify the input to this truncate through knowledge that
7106   // only the low bits are being used.
7107   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7108   // Currently we only perform this optimization on scalars because vectors
7109   // may have different active low bits.
7110   if (!VT.isVector()) {
7111     if (SDValue Shorter =
7112             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7113                                                      VT.getSizeInBits())))
7114       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7115   }
7116   // fold (truncate (load x)) -> (smaller load x)
7117   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7118   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7119     if (SDValue Reduced = ReduceLoadWidth(N))
7120       return Reduced;
7121 
7122     // Handle the case where the load remains an extending load even
7123     // after truncation.
7124     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7125       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7126       if (!LN0->isVolatile() &&
7127           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7128         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7129                                          VT, LN0->getChain(), LN0->getBasePtr(),
7130                                          LN0->getMemoryVT(),
7131                                          LN0->getMemOperand());
7132         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7133         return NewLoad;
7134       }
7135     }
7136   }
7137   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7138   // where ... are all 'undef'.
7139   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7140     SmallVector<EVT, 8> VTs;
7141     SDValue V;
7142     unsigned Idx = 0;
7143     unsigned NumDefs = 0;
7144 
7145     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7146       SDValue X = N0.getOperand(i);
7147       if (X.getOpcode() != ISD::UNDEF) {
7148         V = X;
7149         Idx = i;
7150         NumDefs++;
7151       }
7152       // Stop if more than one members are non-undef.
7153       if (NumDefs > 1)
7154         break;
7155       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7156                                      VT.getVectorElementType(),
7157                                      X.getValueType().getVectorNumElements()));
7158     }
7159 
7160     if (NumDefs == 0)
7161       return DAG.getUNDEF(VT);
7162 
7163     if (NumDefs == 1) {
7164       assert(V.getNode() && "The single defined operand is empty!");
7165       SmallVector<SDValue, 8> Opnds;
7166       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7167         if (i != Idx) {
7168           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7169           continue;
7170         }
7171         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7172         AddToWorklist(NV.getNode());
7173         Opnds.push_back(NV);
7174       }
7175       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7176     }
7177   }
7178 
7179   // Simplify the operands using demanded-bits information.
7180   if (!VT.isVector() &&
7181       SimplifyDemandedBits(SDValue(N, 0)))
7182     return SDValue(N, 0);
7183 
7184   return SDValue();
7185 }
7186 
7187 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7188   SDValue Elt = N->getOperand(i);
7189   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7190     return Elt.getNode();
7191   return Elt.getOperand(Elt.getResNo()).getNode();
7192 }
7193 
7194 /// build_pair (load, load) -> load
7195 /// if load locations are consecutive.
7196 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7197   assert(N->getOpcode() == ISD::BUILD_PAIR);
7198 
7199   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7200   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7201   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7202       LD1->getAddressSpace() != LD2->getAddressSpace())
7203     return SDValue();
7204   EVT LD1VT = LD1->getValueType(0);
7205 
7206   if (ISD::isNON_EXTLoad(LD2) &&
7207       LD2->hasOneUse() &&
7208       // If both are volatile this would reduce the number of volatile loads.
7209       // If one is volatile it might be ok, but play conservative and bail out.
7210       !LD1->isVolatile() &&
7211       !LD2->isVolatile() &&
7212       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7213     unsigned Align = LD1->getAlignment();
7214     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7215         VT.getTypeForEVT(*DAG.getContext()));
7216 
7217     if (NewAlign <= Align &&
7218         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7219       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7220                          LD1->getBasePtr(), LD1->getPointerInfo(),
7221                          false, false, false, Align);
7222   }
7223 
7224   return SDValue();
7225 }
7226 
7227 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7228   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7229   // and Lo parts; on big-endian machines it doesn't.
7230   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7231 }
7232 
7233 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7234   SDValue N0 = N->getOperand(0);
7235   EVT VT = N->getValueType(0);
7236 
7237   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7238   // Only do this before legalize, since afterward the target may be depending
7239   // on the bitconvert.
7240   // First check to see if this is all constant.
7241   if (!LegalTypes &&
7242       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7243       VT.isVector()) {
7244     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7245 
7246     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7247     assert(!DestEltVT.isVector() &&
7248            "Element type of vector ValueType must not be vector!");
7249     if (isSimple)
7250       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7251   }
7252 
7253   // If the input is a constant, let getNode fold it.
7254   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7255     // If we can't allow illegal operations, we need to check that this is just
7256     // a fp -> int or int -> conversion and that the resulting operation will
7257     // be legal.
7258     if (!LegalOperations ||
7259         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7260          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7261         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7262          TLI.isOperationLegal(ISD::Constant, VT)))
7263       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7264   }
7265 
7266   // (conv (conv x, t1), t2) -> (conv x, t2)
7267   if (N0.getOpcode() == ISD::BITCAST)
7268     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7269                        N0.getOperand(0));
7270 
7271   // fold (conv (load x)) -> (load (conv*)x)
7272   // If the resultant load doesn't need a higher alignment than the original!
7273   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7274       // Do not change the width of a volatile load.
7275       !cast<LoadSDNode>(N0)->isVolatile() &&
7276       // Do not remove the cast if the types differ in endian layout.
7277       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7278           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7279       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7280       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7281     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7282     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7283         VT.getTypeForEVT(*DAG.getContext()));
7284     unsigned OrigAlign = LN0->getAlignment();
7285 
7286     if (Align <= OrigAlign) {
7287       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7288                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7289                                  LN0->isVolatile(), LN0->isNonTemporal(),
7290                                  LN0->isInvariant(), OrigAlign,
7291                                  LN0->getAAInfo());
7292       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7293       return Load;
7294     }
7295   }
7296 
7297   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7298   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7299   //
7300   // For ppc_fp128:
7301   // fold (bitcast (fneg x)) ->
7302   //     flipbit = signbit
7303   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7304   //
7305   // fold (bitcast (fabs x)) ->
7306   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7307   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7308   // This often reduces constant pool loads.
7309   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7310        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7311       N0.getNode()->hasOneUse() && VT.isInteger() &&
7312       !VT.isVector() && !N0.getValueType().isVector()) {
7313     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7314                                   N0.getOperand(0));
7315     AddToWorklist(NewConv.getNode());
7316 
7317     SDLoc DL(N);
7318     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7319       assert(VT.getSizeInBits() == 128);
7320       SDValue SignBit = DAG.getConstant(
7321           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7322       SDValue FlipBit;
7323       if (N0.getOpcode() == ISD::FNEG) {
7324         FlipBit = SignBit;
7325         AddToWorklist(FlipBit.getNode());
7326       } else {
7327         assert(N0.getOpcode() == ISD::FABS);
7328         SDValue Hi =
7329             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7330                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7331                                               SDLoc(NewConv)));
7332         AddToWorklist(Hi.getNode());
7333         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7334         AddToWorklist(FlipBit.getNode());
7335       }
7336       SDValue FlipBits =
7337           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7338       AddToWorklist(FlipBits.getNode());
7339       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7340     }
7341     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7342     if (N0.getOpcode() == ISD::FNEG)
7343       return DAG.getNode(ISD::XOR, DL, VT,
7344                          NewConv, DAG.getConstant(SignBit, DL, VT));
7345     assert(N0.getOpcode() == ISD::FABS);
7346     return DAG.getNode(ISD::AND, DL, VT,
7347                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7348   }
7349 
7350   // fold (bitconvert (fcopysign cst, x)) ->
7351   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7352   // Note that we don't handle (copysign x, cst) because this can always be
7353   // folded to an fneg or fabs.
7354   //
7355   // For ppc_fp128:
7356   // fold (bitcast (fcopysign cst, x)) ->
7357   //     flipbit = (and (extract_element
7358   //                     (xor (bitcast cst), (bitcast x)), 0),
7359   //                    signbit)
7360   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7361   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7362       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7363       VT.isInteger() && !VT.isVector()) {
7364     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7365     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7366     if (isTypeLegal(IntXVT)) {
7367       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7368                               IntXVT, N0.getOperand(1));
7369       AddToWorklist(X.getNode());
7370 
7371       // If X has a different width than the result/lhs, sext it or truncate it.
7372       unsigned VTWidth = VT.getSizeInBits();
7373       if (OrigXWidth < VTWidth) {
7374         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7375         AddToWorklist(X.getNode());
7376       } else if (OrigXWidth > VTWidth) {
7377         // To get the sign bit in the right place, we have to shift it right
7378         // before truncating.
7379         SDLoc DL(X);
7380         X = DAG.getNode(ISD::SRL, DL,
7381                         X.getValueType(), X,
7382                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7383                                         X.getValueType()));
7384         AddToWorklist(X.getNode());
7385         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7386         AddToWorklist(X.getNode());
7387       }
7388 
7389       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7390         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7391         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7392         AddToWorklist(Cst.getNode());
7393         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7394         AddToWorklist(X.getNode());
7395         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7396         AddToWorklist(XorResult.getNode());
7397         SDValue XorResult64 = DAG.getNode(
7398             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7399             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7400                                   SDLoc(XorResult)));
7401         AddToWorklist(XorResult64.getNode());
7402         SDValue FlipBit =
7403             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7404                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7405         AddToWorklist(FlipBit.getNode());
7406         SDValue FlipBits =
7407             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7408         AddToWorklist(FlipBits.getNode());
7409         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7410       }
7411       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7412       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7413                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7414       AddToWorklist(X.getNode());
7415 
7416       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7417                                 VT, N0.getOperand(0));
7418       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7419                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7420       AddToWorklist(Cst.getNode());
7421 
7422       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7423     }
7424   }
7425 
7426   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7427   if (N0.getOpcode() == ISD::BUILD_PAIR)
7428     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7429       return CombineLD;
7430 
7431   // Remove double bitcasts from shuffles - this is often a legacy of
7432   // XformToShuffleWithZero being used to combine bitmaskings (of
7433   // float vectors bitcast to integer vectors) into shuffles.
7434   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7435   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7436       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7437       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7438       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7439     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7440 
7441     // If operands are a bitcast, peek through if it casts the original VT.
7442     // If operands are a constant, just bitcast back to original VT.
7443     auto PeekThroughBitcast = [&](SDValue Op) {
7444       if (Op.getOpcode() == ISD::BITCAST &&
7445           Op.getOperand(0).getValueType() == VT)
7446         return SDValue(Op.getOperand(0));
7447       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7448           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7449         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7450       return SDValue();
7451     };
7452 
7453     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7454     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7455     if (!(SV0 && SV1))
7456       return SDValue();
7457 
7458     int MaskScale =
7459         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7460     SmallVector<int, 8> NewMask;
7461     for (int M : SVN->getMask())
7462       for (int i = 0; i != MaskScale; ++i)
7463         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7464 
7465     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7466     if (!LegalMask) {
7467       std::swap(SV0, SV1);
7468       ShuffleVectorSDNode::commuteMask(NewMask);
7469       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7470     }
7471 
7472     if (LegalMask)
7473       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7474   }
7475 
7476   return SDValue();
7477 }
7478 
7479 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7480   EVT VT = N->getValueType(0);
7481   return CombineConsecutiveLoads(N, VT);
7482 }
7483 
7484 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7485 /// operands. DstEltVT indicates the destination element value type.
7486 SDValue DAGCombiner::
7487 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7488   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7489 
7490   // If this is already the right type, we're done.
7491   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7492 
7493   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7494   unsigned DstBitSize = DstEltVT.getSizeInBits();
7495 
7496   // If this is a conversion of N elements of one type to N elements of another
7497   // type, convert each element.  This handles FP<->INT cases.
7498   if (SrcBitSize == DstBitSize) {
7499     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7500                               BV->getValueType(0).getVectorNumElements());
7501 
7502     // Due to the FP element handling below calling this routine recursively,
7503     // we can end up with a scalar-to-vector node here.
7504     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7505       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7506                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7507                                      DstEltVT, BV->getOperand(0)));
7508 
7509     SmallVector<SDValue, 8> Ops;
7510     for (SDValue Op : BV->op_values()) {
7511       // If the vector element type is not legal, the BUILD_VECTOR operands
7512       // are promoted and implicitly truncated.  Make that explicit here.
7513       if (Op.getValueType() != SrcEltVT)
7514         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7515       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7516                                 DstEltVT, Op));
7517       AddToWorklist(Ops.back().getNode());
7518     }
7519     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7520   }
7521 
7522   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7523   // handle annoying details of growing/shrinking FP values, we convert them to
7524   // int first.
7525   if (SrcEltVT.isFloatingPoint()) {
7526     // Convert the input float vector to a int vector where the elements are the
7527     // same sizes.
7528     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7529     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7530     SrcEltVT = IntVT;
7531   }
7532 
7533   // Now we know the input is an integer vector.  If the output is a FP type,
7534   // convert to integer first, then to FP of the right size.
7535   if (DstEltVT.isFloatingPoint()) {
7536     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7537     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7538 
7539     // Next, convert to FP elements of the same size.
7540     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7541   }
7542 
7543   SDLoc DL(BV);
7544 
7545   // Okay, we know the src/dst types are both integers of differing types.
7546   // Handling growing first.
7547   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7548   if (SrcBitSize < DstBitSize) {
7549     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7550 
7551     SmallVector<SDValue, 8> Ops;
7552     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7553          i += NumInputsPerOutput) {
7554       bool isLE = DAG.getDataLayout().isLittleEndian();
7555       APInt NewBits = APInt(DstBitSize, 0);
7556       bool EltIsUndef = true;
7557       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7558         // Shift the previously computed bits over.
7559         NewBits <<= SrcBitSize;
7560         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7561         if (Op.getOpcode() == ISD::UNDEF) continue;
7562         EltIsUndef = false;
7563 
7564         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7565                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7566       }
7567 
7568       if (EltIsUndef)
7569         Ops.push_back(DAG.getUNDEF(DstEltVT));
7570       else
7571         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7572     }
7573 
7574     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7575     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7576   }
7577 
7578   // Finally, this must be the case where we are shrinking elements: each input
7579   // turns into multiple outputs.
7580   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7581   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7582                             NumOutputsPerInput*BV->getNumOperands());
7583   SmallVector<SDValue, 8> Ops;
7584 
7585   for (const SDValue &Op : BV->op_values()) {
7586     if (Op.getOpcode() == ISD::UNDEF) {
7587       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7588       continue;
7589     }
7590 
7591     APInt OpVal = cast<ConstantSDNode>(Op)->
7592                   getAPIntValue().zextOrTrunc(SrcBitSize);
7593 
7594     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7595       APInt ThisVal = OpVal.trunc(DstBitSize);
7596       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7597       OpVal = OpVal.lshr(DstBitSize);
7598     }
7599 
7600     // For big endian targets, swap the order of the pieces of each element.
7601     if (DAG.getDataLayout().isBigEndian())
7602       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7603   }
7604 
7605   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7606 }
7607 
7608 /// Try to perform FMA combining on a given FADD node.
7609 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7610   SDValue N0 = N->getOperand(0);
7611   SDValue N1 = N->getOperand(1);
7612   EVT VT = N->getValueType(0);
7613   SDLoc SL(N);
7614 
7615   const TargetOptions &Options = DAG.getTarget().Options;
7616   bool AllowFusion =
7617       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7618 
7619   // Floating-point multiply-add with intermediate rounding.
7620   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7621 
7622   // Floating-point multiply-add without intermediate rounding.
7623   bool HasFMA =
7624       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7625       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7626 
7627   // No valid opcode, do not combine.
7628   if (!HasFMAD && !HasFMA)
7629     return SDValue();
7630 
7631   // Always prefer FMAD to FMA for precision.
7632   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7633   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7634   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7635 
7636   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7637   // prefer to fold the multiply with fewer uses.
7638   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7639       N1.getOpcode() == ISD::FMUL) {
7640     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7641       std::swap(N0, N1);
7642   }
7643 
7644   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7645   if (N0.getOpcode() == ISD::FMUL &&
7646       (Aggressive || N0->hasOneUse())) {
7647     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7648                        N0.getOperand(0), N0.getOperand(1), N1);
7649   }
7650 
7651   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7652   // Note: Commutes FADD operands.
7653   if (N1.getOpcode() == ISD::FMUL &&
7654       (Aggressive || N1->hasOneUse())) {
7655     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7656                        N1.getOperand(0), N1.getOperand(1), N0);
7657   }
7658 
7659   // Look through FP_EXTEND nodes to do more combining.
7660   if (AllowFusion && LookThroughFPExt) {
7661     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7662     if (N0.getOpcode() == ISD::FP_EXTEND) {
7663       SDValue N00 = N0.getOperand(0);
7664       if (N00.getOpcode() == ISD::FMUL)
7665         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7666                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7667                                        N00.getOperand(0)),
7668                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7669                                        N00.getOperand(1)), N1);
7670     }
7671 
7672     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7673     // Note: Commutes FADD operands.
7674     if (N1.getOpcode() == ISD::FP_EXTEND) {
7675       SDValue N10 = N1.getOperand(0);
7676       if (N10.getOpcode() == ISD::FMUL)
7677         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7678                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7679                                        N10.getOperand(0)),
7680                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7681                                        N10.getOperand(1)), N0);
7682     }
7683   }
7684 
7685   // More folding opportunities when target permits.
7686   if ((AllowFusion || HasFMAD)  && Aggressive) {
7687     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7688     if (N0.getOpcode() == PreferredFusedOpcode &&
7689         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7690       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7691                          N0.getOperand(0), N0.getOperand(1),
7692                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7693                                      N0.getOperand(2).getOperand(0),
7694                                      N0.getOperand(2).getOperand(1),
7695                                      N1));
7696     }
7697 
7698     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7699     if (N1->getOpcode() == PreferredFusedOpcode &&
7700         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7701       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7702                          N1.getOperand(0), N1.getOperand(1),
7703                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7704                                      N1.getOperand(2).getOperand(0),
7705                                      N1.getOperand(2).getOperand(1),
7706                                      N0));
7707     }
7708 
7709     if (AllowFusion && LookThroughFPExt) {
7710       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7711       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7712       auto FoldFAddFMAFPExtFMul = [&] (
7713           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7714         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7715                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7716                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7717                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7718                                        Z));
7719       };
7720       if (N0.getOpcode() == PreferredFusedOpcode) {
7721         SDValue N02 = N0.getOperand(2);
7722         if (N02.getOpcode() == ISD::FP_EXTEND) {
7723           SDValue N020 = N02.getOperand(0);
7724           if (N020.getOpcode() == ISD::FMUL)
7725             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7726                                         N020.getOperand(0), N020.getOperand(1),
7727                                         N1);
7728         }
7729       }
7730 
7731       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7732       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7733       // FIXME: This turns two single-precision and one double-precision
7734       // operation into two double-precision operations, which might not be
7735       // interesting for all targets, especially GPUs.
7736       auto FoldFAddFPExtFMAFMul = [&] (
7737           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7738         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7739                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7740                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7741                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7742                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7743                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7744                                        Z));
7745       };
7746       if (N0.getOpcode() == ISD::FP_EXTEND) {
7747         SDValue N00 = N0.getOperand(0);
7748         if (N00.getOpcode() == PreferredFusedOpcode) {
7749           SDValue N002 = N00.getOperand(2);
7750           if (N002.getOpcode() == ISD::FMUL)
7751             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7752                                         N002.getOperand(0), N002.getOperand(1),
7753                                         N1);
7754         }
7755       }
7756 
7757       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7758       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7759       if (N1.getOpcode() == PreferredFusedOpcode) {
7760         SDValue N12 = N1.getOperand(2);
7761         if (N12.getOpcode() == ISD::FP_EXTEND) {
7762           SDValue N120 = N12.getOperand(0);
7763           if (N120.getOpcode() == ISD::FMUL)
7764             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7765                                         N120.getOperand(0), N120.getOperand(1),
7766                                         N0);
7767         }
7768       }
7769 
7770       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7771       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7772       // FIXME: This turns two single-precision and one double-precision
7773       // operation into two double-precision operations, which might not be
7774       // interesting for all targets, especially GPUs.
7775       if (N1.getOpcode() == ISD::FP_EXTEND) {
7776         SDValue N10 = N1.getOperand(0);
7777         if (N10.getOpcode() == PreferredFusedOpcode) {
7778           SDValue N102 = N10.getOperand(2);
7779           if (N102.getOpcode() == ISD::FMUL)
7780             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7781                                         N102.getOperand(0), N102.getOperand(1),
7782                                         N0);
7783         }
7784       }
7785     }
7786   }
7787 
7788   return SDValue();
7789 }
7790 
7791 /// Try to perform FMA combining on a given FSUB node.
7792 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7793   SDValue N0 = N->getOperand(0);
7794   SDValue N1 = N->getOperand(1);
7795   EVT VT = N->getValueType(0);
7796   SDLoc SL(N);
7797 
7798   const TargetOptions &Options = DAG.getTarget().Options;
7799   bool AllowFusion =
7800       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7801 
7802   // Floating-point multiply-add with intermediate rounding.
7803   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7804 
7805   // Floating-point multiply-add without intermediate rounding.
7806   bool HasFMA =
7807       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7808       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7809 
7810   // No valid opcode, do not combine.
7811   if (!HasFMAD && !HasFMA)
7812     return SDValue();
7813 
7814   // Always prefer FMAD to FMA for precision.
7815   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7816   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7817   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7818 
7819   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7820   if (N0.getOpcode() == ISD::FMUL &&
7821       (Aggressive || N0->hasOneUse())) {
7822     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7823                        N0.getOperand(0), N0.getOperand(1),
7824                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7825   }
7826 
7827   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7828   // Note: Commutes FSUB operands.
7829   if (N1.getOpcode() == ISD::FMUL &&
7830       (Aggressive || N1->hasOneUse()))
7831     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7832                        DAG.getNode(ISD::FNEG, SL, VT,
7833                                    N1.getOperand(0)),
7834                        N1.getOperand(1), N0);
7835 
7836   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7837   if (N0.getOpcode() == ISD::FNEG &&
7838       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7839       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7840     SDValue N00 = N0.getOperand(0).getOperand(0);
7841     SDValue N01 = N0.getOperand(0).getOperand(1);
7842     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7843                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7844                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7845   }
7846 
7847   // Look through FP_EXTEND nodes to do more combining.
7848   if (AllowFusion && LookThroughFPExt) {
7849     // fold (fsub (fpext (fmul x, y)), z)
7850     //   -> (fma (fpext x), (fpext y), (fneg z))
7851     if (N0.getOpcode() == ISD::FP_EXTEND) {
7852       SDValue N00 = N0.getOperand(0);
7853       if (N00.getOpcode() == ISD::FMUL)
7854         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7855                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7856                                        N00.getOperand(0)),
7857                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858                                        N00.getOperand(1)),
7859                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7860     }
7861 
7862     // fold (fsub x, (fpext (fmul y, z)))
7863     //   -> (fma (fneg (fpext y)), (fpext z), x)
7864     // Note: Commutes FSUB operands.
7865     if (N1.getOpcode() == ISD::FP_EXTEND) {
7866       SDValue N10 = N1.getOperand(0);
7867       if (N10.getOpcode() == ISD::FMUL)
7868         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7869                            DAG.getNode(ISD::FNEG, SL, VT,
7870                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7871                                                    N10.getOperand(0))),
7872                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7873                                        N10.getOperand(1)),
7874                            N0);
7875     }
7876 
7877     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7878     //   -> (fneg (fma (fpext x), (fpext y), z))
7879     // Note: This could be removed with appropriate canonicalization of the
7880     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7881     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7882     // from implementing the canonicalization in visitFSUB.
7883     if (N0.getOpcode() == ISD::FP_EXTEND) {
7884       SDValue N00 = N0.getOperand(0);
7885       if (N00.getOpcode() == ISD::FNEG) {
7886         SDValue N000 = N00.getOperand(0);
7887         if (N000.getOpcode() == ISD::FMUL) {
7888           return DAG.getNode(ISD::FNEG, SL, VT,
7889                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7890                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7891                                                      N000.getOperand(0)),
7892                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7893                                                      N000.getOperand(1)),
7894                                          N1));
7895         }
7896       }
7897     }
7898 
7899     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7900     //   -> (fneg (fma (fpext x)), (fpext y), z)
7901     // Note: This could be removed with appropriate canonicalization of the
7902     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7903     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7904     // from implementing the canonicalization in visitFSUB.
7905     if (N0.getOpcode() == ISD::FNEG) {
7906       SDValue N00 = N0.getOperand(0);
7907       if (N00.getOpcode() == ISD::FP_EXTEND) {
7908         SDValue N000 = N00.getOperand(0);
7909         if (N000.getOpcode() == ISD::FMUL) {
7910           return DAG.getNode(ISD::FNEG, SL, VT,
7911                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7912                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7913                                                      N000.getOperand(0)),
7914                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7915                                                      N000.getOperand(1)),
7916                                          N1));
7917         }
7918       }
7919     }
7920 
7921   }
7922 
7923   // More folding opportunities when target permits.
7924   if ((AllowFusion || HasFMAD) && Aggressive) {
7925     // fold (fsub (fma x, y, (fmul u, v)), z)
7926     //   -> (fma x, y (fma u, v, (fneg z)))
7927     if (N0.getOpcode() == PreferredFusedOpcode &&
7928         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7929       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7930                          N0.getOperand(0), N0.getOperand(1),
7931                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7932                                      N0.getOperand(2).getOperand(0),
7933                                      N0.getOperand(2).getOperand(1),
7934                                      DAG.getNode(ISD::FNEG, SL, VT,
7935                                                  N1)));
7936     }
7937 
7938     // fold (fsub x, (fma y, z, (fmul u, v)))
7939     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7940     if (N1.getOpcode() == PreferredFusedOpcode &&
7941         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7942       SDValue N20 = N1.getOperand(2).getOperand(0);
7943       SDValue N21 = N1.getOperand(2).getOperand(1);
7944       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7945                          DAG.getNode(ISD::FNEG, SL, VT,
7946                                      N1.getOperand(0)),
7947                          N1.getOperand(1),
7948                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7949                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7950 
7951                                      N21, N0));
7952     }
7953 
7954     if (AllowFusion && LookThroughFPExt) {
7955       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7956       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7957       if (N0.getOpcode() == PreferredFusedOpcode) {
7958         SDValue N02 = N0.getOperand(2);
7959         if (N02.getOpcode() == ISD::FP_EXTEND) {
7960           SDValue N020 = N02.getOperand(0);
7961           if (N020.getOpcode() == ISD::FMUL)
7962             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7963                                N0.getOperand(0), N0.getOperand(1),
7964                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7965                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7966                                                        N020.getOperand(0)),
7967                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7968                                                        N020.getOperand(1)),
7969                                            DAG.getNode(ISD::FNEG, SL, VT,
7970                                                        N1)));
7971         }
7972       }
7973 
7974       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7975       //   -> (fma (fpext x), (fpext y),
7976       //           (fma (fpext u), (fpext v), (fneg z)))
7977       // FIXME: This turns two single-precision and one double-precision
7978       // operation into two double-precision operations, which might not be
7979       // interesting for all targets, especially GPUs.
7980       if (N0.getOpcode() == ISD::FP_EXTEND) {
7981         SDValue N00 = N0.getOperand(0);
7982         if (N00.getOpcode() == PreferredFusedOpcode) {
7983           SDValue N002 = N00.getOperand(2);
7984           if (N002.getOpcode() == ISD::FMUL)
7985             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7986                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7987                                            N00.getOperand(0)),
7988                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7989                                            N00.getOperand(1)),
7990                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7991                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7992                                                        N002.getOperand(0)),
7993                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7994                                                        N002.getOperand(1)),
7995                                            DAG.getNode(ISD::FNEG, SL, VT,
7996                                                        N1)));
7997         }
7998       }
7999 
8000       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8001       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8002       if (N1.getOpcode() == PreferredFusedOpcode &&
8003         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8004         SDValue N120 = N1.getOperand(2).getOperand(0);
8005         if (N120.getOpcode() == ISD::FMUL) {
8006           SDValue N1200 = N120.getOperand(0);
8007           SDValue N1201 = N120.getOperand(1);
8008           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8009                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8010                              N1.getOperand(1),
8011                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8012                                          DAG.getNode(ISD::FNEG, SL, VT,
8013                                              DAG.getNode(ISD::FP_EXTEND, SL,
8014                                                          VT, N1200)),
8015                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8016                                                      N1201),
8017                                          N0));
8018         }
8019       }
8020 
8021       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8022       //   -> (fma (fneg (fpext y)), (fpext z),
8023       //           (fma (fneg (fpext u)), (fpext v), x))
8024       // FIXME: This turns two single-precision and one double-precision
8025       // operation into two double-precision operations, which might not be
8026       // interesting for all targets, especially GPUs.
8027       if (N1.getOpcode() == ISD::FP_EXTEND &&
8028         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8029         SDValue N100 = N1.getOperand(0).getOperand(0);
8030         SDValue N101 = N1.getOperand(0).getOperand(1);
8031         SDValue N102 = N1.getOperand(0).getOperand(2);
8032         if (N102.getOpcode() == ISD::FMUL) {
8033           SDValue N1020 = N102.getOperand(0);
8034           SDValue N1021 = N102.getOperand(1);
8035           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8036                              DAG.getNode(ISD::FNEG, SL, VT,
8037                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8038                                                      N100)),
8039                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8040                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8041                                          DAG.getNode(ISD::FNEG, SL, VT,
8042                                              DAG.getNode(ISD::FP_EXTEND, SL,
8043                                                          VT, N1020)),
8044                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8045                                                      N1021),
8046                                          N0));
8047         }
8048       }
8049     }
8050   }
8051 
8052   return SDValue();
8053 }
8054 
8055 /// Try to perform FMA combining on a given FMUL node.
8056 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8057   SDValue N0 = N->getOperand(0);
8058   SDValue N1 = N->getOperand(1);
8059   EVT VT = N->getValueType(0);
8060   SDLoc SL(N);
8061 
8062   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8063 
8064   const TargetOptions &Options = DAG.getTarget().Options;
8065   bool AllowFusion =
8066       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8067 
8068   // Floating-point multiply-add with intermediate rounding.
8069   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8070 
8071   // Floating-point multiply-add without intermediate rounding.
8072   bool HasFMA =
8073       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8074       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8075 
8076   // No valid opcode, do not combine.
8077   if (!HasFMAD && !HasFMA)
8078     return SDValue();
8079 
8080   // Always prefer FMAD to FMA for precision.
8081   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8082   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8083 
8084   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8085   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8086   auto FuseFADD = [&](SDValue X, SDValue Y) {
8087     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8088       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8089       if (XC1 && XC1->isExactlyValue(+1.0))
8090         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8091       if (XC1 && XC1->isExactlyValue(-1.0))
8092         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8093                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8094     }
8095     return SDValue();
8096   };
8097 
8098   if (SDValue FMA = FuseFADD(N0, N1))
8099     return FMA;
8100   if (SDValue FMA = FuseFADD(N1, N0))
8101     return FMA;
8102 
8103   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8104   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8105   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8106   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8107   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8108     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8109       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8110       if (XC0 && XC0->isExactlyValue(+1.0))
8111         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8112                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8113                            Y);
8114       if (XC0 && XC0->isExactlyValue(-1.0))
8115         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8116                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8117                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8118 
8119       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8120       if (XC1 && XC1->isExactlyValue(+1.0))
8121         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8122                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8123       if (XC1 && XC1->isExactlyValue(-1.0))
8124         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8125     }
8126     return SDValue();
8127   };
8128 
8129   if (SDValue FMA = FuseFSUB(N0, N1))
8130     return FMA;
8131   if (SDValue FMA = FuseFSUB(N1, N0))
8132     return FMA;
8133 
8134   return SDValue();
8135 }
8136 
8137 SDValue DAGCombiner::visitFADD(SDNode *N) {
8138   SDValue N0 = N->getOperand(0);
8139   SDValue N1 = N->getOperand(1);
8140   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8141   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8142   EVT VT = N->getValueType(0);
8143   SDLoc DL(N);
8144   const TargetOptions &Options = DAG.getTarget().Options;
8145   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8146 
8147   // fold vector ops
8148   if (VT.isVector())
8149     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8150       return FoldedVOp;
8151 
8152   // fold (fadd c1, c2) -> c1 + c2
8153   if (N0CFP && N1CFP)
8154     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8155 
8156   // canonicalize constant to RHS
8157   if (N0CFP && !N1CFP)
8158     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8159 
8160   // fold (fadd A, (fneg B)) -> (fsub A, B)
8161   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8162       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8163     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8164                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8165 
8166   // fold (fadd (fneg A), B) -> (fsub B, A)
8167   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8168       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8169     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8170                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8171 
8172   // If 'unsafe math' is enabled, fold lots of things.
8173   if (Options.UnsafeFPMath) {
8174     // No FP constant should be created after legalization as Instruction
8175     // Selection pass has a hard time dealing with FP constants.
8176     bool AllowNewConst = (Level < AfterLegalizeDAG);
8177 
8178     // fold (fadd A, 0) -> A
8179     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8180       if (N1C->isZero())
8181         return N0;
8182 
8183     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8184     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8185         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8186       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8187                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8188                                      Flags),
8189                          Flags);
8190 
8191     // If allowed, fold (fadd (fneg x), x) -> 0.0
8192     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8193       return DAG.getConstantFP(0.0, DL, VT);
8194 
8195     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8196     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8197       return DAG.getConstantFP(0.0, DL, VT);
8198 
8199     // We can fold chains of FADD's of the same value into multiplications.
8200     // This transform is not safe in general because we are reducing the number
8201     // of rounding steps.
8202     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8203       if (N0.getOpcode() == ISD::FMUL) {
8204         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8205         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8206 
8207         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8208         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8209           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8210                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8211           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8212         }
8213 
8214         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8215         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8216             N1.getOperand(0) == N1.getOperand(1) &&
8217             N0.getOperand(0) == N1.getOperand(0)) {
8218           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8219                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8220           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8221         }
8222       }
8223 
8224       if (N1.getOpcode() == ISD::FMUL) {
8225         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8226         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8227 
8228         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8229         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8230           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8231                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8232           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8233         }
8234 
8235         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8236         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8237             N0.getOperand(0) == N0.getOperand(1) &&
8238             N1.getOperand(0) == N0.getOperand(0)) {
8239           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8240                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8241           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8242         }
8243       }
8244 
8245       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8246         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8247         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8248         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8249             (N0.getOperand(0) == N1)) {
8250           return DAG.getNode(ISD::FMUL, DL, VT,
8251                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8252         }
8253       }
8254 
8255       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8256         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8257         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8258         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8259             N1.getOperand(0) == N0) {
8260           return DAG.getNode(ISD::FMUL, DL, VT,
8261                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8262         }
8263       }
8264 
8265       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8266       if (AllowNewConst &&
8267           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8268           N0.getOperand(0) == N0.getOperand(1) &&
8269           N1.getOperand(0) == N1.getOperand(1) &&
8270           N0.getOperand(0) == N1.getOperand(0)) {
8271         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8272                            DAG.getConstantFP(4.0, DL, VT), Flags);
8273       }
8274     }
8275   } // enable-unsafe-fp-math
8276 
8277   // FADD -> FMA combines:
8278   if (SDValue Fused = visitFADDForFMACombine(N)) {
8279     AddToWorklist(Fused.getNode());
8280     return Fused;
8281   }
8282 
8283   return SDValue();
8284 }
8285 
8286 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8287   SDValue N0 = N->getOperand(0);
8288   SDValue N1 = N->getOperand(1);
8289   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8290   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8291   EVT VT = N->getValueType(0);
8292   SDLoc dl(N);
8293   const TargetOptions &Options = DAG.getTarget().Options;
8294   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8295 
8296   // fold vector ops
8297   if (VT.isVector())
8298     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8299       return FoldedVOp;
8300 
8301   // fold (fsub c1, c2) -> c1-c2
8302   if (N0CFP && N1CFP)
8303     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8304 
8305   // fold (fsub A, (fneg B)) -> (fadd A, B)
8306   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8307     return DAG.getNode(ISD::FADD, dl, VT, N0,
8308                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8309 
8310   // If 'unsafe math' is enabled, fold lots of things.
8311   if (Options.UnsafeFPMath) {
8312     // (fsub A, 0) -> A
8313     if (N1CFP && N1CFP->isZero())
8314       return N0;
8315 
8316     // (fsub 0, B) -> -B
8317     if (N0CFP && N0CFP->isZero()) {
8318       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8319         return GetNegatedExpression(N1, DAG, LegalOperations);
8320       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8321         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8322     }
8323 
8324     // (fsub x, x) -> 0.0
8325     if (N0 == N1)
8326       return DAG.getConstantFP(0.0f, dl, VT);
8327 
8328     // (fsub x, (fadd x, y)) -> (fneg y)
8329     // (fsub x, (fadd y, x)) -> (fneg y)
8330     if (N1.getOpcode() == ISD::FADD) {
8331       SDValue N10 = N1->getOperand(0);
8332       SDValue N11 = N1->getOperand(1);
8333 
8334       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8335         return GetNegatedExpression(N11, DAG, LegalOperations);
8336 
8337       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8338         return GetNegatedExpression(N10, DAG, LegalOperations);
8339     }
8340   }
8341 
8342   // FSUB -> FMA combines:
8343   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8344     AddToWorklist(Fused.getNode());
8345     return Fused;
8346   }
8347 
8348   return SDValue();
8349 }
8350 
8351 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8352   SDValue N0 = N->getOperand(0);
8353   SDValue N1 = N->getOperand(1);
8354   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8355   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8356   EVT VT = N->getValueType(0);
8357   SDLoc DL(N);
8358   const TargetOptions &Options = DAG.getTarget().Options;
8359   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8360 
8361   // fold vector ops
8362   if (VT.isVector()) {
8363     // This just handles C1 * C2 for vectors. Other vector folds are below.
8364     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8365       return FoldedVOp;
8366   }
8367 
8368   // fold (fmul c1, c2) -> c1*c2
8369   if (N0CFP && N1CFP)
8370     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8371 
8372   // canonicalize constant to RHS
8373   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8374      !isConstantFPBuildVectorOrConstantFP(N1))
8375     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8376 
8377   // fold (fmul A, 1.0) -> A
8378   if (N1CFP && N1CFP->isExactlyValue(1.0))
8379     return N0;
8380 
8381   if (Options.UnsafeFPMath) {
8382     // fold (fmul A, 0) -> 0
8383     if (N1CFP && N1CFP->isZero())
8384       return N1;
8385 
8386     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8387     if (N0.getOpcode() == ISD::FMUL) {
8388       // Fold scalars or any vector constants (not just splats).
8389       // This fold is done in general by InstCombine, but extra fmul insts
8390       // may have been generated during lowering.
8391       SDValue N00 = N0.getOperand(0);
8392       SDValue N01 = N0.getOperand(1);
8393       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8394       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8395       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8396 
8397       // Check 1: Make sure that the first operand of the inner multiply is NOT
8398       // a constant. Otherwise, we may induce infinite looping.
8399       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8400         // Check 2: Make sure that the second operand of the inner multiply and
8401         // the second operand of the outer multiply are constants.
8402         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8403             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8404           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8405           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8406         }
8407       }
8408     }
8409 
8410     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8411     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8412     // during an early run of DAGCombiner can prevent folding with fmuls
8413     // inserted during lowering.
8414     if (N0.getOpcode() == ISD::FADD &&
8415         (N0.getOperand(0) == N0.getOperand(1)) &&
8416         N0.hasOneUse()) {
8417       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8418       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8419       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8420     }
8421   }
8422 
8423   // fold (fmul X, 2.0) -> (fadd X, X)
8424   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8425     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8426 
8427   // fold (fmul X, -1.0) -> (fneg X)
8428   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8429     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8430       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8431 
8432   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8433   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8434     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8435       // Both can be negated for free, check to see if at least one is cheaper
8436       // negated.
8437       if (LHSNeg == 2 || RHSNeg == 2)
8438         return DAG.getNode(ISD::FMUL, DL, VT,
8439                            GetNegatedExpression(N0, DAG, LegalOperations),
8440                            GetNegatedExpression(N1, DAG, LegalOperations),
8441                            Flags);
8442     }
8443   }
8444 
8445   // FMUL -> FMA combines:
8446   if (SDValue Fused = visitFMULForFMACombine(N)) {
8447     AddToWorklist(Fused.getNode());
8448     return Fused;
8449   }
8450 
8451   return SDValue();
8452 }
8453 
8454 SDValue DAGCombiner::visitFMA(SDNode *N) {
8455   SDValue N0 = N->getOperand(0);
8456   SDValue N1 = N->getOperand(1);
8457   SDValue N2 = N->getOperand(2);
8458   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8459   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8460   EVT VT = N->getValueType(0);
8461   SDLoc dl(N);
8462   const TargetOptions &Options = DAG.getTarget().Options;
8463 
8464   // Constant fold FMA.
8465   if (isa<ConstantFPSDNode>(N0) &&
8466       isa<ConstantFPSDNode>(N1) &&
8467       isa<ConstantFPSDNode>(N2)) {
8468     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8469   }
8470 
8471   if (Options.UnsafeFPMath) {
8472     if (N0CFP && N0CFP->isZero())
8473       return N2;
8474     if (N1CFP && N1CFP->isZero())
8475       return N2;
8476   }
8477   // TODO: The FMA node should have flags that propagate to these nodes.
8478   if (N0CFP && N0CFP->isExactlyValue(1.0))
8479     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8480   if (N1CFP && N1CFP->isExactlyValue(1.0))
8481     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8482 
8483   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8484   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8485      !isConstantFPBuildVectorOrConstantFP(N1))
8486     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8487 
8488   // TODO: FMA nodes should have flags that propagate to the created nodes.
8489   // For now, create a Flags object for use with all unsafe math transforms.
8490   SDNodeFlags Flags;
8491   Flags.setUnsafeAlgebra(true);
8492 
8493   if (Options.UnsafeFPMath) {
8494     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8495     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8496         isConstantFPBuildVectorOrConstantFP(N1) &&
8497         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8498       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8499                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8500                                      &Flags), &Flags);
8501     }
8502 
8503     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8504     if (N0.getOpcode() == ISD::FMUL &&
8505         isConstantFPBuildVectorOrConstantFP(N1) &&
8506         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8507       return DAG.getNode(ISD::FMA, dl, VT,
8508                          N0.getOperand(0),
8509                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8510                                      &Flags),
8511                          N2);
8512     }
8513   }
8514 
8515   // (fma x, 1, y) -> (fadd x, y)
8516   // (fma x, -1, y) -> (fadd (fneg x), y)
8517   if (N1CFP) {
8518     if (N1CFP->isExactlyValue(1.0))
8519       // TODO: The FMA node should have flags that propagate to this node.
8520       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8521 
8522     if (N1CFP->isExactlyValue(-1.0) &&
8523         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8524       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8525       AddToWorklist(RHSNeg.getNode());
8526       // TODO: The FMA node should have flags that propagate to this node.
8527       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8528     }
8529   }
8530 
8531   if (Options.UnsafeFPMath) {
8532     // (fma x, c, x) -> (fmul x, (c+1))
8533     if (N1CFP && N0 == N2) {
8534     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8535                          DAG.getNode(ISD::FADD, dl, VT,
8536                                      N1, DAG.getConstantFP(1.0, dl, VT),
8537                                      &Flags), &Flags);
8538     }
8539 
8540     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8541     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8542       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8543                          DAG.getNode(ISD::FADD, dl, VT,
8544                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8545                                      &Flags), &Flags);
8546     }
8547   }
8548 
8549   return SDValue();
8550 }
8551 
8552 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8553 // reciprocal.
8554 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8555 // Notice that this is not always beneficial. One reason is different target
8556 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8557 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8558 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8559 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8560   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8561   const SDNodeFlags *Flags = N->getFlags();
8562   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8563     return SDValue();
8564 
8565   // Skip if current node is a reciprocal.
8566   SDValue N0 = N->getOperand(0);
8567   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8568   if (N0CFP && N0CFP->isExactlyValue(1.0))
8569     return SDValue();
8570 
8571   // Exit early if the target does not want this transform or if there can't
8572   // possibly be enough uses of the divisor to make the transform worthwhile.
8573   SDValue N1 = N->getOperand(1);
8574   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8575   if (!MinUses || N1->use_size() < MinUses)
8576     return SDValue();
8577 
8578   // Find all FDIV users of the same divisor.
8579   // Use a set because duplicates may be present in the user list.
8580   SetVector<SDNode *> Users;
8581   for (auto *U : N1->uses()) {
8582     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8583       // This division is eligible for optimization only if global unsafe math
8584       // is enabled or if this division allows reciprocal formation.
8585       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8586         Users.insert(U);
8587     }
8588   }
8589 
8590   // Now that we have the actual number of divisor uses, make sure it meets
8591   // the minimum threshold specified by the target.
8592   if (Users.size() < MinUses)
8593     return SDValue();
8594 
8595   EVT VT = N->getValueType(0);
8596   SDLoc DL(N);
8597   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8598   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8599 
8600   // Dividend / Divisor -> Dividend * Reciprocal
8601   for (auto *U : Users) {
8602     SDValue Dividend = U->getOperand(0);
8603     if (Dividend != FPOne) {
8604       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8605                                     Reciprocal, Flags);
8606       CombineTo(U, NewNode);
8607     } else if (U != Reciprocal.getNode()) {
8608       // In the absence of fast-math-flags, this user node is always the
8609       // same node as Reciprocal, but with FMF they may be different nodes.
8610       CombineTo(U, Reciprocal);
8611     }
8612   }
8613   return SDValue(N, 0);  // N was replaced.
8614 }
8615 
8616 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8617   SDValue N0 = N->getOperand(0);
8618   SDValue N1 = N->getOperand(1);
8619   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8620   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8621   EVT VT = N->getValueType(0);
8622   SDLoc DL(N);
8623   const TargetOptions &Options = DAG.getTarget().Options;
8624   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8625 
8626   // fold vector ops
8627   if (VT.isVector())
8628     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8629       return FoldedVOp;
8630 
8631   // fold (fdiv c1, c2) -> c1/c2
8632   if (N0CFP && N1CFP)
8633     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8634 
8635   if (Options.UnsafeFPMath) {
8636     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8637     if (N1CFP) {
8638       // Compute the reciprocal 1.0 / c2.
8639       APFloat N1APF = N1CFP->getValueAPF();
8640       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8641       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8642       // Only do the transform if the reciprocal is a legal fp immediate that
8643       // isn't too nasty (eg NaN, denormal, ...).
8644       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8645           (!LegalOperations ||
8646            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8647            // backend)... we should handle this gracefully after Legalize.
8648            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8649            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8650            TLI.isFPImmLegal(Recip, VT)))
8651         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8652                            DAG.getConstantFP(Recip, DL, VT), Flags);
8653     }
8654 
8655     // If this FDIV is part of a reciprocal square root, it may be folded
8656     // into a target-specific square root estimate instruction.
8657     if (N1.getOpcode() == ISD::FSQRT) {
8658       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8659         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8660       }
8661     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8662                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8663       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8664                                           Flags)) {
8665         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8666         AddToWorklist(RV.getNode());
8667         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8668       }
8669     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8670                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8671       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8672                                           Flags)) {
8673         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8674         AddToWorklist(RV.getNode());
8675         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8676       }
8677     } else if (N1.getOpcode() == ISD::FMUL) {
8678       // Look through an FMUL. Even though this won't remove the FDIV directly,
8679       // it's still worthwhile to get rid of the FSQRT if possible.
8680       SDValue SqrtOp;
8681       SDValue OtherOp;
8682       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8683         SqrtOp = N1.getOperand(0);
8684         OtherOp = N1.getOperand(1);
8685       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8686         SqrtOp = N1.getOperand(1);
8687         OtherOp = N1.getOperand(0);
8688       }
8689       if (SqrtOp.getNode()) {
8690         // We found a FSQRT, so try to make this fold:
8691         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8692         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8693           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8694           AddToWorklist(RV.getNode());
8695           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8696         }
8697       }
8698     }
8699 
8700     // Fold into a reciprocal estimate and multiply instead of a real divide.
8701     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8702       AddToWorklist(RV.getNode());
8703       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8704     }
8705   }
8706 
8707   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8708   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8709     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8710       // Both can be negated for free, check to see if at least one is cheaper
8711       // negated.
8712       if (LHSNeg == 2 || RHSNeg == 2)
8713         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8714                            GetNegatedExpression(N0, DAG, LegalOperations),
8715                            GetNegatedExpression(N1, DAG, LegalOperations),
8716                            Flags);
8717     }
8718   }
8719 
8720   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8721     return CombineRepeatedDivisors;
8722 
8723   return SDValue();
8724 }
8725 
8726 SDValue DAGCombiner::visitFREM(SDNode *N) {
8727   SDValue N0 = N->getOperand(0);
8728   SDValue N1 = N->getOperand(1);
8729   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8730   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8731   EVT VT = N->getValueType(0);
8732 
8733   // fold (frem c1, c2) -> fmod(c1,c2)
8734   if (N0CFP && N1CFP)
8735     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8736                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8737 
8738   return SDValue();
8739 }
8740 
8741 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8742   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8743     return SDValue();
8744 
8745   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8746   // For now, create a Flags object for use with all unsafe math transforms.
8747   SDNodeFlags Flags;
8748   Flags.setUnsafeAlgebra(true);
8749 
8750   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8751   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8752   if (!RV)
8753     return SDValue();
8754 
8755   EVT VT = RV.getValueType();
8756   SDLoc DL(N);
8757   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8758   AddToWorklist(RV.getNode());
8759 
8760   // Unfortunately, RV is now NaN if the input was exactly 0.
8761   // Select out this case and force the answer to 0.
8762   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8763   EVT CCVT = getSetCCResultType(VT);
8764   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8765   AddToWorklist(ZeroCmp.getNode());
8766   AddToWorklist(RV.getNode());
8767 
8768   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8769                      ZeroCmp, Zero, RV);
8770 }
8771 
8772 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8773 /// copysign(x, fp_round(y)) -> copysign(x, y)
8774 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8775   SDValue N1 = N->getOperand(1);
8776   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8777        N1.getOpcode() == ISD::FP_ROUND)) {
8778     // Do not optimize out type conversion of f128 type yet.
8779     // For some targets like x86_64, configuration is changed to keep one f128
8780     // value in one SSE register, but instruction selection cannot handle
8781     // FCOPYSIGN on SSE registers yet.
8782     EVT N1VT = N1->getValueType(0);
8783     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8784     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8785   }
8786   return false;
8787 }
8788 
8789 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8790   SDValue N0 = N->getOperand(0);
8791   SDValue N1 = N->getOperand(1);
8792   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8793   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8794   EVT VT = N->getValueType(0);
8795 
8796   if (N0CFP && N1CFP)  // Constant fold
8797     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8798 
8799   if (N1CFP) {
8800     const APFloat& V = N1CFP->getValueAPF();
8801     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8802     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8803     if (!V.isNegative()) {
8804       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8805         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8806     } else {
8807       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8808         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8809                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8810     }
8811   }
8812 
8813   // copysign(fabs(x), y) -> copysign(x, y)
8814   // copysign(fneg(x), y) -> copysign(x, y)
8815   // copysign(copysign(x,z), y) -> copysign(x, y)
8816   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8817       N0.getOpcode() == ISD::FCOPYSIGN)
8818     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8819                        N0.getOperand(0), N1);
8820 
8821   // copysign(x, abs(y)) -> abs(x)
8822   if (N1.getOpcode() == ISD::FABS)
8823     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8824 
8825   // copysign(x, copysign(y,z)) -> copysign(x, z)
8826   if (N1.getOpcode() == ISD::FCOPYSIGN)
8827     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8828                        N0, N1.getOperand(1));
8829 
8830   // copysign(x, fp_extend(y)) -> copysign(x, y)
8831   // copysign(x, fp_round(y)) -> copysign(x, y)
8832   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8833     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8834                        N0, N1.getOperand(0));
8835 
8836   return SDValue();
8837 }
8838 
8839 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8840   SDValue N0 = N->getOperand(0);
8841   EVT VT = N->getValueType(0);
8842   EVT OpVT = N0.getValueType();
8843 
8844   // fold (sint_to_fp c1) -> c1fp
8845   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
8846       // ...but only if the target supports immediate floating-point values
8847       (!LegalOperations ||
8848        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8849     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8850 
8851   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8852   // but UINT_TO_FP is legal on this target, try to convert.
8853   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8854       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8855     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8856     if (DAG.SignBitIsZero(N0))
8857       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8858   }
8859 
8860   // The next optimizations are desirable only if SELECT_CC can be lowered.
8861   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8862     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8863     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8864         !VT.isVector() &&
8865         (!LegalOperations ||
8866          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8867       SDLoc DL(N);
8868       SDValue Ops[] =
8869         { N0.getOperand(0), N0.getOperand(1),
8870           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8871           N0.getOperand(2) };
8872       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8873     }
8874 
8875     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8876     //      (select_cc x, y, 1.0, 0.0,, cc)
8877     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8878         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8879         (!LegalOperations ||
8880          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8881       SDLoc DL(N);
8882       SDValue Ops[] =
8883         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8884           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8885           N0.getOperand(0).getOperand(2) };
8886       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8887     }
8888   }
8889 
8890   return SDValue();
8891 }
8892 
8893 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8894   SDValue N0 = N->getOperand(0);
8895   EVT VT = N->getValueType(0);
8896   EVT OpVT = N0.getValueType();
8897 
8898   // fold (uint_to_fp c1) -> c1fp
8899   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
8900       // ...but only if the target supports immediate floating-point values
8901       (!LegalOperations ||
8902        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8903     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8904 
8905   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8906   // but SINT_TO_FP is legal on this target, try to convert.
8907   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8908       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8909     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8910     if (DAG.SignBitIsZero(N0))
8911       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8912   }
8913 
8914   // The next optimizations are desirable only if SELECT_CC can be lowered.
8915   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8916     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8917 
8918     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8919         (!LegalOperations ||
8920          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8921       SDLoc DL(N);
8922       SDValue Ops[] =
8923         { N0.getOperand(0), N0.getOperand(1),
8924           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8925           N0.getOperand(2) };
8926       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8927     }
8928   }
8929 
8930   return SDValue();
8931 }
8932 
8933 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8934 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8935   SDValue N0 = N->getOperand(0);
8936   EVT VT = N->getValueType(0);
8937 
8938   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8939     return SDValue();
8940 
8941   SDValue Src = N0.getOperand(0);
8942   EVT SrcVT = Src.getValueType();
8943   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8944   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8945 
8946   // We can safely assume the conversion won't overflow the output range,
8947   // because (for example) (uint8_t)18293.f is undefined behavior.
8948 
8949   // Since we can assume the conversion won't overflow, our decision as to
8950   // whether the input will fit in the float should depend on the minimum
8951   // of the input range and output range.
8952 
8953   // This means this is also safe for a signed input and unsigned output, since
8954   // a negative input would lead to undefined behavior.
8955   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8956   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8957   unsigned ActualSize = std::min(InputSize, OutputSize);
8958   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8959 
8960   // We can only fold away the float conversion if the input range can be
8961   // represented exactly in the float range.
8962   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8963     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8964       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8965                                                        : ISD::ZERO_EXTEND;
8966       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8967     }
8968     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8969       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8970     return DAG.getBitcast(VT, Src);
8971   }
8972   return SDValue();
8973 }
8974 
8975 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8976   SDValue N0 = N->getOperand(0);
8977   EVT VT = N->getValueType(0);
8978 
8979   // fold (fp_to_sint c1fp) -> c1
8980   if (isConstantFPBuildVectorOrConstantFP(N0))
8981     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8982 
8983   return FoldIntToFPToInt(N, DAG);
8984 }
8985 
8986 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8987   SDValue N0 = N->getOperand(0);
8988   EVT VT = N->getValueType(0);
8989 
8990   // fold (fp_to_uint c1fp) -> c1
8991   if (isConstantFPBuildVectorOrConstantFP(N0))
8992     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8993 
8994   return FoldIntToFPToInt(N, DAG);
8995 }
8996 
8997 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8998   SDValue N0 = N->getOperand(0);
8999   SDValue N1 = N->getOperand(1);
9000   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9001   EVT VT = N->getValueType(0);
9002 
9003   // fold (fp_round c1fp) -> c1fp
9004   if (N0CFP)
9005     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9006 
9007   // fold (fp_round (fp_extend x)) -> x
9008   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9009     return N0.getOperand(0);
9010 
9011   // fold (fp_round (fp_round x)) -> (fp_round x)
9012   if (N0.getOpcode() == ISD::FP_ROUND) {
9013     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9014     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9015 
9016     // Skip this folding if it results in an fp_round from f80 to f16.
9017     //
9018     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9019     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9020     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9021     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9022     // x86.
9023     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9024       return SDValue();
9025 
9026     // If the first fp_round isn't a value preserving truncation, it might
9027     // introduce a tie in the second fp_round, that wouldn't occur in the
9028     // single-step fp_round we want to fold to.
9029     // In other words, double rounding isn't the same as rounding.
9030     // Also, this is a value preserving truncation iff both fp_round's are.
9031     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9032       SDLoc DL(N);
9033       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9034                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9035     }
9036   }
9037 
9038   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9039   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9040     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9041                               N0.getOperand(0), N1);
9042     AddToWorklist(Tmp.getNode());
9043     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9044                        Tmp, N0.getOperand(1));
9045   }
9046 
9047   return SDValue();
9048 }
9049 
9050 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9051   SDValue N0 = N->getOperand(0);
9052   EVT VT = N->getValueType(0);
9053   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9054   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9055 
9056   // fold (fp_round_inreg c1fp) -> c1fp
9057   if (N0CFP && isTypeLegal(EVT)) {
9058     SDLoc DL(N);
9059     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9060     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9061   }
9062 
9063   return SDValue();
9064 }
9065 
9066 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9067   SDValue N0 = N->getOperand(0);
9068   EVT VT = N->getValueType(0);
9069 
9070   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9071   if (N->hasOneUse() &&
9072       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9073     return SDValue();
9074 
9075   // fold (fp_extend c1fp) -> c1fp
9076   if (isConstantFPBuildVectorOrConstantFP(N0))
9077     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9078 
9079   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9080   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9081       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9082     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9083 
9084   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9085   // value of X.
9086   if (N0.getOpcode() == ISD::FP_ROUND
9087       && N0.getNode()->getConstantOperandVal(1) == 1) {
9088     SDValue In = N0.getOperand(0);
9089     if (In.getValueType() == VT) return In;
9090     if (VT.bitsLT(In.getValueType()))
9091       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9092                          In, N0.getOperand(1));
9093     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9094   }
9095 
9096   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9097   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9098        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9099     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9100     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9101                                      LN0->getChain(),
9102                                      LN0->getBasePtr(), N0.getValueType(),
9103                                      LN0->getMemOperand());
9104     CombineTo(N, ExtLoad);
9105     CombineTo(N0.getNode(),
9106               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9107                           N0.getValueType(), ExtLoad,
9108                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9109               ExtLoad.getValue(1));
9110     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9111   }
9112 
9113   return SDValue();
9114 }
9115 
9116 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9117   SDValue N0 = N->getOperand(0);
9118   EVT VT = N->getValueType(0);
9119 
9120   // fold (fceil c1) -> fceil(c1)
9121   if (isConstantFPBuildVectorOrConstantFP(N0))
9122     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9123 
9124   return SDValue();
9125 }
9126 
9127 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9128   SDValue N0 = N->getOperand(0);
9129   EVT VT = N->getValueType(0);
9130 
9131   // fold (ftrunc c1) -> ftrunc(c1)
9132   if (isConstantFPBuildVectorOrConstantFP(N0))
9133     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9134 
9135   return SDValue();
9136 }
9137 
9138 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9139   SDValue N0 = N->getOperand(0);
9140   EVT VT = N->getValueType(0);
9141 
9142   // fold (ffloor c1) -> ffloor(c1)
9143   if (isConstantFPBuildVectorOrConstantFP(N0))
9144     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9145 
9146   return SDValue();
9147 }
9148 
9149 // FIXME: FNEG and FABS have a lot in common; refactor.
9150 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9151   SDValue N0 = N->getOperand(0);
9152   EVT VT = N->getValueType(0);
9153 
9154   // Constant fold FNEG.
9155   if (isConstantFPBuildVectorOrConstantFP(N0))
9156     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9157 
9158   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9159                          &DAG.getTarget().Options))
9160     return GetNegatedExpression(N0, DAG, LegalOperations);
9161 
9162   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9163   // constant pool values.
9164   if (!TLI.isFNegFree(VT) &&
9165       N0.getOpcode() == ISD::BITCAST &&
9166       N0.getNode()->hasOneUse()) {
9167     SDValue Int = N0.getOperand(0);
9168     EVT IntVT = Int.getValueType();
9169     if (IntVT.isInteger() && !IntVT.isVector()) {
9170       APInt SignMask;
9171       if (N0.getValueType().isVector()) {
9172         // For a vector, get a mask such as 0x80... per scalar element
9173         // and splat it.
9174         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9175         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9176       } else {
9177         // For a scalar, just generate 0x80...
9178         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9179       }
9180       SDLoc DL0(N0);
9181       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9182                         DAG.getConstant(SignMask, DL0, IntVT));
9183       AddToWorklist(Int.getNode());
9184       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9185     }
9186   }
9187 
9188   // (fneg (fmul c, x)) -> (fmul -c, x)
9189   if (N0.getOpcode() == ISD::FMUL &&
9190       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9191     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9192     if (CFP1) {
9193       APFloat CVal = CFP1->getValueAPF();
9194       CVal.changeSign();
9195       if (Level >= AfterLegalizeDAG &&
9196           (TLI.isFPImmLegal(CVal, VT) ||
9197            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9198         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9199                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9200                                        N0.getOperand(1)),
9201                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9202     }
9203   }
9204 
9205   return SDValue();
9206 }
9207 
9208 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9209   SDValue N0 = N->getOperand(0);
9210   SDValue N1 = N->getOperand(1);
9211   EVT VT = N->getValueType(0);
9212   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9213   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9214 
9215   if (N0CFP && N1CFP) {
9216     const APFloat &C0 = N0CFP->getValueAPF();
9217     const APFloat &C1 = N1CFP->getValueAPF();
9218     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9219   }
9220 
9221   // Canonicalize to constant on RHS.
9222   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9223      !isConstantFPBuildVectorOrConstantFP(N1))
9224     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9225 
9226   return SDValue();
9227 }
9228 
9229 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9230   SDValue N0 = N->getOperand(0);
9231   SDValue N1 = N->getOperand(1);
9232   EVT VT = N->getValueType(0);
9233   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9234   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9235 
9236   if (N0CFP && N1CFP) {
9237     const APFloat &C0 = N0CFP->getValueAPF();
9238     const APFloat &C1 = N1CFP->getValueAPF();
9239     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9240   }
9241 
9242   // Canonicalize to constant on RHS.
9243   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9244      !isConstantFPBuildVectorOrConstantFP(N1))
9245     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9246 
9247   return SDValue();
9248 }
9249 
9250 SDValue DAGCombiner::visitFABS(SDNode *N) {
9251   SDValue N0 = N->getOperand(0);
9252   EVT VT = N->getValueType(0);
9253 
9254   // fold (fabs c1) -> fabs(c1)
9255   if (isConstantFPBuildVectorOrConstantFP(N0))
9256     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9257 
9258   // fold (fabs (fabs x)) -> (fabs x)
9259   if (N0.getOpcode() == ISD::FABS)
9260     return N->getOperand(0);
9261 
9262   // fold (fabs (fneg x)) -> (fabs x)
9263   // fold (fabs (fcopysign x, y)) -> (fabs x)
9264   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9265     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9266 
9267   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9268   // constant pool values.
9269   if (!TLI.isFAbsFree(VT) &&
9270       N0.getOpcode() == ISD::BITCAST &&
9271       N0.getNode()->hasOneUse()) {
9272     SDValue Int = N0.getOperand(0);
9273     EVT IntVT = Int.getValueType();
9274     if (IntVT.isInteger() && !IntVT.isVector()) {
9275       APInt SignMask;
9276       if (N0.getValueType().isVector()) {
9277         // For a vector, get a mask such as 0x7f... per scalar element
9278         // and splat it.
9279         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9280         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9281       } else {
9282         // For a scalar, just generate 0x7f...
9283         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9284       }
9285       SDLoc DL(N0);
9286       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9287                         DAG.getConstant(SignMask, DL, IntVT));
9288       AddToWorklist(Int.getNode());
9289       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9290     }
9291   }
9292 
9293   return SDValue();
9294 }
9295 
9296 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9297   SDValue Chain = N->getOperand(0);
9298   SDValue N1 = N->getOperand(1);
9299   SDValue N2 = N->getOperand(2);
9300 
9301   // If N is a constant we could fold this into a fallthrough or unconditional
9302   // branch. However that doesn't happen very often in normal code, because
9303   // Instcombine/SimplifyCFG should have handled the available opportunities.
9304   // If we did this folding here, it would be necessary to update the
9305   // MachineBasicBlock CFG, which is awkward.
9306 
9307   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9308   // on the target.
9309   if (N1.getOpcode() == ISD::SETCC &&
9310       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9311                                    N1.getOperand(0).getValueType())) {
9312     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9313                        Chain, N1.getOperand(2),
9314                        N1.getOperand(0), N1.getOperand(1), N2);
9315   }
9316 
9317   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9318       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9319        (N1.getOperand(0).hasOneUse() &&
9320         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9321     SDNode *Trunc = nullptr;
9322     if (N1.getOpcode() == ISD::TRUNCATE) {
9323       // Look pass the truncate.
9324       Trunc = N1.getNode();
9325       N1 = N1.getOperand(0);
9326     }
9327 
9328     // Match this pattern so that we can generate simpler code:
9329     //
9330     //   %a = ...
9331     //   %b = and i32 %a, 2
9332     //   %c = srl i32 %b, 1
9333     //   brcond i32 %c ...
9334     //
9335     // into
9336     //
9337     //   %a = ...
9338     //   %b = and i32 %a, 2
9339     //   %c = setcc eq %b, 0
9340     //   brcond %c ...
9341     //
9342     // This applies only when the AND constant value has one bit set and the
9343     // SRL constant is equal to the log2 of the AND constant. The back-end is
9344     // smart enough to convert the result into a TEST/JMP sequence.
9345     SDValue Op0 = N1.getOperand(0);
9346     SDValue Op1 = N1.getOperand(1);
9347 
9348     if (Op0.getOpcode() == ISD::AND &&
9349         Op1.getOpcode() == ISD::Constant) {
9350       SDValue AndOp1 = Op0.getOperand(1);
9351 
9352       if (AndOp1.getOpcode() == ISD::Constant) {
9353         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9354 
9355         if (AndConst.isPowerOf2() &&
9356             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9357           SDLoc DL(N);
9358           SDValue SetCC =
9359             DAG.getSetCC(DL,
9360                          getSetCCResultType(Op0.getValueType()),
9361                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9362                          ISD::SETNE);
9363 
9364           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9365                                           MVT::Other, Chain, SetCC, N2);
9366           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9367           // will convert it back to (X & C1) >> C2.
9368           CombineTo(N, NewBRCond, false);
9369           // Truncate is dead.
9370           if (Trunc)
9371             deleteAndRecombine(Trunc);
9372           // Replace the uses of SRL with SETCC
9373           WorklistRemover DeadNodes(*this);
9374           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9375           deleteAndRecombine(N1.getNode());
9376           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9377         }
9378       }
9379     }
9380 
9381     if (Trunc)
9382       // Restore N1 if the above transformation doesn't match.
9383       N1 = N->getOperand(1);
9384   }
9385 
9386   // Transform br(xor(x, y)) -> br(x != y)
9387   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9388   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9389     SDNode *TheXor = N1.getNode();
9390     SDValue Op0 = TheXor->getOperand(0);
9391     SDValue Op1 = TheXor->getOperand(1);
9392     if (Op0.getOpcode() == Op1.getOpcode()) {
9393       // Avoid missing important xor optimizations.
9394       if (SDValue Tmp = visitXOR(TheXor)) {
9395         if (Tmp.getNode() != TheXor) {
9396           DEBUG(dbgs() << "\nReplacing.8 ";
9397                 TheXor->dump(&DAG);
9398                 dbgs() << "\nWith: ";
9399                 Tmp.getNode()->dump(&DAG);
9400                 dbgs() << '\n');
9401           WorklistRemover DeadNodes(*this);
9402           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9403           deleteAndRecombine(TheXor);
9404           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9405                              MVT::Other, Chain, Tmp, N2);
9406         }
9407 
9408         // visitXOR has changed XOR's operands or replaced the XOR completely,
9409         // bail out.
9410         return SDValue(N, 0);
9411       }
9412     }
9413 
9414     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9415       bool Equal = false;
9416       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9417           Op0.getOpcode() == ISD::XOR) {
9418         TheXor = Op0.getNode();
9419         Equal = true;
9420       }
9421 
9422       EVT SetCCVT = N1.getValueType();
9423       if (LegalTypes)
9424         SetCCVT = getSetCCResultType(SetCCVT);
9425       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9426                                    SetCCVT,
9427                                    Op0, Op1,
9428                                    Equal ? ISD::SETEQ : ISD::SETNE);
9429       // Replace the uses of XOR with SETCC
9430       WorklistRemover DeadNodes(*this);
9431       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9432       deleteAndRecombine(N1.getNode());
9433       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9434                          MVT::Other, Chain, SetCC, N2);
9435     }
9436   }
9437 
9438   return SDValue();
9439 }
9440 
9441 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9442 //
9443 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9444   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9445   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9446 
9447   // If N is a constant we could fold this into a fallthrough or unconditional
9448   // branch. However that doesn't happen very often in normal code, because
9449   // Instcombine/SimplifyCFG should have handled the available opportunities.
9450   // If we did this folding here, it would be necessary to update the
9451   // MachineBasicBlock CFG, which is awkward.
9452 
9453   // Use SimplifySetCC to simplify SETCC's.
9454   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9455                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9456                                false);
9457   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9458 
9459   // fold to a simpler setcc
9460   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9461     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9462                        N->getOperand(0), Simp.getOperand(2),
9463                        Simp.getOperand(0), Simp.getOperand(1),
9464                        N->getOperand(4));
9465 
9466   return SDValue();
9467 }
9468 
9469 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9470 /// and that N may be folded in the load / store addressing mode.
9471 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9472                                     SelectionDAG &DAG,
9473                                     const TargetLowering &TLI) {
9474   EVT VT;
9475   unsigned AS;
9476 
9477   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9478     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9479       return false;
9480     VT = LD->getMemoryVT();
9481     AS = LD->getAddressSpace();
9482   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9483     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9484       return false;
9485     VT = ST->getMemoryVT();
9486     AS = ST->getAddressSpace();
9487   } else
9488     return false;
9489 
9490   TargetLowering::AddrMode AM;
9491   if (N->getOpcode() == ISD::ADD) {
9492     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9493     if (Offset)
9494       // [reg +/- imm]
9495       AM.BaseOffs = Offset->getSExtValue();
9496     else
9497       // [reg +/- reg]
9498       AM.Scale = 1;
9499   } else if (N->getOpcode() == ISD::SUB) {
9500     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9501     if (Offset)
9502       // [reg +/- imm]
9503       AM.BaseOffs = -Offset->getSExtValue();
9504     else
9505       // [reg +/- reg]
9506       AM.Scale = 1;
9507   } else
9508     return false;
9509 
9510   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9511                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9512 }
9513 
9514 /// Try turning a load/store into a pre-indexed load/store when the base
9515 /// pointer is an add or subtract and it has other uses besides the load/store.
9516 /// After the transformation, the new indexed load/store has effectively folded
9517 /// the add/subtract in and all of its other uses are redirected to the
9518 /// new load/store.
9519 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9520   if (Level < AfterLegalizeDAG)
9521     return false;
9522 
9523   bool isLoad = true;
9524   SDValue Ptr;
9525   EVT VT;
9526   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9527     if (LD->isIndexed())
9528       return false;
9529     VT = LD->getMemoryVT();
9530     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9531         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9532       return false;
9533     Ptr = LD->getBasePtr();
9534   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9535     if (ST->isIndexed())
9536       return false;
9537     VT = ST->getMemoryVT();
9538     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9539         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9540       return false;
9541     Ptr = ST->getBasePtr();
9542     isLoad = false;
9543   } else {
9544     return false;
9545   }
9546 
9547   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9548   // out.  There is no reason to make this a preinc/predec.
9549   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9550       Ptr.getNode()->hasOneUse())
9551     return false;
9552 
9553   // Ask the target to do addressing mode selection.
9554   SDValue BasePtr;
9555   SDValue Offset;
9556   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9557   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9558     return false;
9559 
9560   // Backends without true r+i pre-indexed forms may need to pass a
9561   // constant base with a variable offset so that constant coercion
9562   // will work with the patterns in canonical form.
9563   bool Swapped = false;
9564   if (isa<ConstantSDNode>(BasePtr)) {
9565     std::swap(BasePtr, Offset);
9566     Swapped = true;
9567   }
9568 
9569   // Don't create a indexed load / store with zero offset.
9570   if (isNullConstant(Offset))
9571     return false;
9572 
9573   // Try turning it into a pre-indexed load / store except when:
9574   // 1) The new base ptr is a frame index.
9575   // 2) If N is a store and the new base ptr is either the same as or is a
9576   //    predecessor of the value being stored.
9577   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9578   //    that would create a cycle.
9579   // 4) All uses are load / store ops that use it as old base ptr.
9580 
9581   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9582   // (plus the implicit offset) to a register to preinc anyway.
9583   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9584     return false;
9585 
9586   // Check #2.
9587   if (!isLoad) {
9588     SDValue Val = cast<StoreSDNode>(N)->getValue();
9589     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9590       return false;
9591   }
9592 
9593   // Caches for hasPredecessorHelper.
9594   SmallPtrSet<const SDNode *, 32> Visited;
9595   SmallVector<const SDNode *, 16> Worklist;
9596 
9597   // If the offset is a constant, there may be other adds of constants that
9598   // can be folded with this one. We should do this to avoid having to keep
9599   // a copy of the original base pointer.
9600   SmallVector<SDNode *, 16> OtherUses;
9601   if (isa<ConstantSDNode>(Offset))
9602     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9603                               UE = BasePtr.getNode()->use_end();
9604          UI != UE; ++UI) {
9605       SDUse &Use = UI.getUse();
9606       // Skip the use that is Ptr and uses of other results from BasePtr's
9607       // node (important for nodes that return multiple results).
9608       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9609         continue;
9610 
9611       if (N->hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9612         continue;
9613 
9614       if (Use.getUser()->getOpcode() != ISD::ADD &&
9615           Use.getUser()->getOpcode() != ISD::SUB) {
9616         OtherUses.clear();
9617         break;
9618       }
9619 
9620       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9621       if (!isa<ConstantSDNode>(Op1)) {
9622         OtherUses.clear();
9623         break;
9624       }
9625 
9626       // FIXME: In some cases, we can be smarter about this.
9627       if (Op1.getValueType() != Offset.getValueType()) {
9628         OtherUses.clear();
9629         break;
9630       }
9631 
9632       OtherUses.push_back(Use.getUser());
9633     }
9634 
9635   if (Swapped)
9636     std::swap(BasePtr, Offset);
9637 
9638   // Now check for #3 and #4.
9639   bool RealUse = false;
9640 
9641   for (SDNode *Use : Ptr.getNode()->uses()) {
9642     if (Use == N)
9643       continue;
9644     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9645       return false;
9646 
9647     // If Ptr may be folded in addressing mode of other use, then it's
9648     // not profitable to do this transformation.
9649     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9650       RealUse = true;
9651   }
9652 
9653   if (!RealUse)
9654     return false;
9655 
9656   SDValue Result;
9657   if (isLoad)
9658     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9659                                 BasePtr, Offset, AM);
9660   else
9661     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9662                                  BasePtr, Offset, AM);
9663   ++PreIndexedNodes;
9664   ++NodesCombined;
9665   DEBUG(dbgs() << "\nReplacing.4 ";
9666         N->dump(&DAG);
9667         dbgs() << "\nWith: ";
9668         Result.getNode()->dump(&DAG);
9669         dbgs() << '\n');
9670   WorklistRemover DeadNodes(*this);
9671   if (isLoad) {
9672     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9673     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9674   } else {
9675     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9676   }
9677 
9678   // Finally, since the node is now dead, remove it from the graph.
9679   deleteAndRecombine(N);
9680 
9681   if (Swapped)
9682     std::swap(BasePtr, Offset);
9683 
9684   // Replace other uses of BasePtr that can be updated to use Ptr
9685   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9686     unsigned OffsetIdx = 1;
9687     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9688       OffsetIdx = 0;
9689     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9690            BasePtr.getNode() && "Expected BasePtr operand");
9691 
9692     // We need to replace ptr0 in the following expression:
9693     //   x0 * offset0 + y0 * ptr0 = t0
9694     // knowing that
9695     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9696     //
9697     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9698     // indexed load/store and the expresion that needs to be re-written.
9699     //
9700     // Therefore, we have:
9701     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9702 
9703     ConstantSDNode *CN =
9704       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9705     int X0, X1, Y0, Y1;
9706     APInt Offset0 = CN->getAPIntValue();
9707     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9708 
9709     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9710     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9711     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9712     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9713 
9714     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9715 
9716     APInt CNV = Offset0;
9717     if (X0 < 0) CNV = -CNV;
9718     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9719     else CNV = CNV - Offset1;
9720 
9721     SDLoc DL(OtherUses[i]);
9722 
9723     // We can now generate the new expression.
9724     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9725     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9726 
9727     SDValue NewUse = DAG.getNode(Opcode,
9728                                  DL,
9729                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9730     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9731     deleteAndRecombine(OtherUses[i]);
9732   }
9733 
9734   // Replace the uses of Ptr with uses of the updated base value.
9735   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9736   deleteAndRecombine(Ptr.getNode());
9737 
9738   return true;
9739 }
9740 
9741 /// Try to combine a load/store with a add/sub of the base pointer node into a
9742 /// post-indexed load/store. The transformation folded the add/subtract into the
9743 /// new indexed load/store effectively and all of its uses are redirected to the
9744 /// new load/store.
9745 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9746   if (Level < AfterLegalizeDAG)
9747     return false;
9748 
9749   bool isLoad = true;
9750   SDValue Ptr;
9751   EVT VT;
9752   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9753     if (LD->isIndexed())
9754       return false;
9755     VT = LD->getMemoryVT();
9756     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9757         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9758       return false;
9759     Ptr = LD->getBasePtr();
9760   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9761     if (ST->isIndexed())
9762       return false;
9763     VT = ST->getMemoryVT();
9764     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9765         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9766       return false;
9767     Ptr = ST->getBasePtr();
9768     isLoad = false;
9769   } else {
9770     return false;
9771   }
9772 
9773   if (Ptr.getNode()->hasOneUse())
9774     return false;
9775 
9776   for (SDNode *Op : Ptr.getNode()->uses()) {
9777     if (Op == N ||
9778         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9779       continue;
9780 
9781     SDValue BasePtr;
9782     SDValue Offset;
9783     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9784     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9785       // Don't create a indexed load / store with zero offset.
9786       if (isNullConstant(Offset))
9787         continue;
9788 
9789       // Try turning it into a post-indexed load / store except when
9790       // 1) All uses are load / store ops that use it as base ptr (and
9791       //    it may be folded as addressing mmode).
9792       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9793       //    nor a successor of N. Otherwise, if Op is folded that would
9794       //    create a cycle.
9795 
9796       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9797         continue;
9798 
9799       // Check for #1.
9800       bool TryNext = false;
9801       for (SDNode *Use : BasePtr.getNode()->uses()) {
9802         if (Use == Ptr.getNode())
9803           continue;
9804 
9805         // If all the uses are load / store addresses, then don't do the
9806         // transformation.
9807         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9808           bool RealUse = false;
9809           for (SDNode *UseUse : Use->uses()) {
9810             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9811               RealUse = true;
9812           }
9813 
9814           if (!RealUse) {
9815             TryNext = true;
9816             break;
9817           }
9818         }
9819       }
9820 
9821       if (TryNext)
9822         continue;
9823 
9824       // Check for #2
9825       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9826         SDValue Result = isLoad
9827           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9828                                BasePtr, Offset, AM)
9829           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9830                                 BasePtr, Offset, AM);
9831         ++PostIndexedNodes;
9832         ++NodesCombined;
9833         DEBUG(dbgs() << "\nReplacing.5 ";
9834               N->dump(&DAG);
9835               dbgs() << "\nWith: ";
9836               Result.getNode()->dump(&DAG);
9837               dbgs() << '\n');
9838         WorklistRemover DeadNodes(*this);
9839         if (isLoad) {
9840           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9841           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9842         } else {
9843           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9844         }
9845 
9846         // Finally, since the node is now dead, remove it from the graph.
9847         deleteAndRecombine(N);
9848 
9849         // Replace the uses of Use with uses of the updated base value.
9850         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9851                                       Result.getValue(isLoad ? 1 : 0));
9852         deleteAndRecombine(Op);
9853         return true;
9854       }
9855     }
9856   }
9857 
9858   return false;
9859 }
9860 
9861 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9862 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9863   ISD::MemIndexedMode AM = LD->getAddressingMode();
9864   assert(AM != ISD::UNINDEXED);
9865   SDValue BP = LD->getOperand(1);
9866   SDValue Inc = LD->getOperand(2);
9867 
9868   // Some backends use TargetConstants for load offsets, but don't expect
9869   // TargetConstants in general ADD nodes. We can convert these constants into
9870   // regular Constants (if the constant is not opaque).
9871   assert((Inc.getOpcode() != ISD::TargetConstant ||
9872           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9873          "Cannot split out indexing using opaque target constants");
9874   if (Inc.getOpcode() == ISD::TargetConstant) {
9875     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9876     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9877                           ConstInc->getValueType(0));
9878   }
9879 
9880   unsigned Opc =
9881       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9882   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9883 }
9884 
9885 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9886   LoadSDNode *LD  = cast<LoadSDNode>(N);
9887   SDValue Chain = LD->getChain();
9888   SDValue Ptr   = LD->getBasePtr();
9889 
9890   // If load is not volatile and there are no uses of the loaded value (and
9891   // the updated indexed value in case of indexed loads), change uses of the
9892   // chain value into uses of the chain input (i.e. delete the dead load).
9893   if (!LD->isVolatile()) {
9894     if (N->getValueType(1) == MVT::Other) {
9895       // Unindexed loads.
9896       if (!N->hasAnyUseOfValue(0)) {
9897         // It's not safe to use the two value CombineTo variant here. e.g.
9898         // v1, chain2 = load chain1, loc
9899         // v2, chain3 = load chain2, loc
9900         // v3         = add v2, c
9901         // Now we replace use of chain2 with chain1.  This makes the second load
9902         // isomorphic to the one we are deleting, and thus makes this load live.
9903         DEBUG(dbgs() << "\nReplacing.6 ";
9904               N->dump(&DAG);
9905               dbgs() << "\nWith chain: ";
9906               Chain.getNode()->dump(&DAG);
9907               dbgs() << "\n");
9908         WorklistRemover DeadNodes(*this);
9909         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9910 
9911         if (N->use_empty())
9912           deleteAndRecombine(N);
9913 
9914         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9915       }
9916     } else {
9917       // Indexed loads.
9918       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9919 
9920       // If this load has an opaque TargetConstant offset, then we cannot split
9921       // the indexing into an add/sub directly (that TargetConstant may not be
9922       // valid for a different type of node, and we cannot convert an opaque
9923       // target constant into a regular constant).
9924       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9925                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9926 
9927       if (!N->hasAnyUseOfValue(0) &&
9928           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9929         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9930         SDValue Index;
9931         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9932           Index = SplitIndexingFromLoad(LD);
9933           // Try to fold the base pointer arithmetic into subsequent loads and
9934           // stores.
9935           AddUsersToWorklist(N);
9936         } else
9937           Index = DAG.getUNDEF(N->getValueType(1));
9938         DEBUG(dbgs() << "\nReplacing.7 ";
9939               N->dump(&DAG);
9940               dbgs() << "\nWith: ";
9941               Undef.getNode()->dump(&DAG);
9942               dbgs() << " and 2 other values\n");
9943         WorklistRemover DeadNodes(*this);
9944         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9945         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9946         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9947         deleteAndRecombine(N);
9948         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9949       }
9950     }
9951   }
9952 
9953   // If this load is directly stored, replace the load value with the stored
9954   // value.
9955   // TODO: Handle store large -> read small portion.
9956   // TODO: Handle TRUNCSTORE/LOADEXT
9957   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9958     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9959       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9960       if (PrevST->getBasePtr() == Ptr &&
9961           PrevST->getValue().getValueType() == N->getValueType(0))
9962       return CombineTo(N, Chain.getOperand(1), Chain);
9963     }
9964   }
9965 
9966   // Try to infer better alignment information than the load already has.
9967   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9968     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9969       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9970         SDValue NewLoad =
9971                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9972                               LD->getValueType(0),
9973                               Chain, Ptr, LD->getPointerInfo(),
9974                               LD->getMemoryVT(),
9975                               LD->isVolatile(), LD->isNonTemporal(),
9976                               LD->isInvariant(), Align, LD->getAAInfo());
9977         if (NewLoad.getNode() != N)
9978           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9979       }
9980     }
9981   }
9982 
9983   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9984                                                   : DAG.getSubtarget().useAA();
9985 #ifndef NDEBUG
9986   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9987       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9988     UseAA = false;
9989 #endif
9990   if (UseAA && LD->isUnindexed()) {
9991     // Walk up chain skipping non-aliasing memory nodes.
9992     SDValue BetterChain = FindBetterChain(N, Chain);
9993 
9994     // If there is a better chain.
9995     if (Chain != BetterChain) {
9996       SDValue ReplLoad;
9997 
9998       // Replace the chain to void dependency.
9999       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10000         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10001                                BetterChain, Ptr, LD->getMemOperand());
10002       } else {
10003         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10004                                   LD->getValueType(0),
10005                                   BetterChain, Ptr, LD->getMemoryVT(),
10006                                   LD->getMemOperand());
10007       }
10008 
10009       // Create token factor to keep old chain connected.
10010       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10011                                   MVT::Other, Chain, ReplLoad.getValue(1));
10012 
10013       // Make sure the new and old chains are cleaned up.
10014       AddToWorklist(Token.getNode());
10015 
10016       // Replace uses with load result and token factor. Don't add users
10017       // to work list.
10018       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10019     }
10020   }
10021 
10022   // Try transforming N to an indexed load.
10023   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10024     return SDValue(N, 0);
10025 
10026   // Try to slice up N to more direct loads if the slices are mapped to
10027   // different register banks or pairing can take place.
10028   if (SliceUpLoad(N))
10029     return SDValue(N, 0);
10030 
10031   return SDValue();
10032 }
10033 
10034 namespace {
10035 /// \brief Helper structure used to slice a load in smaller loads.
10036 /// Basically a slice is obtained from the following sequence:
10037 /// Origin = load Ty1, Base
10038 /// Shift = srl Ty1 Origin, CstTy Amount
10039 /// Inst = trunc Shift to Ty2
10040 ///
10041 /// Then, it will be rewriten into:
10042 /// Slice = load SliceTy, Base + SliceOffset
10043 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10044 ///
10045 /// SliceTy is deduced from the number of bits that are actually used to
10046 /// build Inst.
10047 struct LoadedSlice {
10048   /// \brief Helper structure used to compute the cost of a slice.
10049   struct Cost {
10050     /// Are we optimizing for code size.
10051     bool ForCodeSize;
10052     /// Various cost.
10053     unsigned Loads;
10054     unsigned Truncates;
10055     unsigned CrossRegisterBanksCopies;
10056     unsigned ZExts;
10057     unsigned Shift;
10058 
10059     Cost(bool ForCodeSize = false)
10060         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10061           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10062 
10063     /// \brief Get the cost of one isolated slice.
10064     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10065         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10066           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10067       EVT TruncType = LS.Inst->getValueType(0);
10068       EVT LoadedType = LS.getLoadedType();
10069       if (TruncType != LoadedType &&
10070           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10071         ZExts = 1;
10072     }
10073 
10074     /// \brief Account for slicing gain in the current cost.
10075     /// Slicing provide a few gains like removing a shift or a
10076     /// truncate. This method allows to grow the cost of the original
10077     /// load with the gain from this slice.
10078     void addSliceGain(const LoadedSlice &LS) {
10079       // Each slice saves a truncate.
10080       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10081       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10082                               LS.Inst->getValueType(0)))
10083         ++Truncates;
10084       // If there is a shift amount, this slice gets rid of it.
10085       if (LS.Shift)
10086         ++Shift;
10087       // If this slice can merge a cross register bank copy, account for it.
10088       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10089         ++CrossRegisterBanksCopies;
10090     }
10091 
10092     Cost &operator+=(const Cost &RHS) {
10093       Loads += RHS.Loads;
10094       Truncates += RHS.Truncates;
10095       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10096       ZExts += RHS.ZExts;
10097       Shift += RHS.Shift;
10098       return *this;
10099     }
10100 
10101     bool operator==(const Cost &RHS) const {
10102       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10103              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10104              ZExts == RHS.ZExts && Shift == RHS.Shift;
10105     }
10106 
10107     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10108 
10109     bool operator<(const Cost &RHS) const {
10110       // Assume cross register banks copies are as expensive as loads.
10111       // FIXME: Do we want some more target hooks?
10112       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10113       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10114       // Unless we are optimizing for code size, consider the
10115       // expensive operation first.
10116       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10117         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10118       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10119              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10120     }
10121 
10122     bool operator>(const Cost &RHS) const { return RHS < *this; }
10123 
10124     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10125 
10126     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10127   };
10128   // The last instruction that represent the slice. This should be a
10129   // truncate instruction.
10130   SDNode *Inst;
10131   // The original load instruction.
10132   LoadSDNode *Origin;
10133   // The right shift amount in bits from the original load.
10134   unsigned Shift;
10135   // The DAG from which Origin came from.
10136   // This is used to get some contextual information about legal types, etc.
10137   SelectionDAG *DAG;
10138 
10139   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10140               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10141       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10142 
10143   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10144   /// \return Result is \p BitWidth and has used bits set to 1 and
10145   ///         not used bits set to 0.
10146   APInt getUsedBits() const {
10147     // Reproduce the trunc(lshr) sequence:
10148     // - Start from the truncated value.
10149     // - Zero extend to the desired bit width.
10150     // - Shift left.
10151     assert(Origin && "No original load to compare against.");
10152     unsigned BitWidth = Origin->getValueSizeInBits(0);
10153     assert(Inst && "This slice is not bound to an instruction");
10154     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10155            "Extracted slice is bigger than the whole type!");
10156     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10157     UsedBits.setAllBits();
10158     UsedBits = UsedBits.zext(BitWidth);
10159     UsedBits <<= Shift;
10160     return UsedBits;
10161   }
10162 
10163   /// \brief Get the size of the slice to be loaded in bytes.
10164   unsigned getLoadedSize() const {
10165     unsigned SliceSize = getUsedBits().countPopulation();
10166     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10167     return SliceSize / 8;
10168   }
10169 
10170   /// \brief Get the type that will be loaded for this slice.
10171   /// Note: This may not be the final type for the slice.
10172   EVT getLoadedType() const {
10173     assert(DAG && "Missing context");
10174     LLVMContext &Ctxt = *DAG->getContext();
10175     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10176   }
10177 
10178   /// \brief Get the alignment of the load used for this slice.
10179   unsigned getAlignment() const {
10180     unsigned Alignment = Origin->getAlignment();
10181     unsigned Offset = getOffsetFromBase();
10182     if (Offset != 0)
10183       Alignment = MinAlign(Alignment, Alignment + Offset);
10184     return Alignment;
10185   }
10186 
10187   /// \brief Check if this slice can be rewritten with legal operations.
10188   bool isLegal() const {
10189     // An invalid slice is not legal.
10190     if (!Origin || !Inst || !DAG)
10191       return false;
10192 
10193     // Offsets are for indexed load only, we do not handle that.
10194     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10195       return false;
10196 
10197     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10198 
10199     // Check that the type is legal.
10200     EVT SliceType = getLoadedType();
10201     if (!TLI.isTypeLegal(SliceType))
10202       return false;
10203 
10204     // Check that the load is legal for this type.
10205     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10206       return false;
10207 
10208     // Check that the offset can be computed.
10209     // 1. Check its type.
10210     EVT PtrType = Origin->getBasePtr().getValueType();
10211     if (PtrType == MVT::Untyped || PtrType.isExtended())
10212       return false;
10213 
10214     // 2. Check that it fits in the immediate.
10215     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10216       return false;
10217 
10218     // 3. Check that the computation is legal.
10219     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10220       return false;
10221 
10222     // Check that the zext is legal if it needs one.
10223     EVT TruncateType = Inst->getValueType(0);
10224     if (TruncateType != SliceType &&
10225         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10226       return false;
10227 
10228     return true;
10229   }
10230 
10231   /// \brief Get the offset in bytes of this slice in the original chunk of
10232   /// bits.
10233   /// \pre DAG != nullptr.
10234   uint64_t getOffsetFromBase() const {
10235     assert(DAG && "Missing context.");
10236     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10237     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10238     uint64_t Offset = Shift / 8;
10239     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10240     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10241            "The size of the original loaded type is not a multiple of a"
10242            " byte.");
10243     // If Offset is bigger than TySizeInBytes, it means we are loading all
10244     // zeros. This should have been optimized before in the process.
10245     assert(TySizeInBytes > Offset &&
10246            "Invalid shift amount for given loaded size");
10247     if (IsBigEndian)
10248       Offset = TySizeInBytes - Offset - getLoadedSize();
10249     return Offset;
10250   }
10251 
10252   /// \brief Generate the sequence of instructions to load the slice
10253   /// represented by this object and redirect the uses of this slice to
10254   /// this new sequence of instructions.
10255   /// \pre this->Inst && this->Origin are valid Instructions and this
10256   /// object passed the legal check: LoadedSlice::isLegal returned true.
10257   /// \return The last instruction of the sequence used to load the slice.
10258   SDValue loadSlice() const {
10259     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10260     const SDValue &OldBaseAddr = Origin->getBasePtr();
10261     SDValue BaseAddr = OldBaseAddr;
10262     // Get the offset in that chunk of bytes w.r.t. the endianess.
10263     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10264     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10265     if (Offset) {
10266       // BaseAddr = BaseAddr + Offset.
10267       EVT ArithType = BaseAddr.getValueType();
10268       SDLoc DL(Origin);
10269       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10270                               DAG->getConstant(Offset, DL, ArithType));
10271     }
10272 
10273     // Create the type of the loaded slice according to its size.
10274     EVT SliceType = getLoadedType();
10275 
10276     // Create the load for the slice.
10277     SDValue LastInst = DAG->getLoad(
10278         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10279         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10280         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10281     // If the final type is not the same as the loaded type, this means that
10282     // we have to pad with zero. Create a zero extend for that.
10283     EVT FinalType = Inst->getValueType(0);
10284     if (SliceType != FinalType)
10285       LastInst =
10286           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10287     return LastInst;
10288   }
10289 
10290   /// \brief Check if this slice can be merged with an expensive cross register
10291   /// bank copy. E.g.,
10292   /// i = load i32
10293   /// f = bitcast i32 i to float
10294   bool canMergeExpensiveCrossRegisterBankCopy() const {
10295     if (!Inst || !Inst->hasOneUse())
10296       return false;
10297     SDNode *Use = *Inst->use_begin();
10298     if (Use->getOpcode() != ISD::BITCAST)
10299       return false;
10300     assert(DAG && "Missing context");
10301     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10302     EVT ResVT = Use->getValueType(0);
10303     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10304     const TargetRegisterClass *ArgRC =
10305         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10306     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10307       return false;
10308 
10309     // At this point, we know that we perform a cross-register-bank copy.
10310     // Check if it is expensive.
10311     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10312     // Assume bitcasts are cheap, unless both register classes do not
10313     // explicitly share a common sub class.
10314     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10315       return false;
10316 
10317     // Check if it will be merged with the load.
10318     // 1. Check the alignment constraint.
10319     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10320         ResVT.getTypeForEVT(*DAG->getContext()));
10321 
10322     if (RequiredAlignment > getAlignment())
10323       return false;
10324 
10325     // 2. Check that the load is a legal operation for that type.
10326     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10327       return false;
10328 
10329     // 3. Check that we do not have a zext in the way.
10330     if (Inst->getValueType(0) != getLoadedType())
10331       return false;
10332 
10333     return true;
10334   }
10335 };
10336 }
10337 
10338 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10339 /// \p UsedBits looks like 0..0 1..1 0..0.
10340 static bool areUsedBitsDense(const APInt &UsedBits) {
10341   // If all the bits are one, this is dense!
10342   if (UsedBits.isAllOnesValue())
10343     return true;
10344 
10345   // Get rid of the unused bits on the right.
10346   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10347   // Get rid of the unused bits on the left.
10348   if (NarrowedUsedBits.countLeadingZeros())
10349     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10350   // Check that the chunk of bits is completely used.
10351   return NarrowedUsedBits.isAllOnesValue();
10352 }
10353 
10354 /// \brief Check whether or not \p First and \p Second are next to each other
10355 /// in memory. This means that there is no hole between the bits loaded
10356 /// by \p First and the bits loaded by \p Second.
10357 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10358                                      const LoadedSlice &Second) {
10359   assert(First.Origin == Second.Origin && First.Origin &&
10360          "Unable to match different memory origins.");
10361   APInt UsedBits = First.getUsedBits();
10362   assert((UsedBits & Second.getUsedBits()) == 0 &&
10363          "Slices are not supposed to overlap.");
10364   UsedBits |= Second.getUsedBits();
10365   return areUsedBitsDense(UsedBits);
10366 }
10367 
10368 /// \brief Adjust the \p GlobalLSCost according to the target
10369 /// paring capabilities and the layout of the slices.
10370 /// \pre \p GlobalLSCost should account for at least as many loads as
10371 /// there is in the slices in \p LoadedSlices.
10372 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10373                                  LoadedSlice::Cost &GlobalLSCost) {
10374   unsigned NumberOfSlices = LoadedSlices.size();
10375   // If there is less than 2 elements, no pairing is possible.
10376   if (NumberOfSlices < 2)
10377     return;
10378 
10379   // Sort the slices so that elements that are likely to be next to each
10380   // other in memory are next to each other in the list.
10381   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10382             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10383     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10384     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10385   });
10386   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10387   // First (resp. Second) is the first (resp. Second) potentially candidate
10388   // to be placed in a paired load.
10389   const LoadedSlice *First = nullptr;
10390   const LoadedSlice *Second = nullptr;
10391   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10392                 // Set the beginning of the pair.
10393                                                            First = Second) {
10394 
10395     Second = &LoadedSlices[CurrSlice];
10396 
10397     // If First is NULL, it means we start a new pair.
10398     // Get to the next slice.
10399     if (!First)
10400       continue;
10401 
10402     EVT LoadedType = First->getLoadedType();
10403 
10404     // If the types of the slices are different, we cannot pair them.
10405     if (LoadedType != Second->getLoadedType())
10406       continue;
10407 
10408     // Check if the target supplies paired loads for this type.
10409     unsigned RequiredAlignment = 0;
10410     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10411       // move to the next pair, this type is hopeless.
10412       Second = nullptr;
10413       continue;
10414     }
10415     // Check if we meet the alignment requirement.
10416     if (RequiredAlignment > First->getAlignment())
10417       continue;
10418 
10419     // Check that both loads are next to each other in memory.
10420     if (!areSlicesNextToEachOther(*First, *Second))
10421       continue;
10422 
10423     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10424     --GlobalLSCost.Loads;
10425     // Move to the next pair.
10426     Second = nullptr;
10427   }
10428 }
10429 
10430 /// \brief Check the profitability of all involved LoadedSlice.
10431 /// Currently, it is considered profitable if there is exactly two
10432 /// involved slices (1) which are (2) next to each other in memory, and
10433 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10434 ///
10435 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10436 /// the elements themselves.
10437 ///
10438 /// FIXME: When the cost model will be mature enough, we can relax
10439 /// constraints (1) and (2).
10440 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10441                                 const APInt &UsedBits, bool ForCodeSize) {
10442   unsigned NumberOfSlices = LoadedSlices.size();
10443   if (StressLoadSlicing)
10444     return NumberOfSlices > 1;
10445 
10446   // Check (1).
10447   if (NumberOfSlices != 2)
10448     return false;
10449 
10450   // Check (2).
10451   if (!areUsedBitsDense(UsedBits))
10452     return false;
10453 
10454   // Check (3).
10455   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10456   // The original code has one big load.
10457   OrigCost.Loads = 1;
10458   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10459     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10460     // Accumulate the cost of all the slices.
10461     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10462     GlobalSlicingCost += SliceCost;
10463 
10464     // Account as cost in the original configuration the gain obtained
10465     // with the current slices.
10466     OrigCost.addSliceGain(LS);
10467   }
10468 
10469   // If the target supports paired load, adjust the cost accordingly.
10470   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10471   return OrigCost > GlobalSlicingCost;
10472 }
10473 
10474 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10475 /// operations, split it in the various pieces being extracted.
10476 ///
10477 /// This sort of thing is introduced by SROA.
10478 /// This slicing takes care not to insert overlapping loads.
10479 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10480 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10481   if (Level < AfterLegalizeDAG)
10482     return false;
10483 
10484   LoadSDNode *LD = cast<LoadSDNode>(N);
10485   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10486       !LD->getValueType(0).isInteger())
10487     return false;
10488 
10489   // Keep track of already used bits to detect overlapping values.
10490   // In that case, we will just abort the transformation.
10491   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10492 
10493   SmallVector<LoadedSlice, 4> LoadedSlices;
10494 
10495   // Check if this load is used as several smaller chunks of bits.
10496   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10497   // of computation for each trunc.
10498   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10499        UI != UIEnd; ++UI) {
10500     // Skip the uses of the chain.
10501     if (UI.getUse().getResNo() != 0)
10502       continue;
10503 
10504     SDNode *User = *UI;
10505     unsigned Shift = 0;
10506 
10507     // Check if this is a trunc(lshr).
10508     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10509         isa<ConstantSDNode>(User->getOperand(1))) {
10510       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10511       User = *User->use_begin();
10512     }
10513 
10514     // At this point, User is a Truncate, iff we encountered, trunc or
10515     // trunc(lshr).
10516     if (User->getOpcode() != ISD::TRUNCATE)
10517       return false;
10518 
10519     // The width of the type must be a power of 2 and greater than 8-bits.
10520     // Otherwise the load cannot be represented in LLVM IR.
10521     // Moreover, if we shifted with a non-8-bits multiple, the slice
10522     // will be across several bytes. We do not support that.
10523     unsigned Width = User->getValueSizeInBits(0);
10524     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10525       return 0;
10526 
10527     // Build the slice for this chain of computations.
10528     LoadedSlice LS(User, LD, Shift, &DAG);
10529     APInt CurrentUsedBits = LS.getUsedBits();
10530 
10531     // Check if this slice overlaps with another.
10532     if ((CurrentUsedBits & UsedBits) != 0)
10533       return false;
10534     // Update the bits used globally.
10535     UsedBits |= CurrentUsedBits;
10536 
10537     // Check if the new slice would be legal.
10538     if (!LS.isLegal())
10539       return false;
10540 
10541     // Record the slice.
10542     LoadedSlices.push_back(LS);
10543   }
10544 
10545   // Abort slicing if it does not seem to be profitable.
10546   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10547     return false;
10548 
10549   ++SlicedLoads;
10550 
10551   // Rewrite each chain to use an independent load.
10552   // By construction, each chain can be represented by a unique load.
10553 
10554   // Prepare the argument for the new token factor for all the slices.
10555   SmallVector<SDValue, 8> ArgChains;
10556   for (SmallVectorImpl<LoadedSlice>::const_iterator
10557            LSIt = LoadedSlices.begin(),
10558            LSItEnd = LoadedSlices.end();
10559        LSIt != LSItEnd; ++LSIt) {
10560     SDValue SliceInst = LSIt->loadSlice();
10561     CombineTo(LSIt->Inst, SliceInst, true);
10562     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10563       SliceInst = SliceInst.getOperand(0);
10564     assert(SliceInst->getOpcode() == ISD::LOAD &&
10565            "It takes more than a zext to get to the loaded slice!!");
10566     ArgChains.push_back(SliceInst.getValue(1));
10567   }
10568 
10569   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10570                               ArgChains);
10571   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10572   return true;
10573 }
10574 
10575 /// Check to see if V is (and load (ptr), imm), where the load is having
10576 /// specific bytes cleared out.  If so, return the byte size being masked out
10577 /// and the shift amount.
10578 static std::pair<unsigned, unsigned>
10579 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10580   std::pair<unsigned, unsigned> Result(0, 0);
10581 
10582   // Check for the structure we're looking for.
10583   if (V->getOpcode() != ISD::AND ||
10584       !isa<ConstantSDNode>(V->getOperand(1)) ||
10585       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10586     return Result;
10587 
10588   // Check the chain and pointer.
10589   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10590   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10591 
10592   // The store should be chained directly to the load or be an operand of a
10593   // tokenfactor.
10594   if (LD == Chain.getNode())
10595     ; // ok.
10596   else if (Chain->getOpcode() != ISD::TokenFactor)
10597     return Result; // Fail.
10598   else {
10599     bool isOk = false;
10600     for (const SDValue &ChainOp : Chain->op_values())
10601       if (ChainOp.getNode() == LD) {
10602         isOk = true;
10603         break;
10604       }
10605     if (!isOk) return Result;
10606   }
10607 
10608   // This only handles simple types.
10609   if (V.getValueType() != MVT::i16 &&
10610       V.getValueType() != MVT::i32 &&
10611       V.getValueType() != MVT::i64)
10612     return Result;
10613 
10614   // Check the constant mask.  Invert it so that the bits being masked out are
10615   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10616   // follow the sign bit for uniformity.
10617   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10618   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10619   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10620   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10621   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10622   if (NotMaskLZ == 64) return Result;  // All zero mask.
10623 
10624   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10625   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10626     return Result;
10627 
10628   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10629   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10630     NotMaskLZ -= 64-V.getValueSizeInBits();
10631 
10632   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10633   switch (MaskedBytes) {
10634   case 1:
10635   case 2:
10636   case 4: break;
10637   default: return Result; // All one mask, or 5-byte mask.
10638   }
10639 
10640   // Verify that the first bit starts at a multiple of mask so that the access
10641   // is aligned the same as the access width.
10642   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10643 
10644   Result.first = MaskedBytes;
10645   Result.second = NotMaskTZ/8;
10646   return Result;
10647 }
10648 
10649 
10650 /// Check to see if IVal is something that provides a value as specified by
10651 /// MaskInfo. If so, replace the specified store with a narrower store of
10652 /// truncated IVal.
10653 static SDNode *
10654 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10655                                 SDValue IVal, StoreSDNode *St,
10656                                 DAGCombiner *DC) {
10657   unsigned NumBytes = MaskInfo.first;
10658   unsigned ByteShift = MaskInfo.second;
10659   SelectionDAG &DAG = DC->getDAG();
10660 
10661   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10662   // that uses this.  If not, this is not a replacement.
10663   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10664                                   ByteShift*8, (ByteShift+NumBytes)*8);
10665   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10666 
10667   // Check that it is legal on the target to do this.  It is legal if the new
10668   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10669   // legalization.
10670   MVT VT = MVT::getIntegerVT(NumBytes*8);
10671   if (!DC->isTypeLegal(VT))
10672     return nullptr;
10673 
10674   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10675   // shifted by ByteShift and truncated down to NumBytes.
10676   if (ByteShift) {
10677     SDLoc DL(IVal);
10678     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10679                        DAG.getConstant(ByteShift*8, DL,
10680                                     DC->getShiftAmountTy(IVal.getValueType())));
10681   }
10682 
10683   // Figure out the offset for the store and the alignment of the access.
10684   unsigned StOffset;
10685   unsigned NewAlign = St->getAlignment();
10686 
10687   if (DAG.getDataLayout().isLittleEndian())
10688     StOffset = ByteShift;
10689   else
10690     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10691 
10692   SDValue Ptr = St->getBasePtr();
10693   if (StOffset) {
10694     SDLoc DL(IVal);
10695     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10696                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10697     NewAlign = MinAlign(NewAlign, StOffset);
10698   }
10699 
10700   // Truncate down to the new size.
10701   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10702 
10703   ++OpsNarrowed;
10704   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10705                       St->getPointerInfo().getWithOffset(StOffset),
10706                       false, false, NewAlign).getNode();
10707 }
10708 
10709 
10710 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10711 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10712 /// narrowing the load and store if it would end up being a win for performance
10713 /// or code size.
10714 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10715   StoreSDNode *ST  = cast<StoreSDNode>(N);
10716   if (ST->isVolatile())
10717     return SDValue();
10718 
10719   SDValue Chain = ST->getChain();
10720   SDValue Value = ST->getValue();
10721   SDValue Ptr   = ST->getBasePtr();
10722   EVT VT = Value.getValueType();
10723 
10724   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10725     return SDValue();
10726 
10727   unsigned Opc = Value.getOpcode();
10728 
10729   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10730   // is a byte mask indicating a consecutive number of bytes, check to see if
10731   // Y is known to provide just those bytes.  If so, we try to replace the
10732   // load + replace + store sequence with a single (narrower) store, which makes
10733   // the load dead.
10734   if (Opc == ISD::OR) {
10735     std::pair<unsigned, unsigned> MaskedLoad;
10736     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10737     if (MaskedLoad.first)
10738       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10739                                                   Value.getOperand(1), ST,this))
10740         return SDValue(NewST, 0);
10741 
10742     // Or is commutative, so try swapping X and Y.
10743     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10744     if (MaskedLoad.first)
10745       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10746                                                   Value.getOperand(0), ST,this))
10747         return SDValue(NewST, 0);
10748   }
10749 
10750   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10751       Value.getOperand(1).getOpcode() != ISD::Constant)
10752     return SDValue();
10753 
10754   SDValue N0 = Value.getOperand(0);
10755   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10756       Chain == SDValue(N0.getNode(), 1)) {
10757     LoadSDNode *LD = cast<LoadSDNode>(N0);
10758     if (LD->getBasePtr() != Ptr ||
10759         LD->getPointerInfo().getAddrSpace() !=
10760         ST->getPointerInfo().getAddrSpace())
10761       return SDValue();
10762 
10763     // Find the type to narrow it the load / op / store to.
10764     SDValue N1 = Value.getOperand(1);
10765     unsigned BitWidth = N1.getValueSizeInBits();
10766     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10767     if (Opc == ISD::AND)
10768       Imm ^= APInt::getAllOnesValue(BitWidth);
10769     if (Imm == 0 || Imm.isAllOnesValue())
10770       return SDValue();
10771     unsigned ShAmt = Imm.countTrailingZeros();
10772     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10773     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10774     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10775     // The narrowing should be profitable, the load/store operation should be
10776     // legal (or custom) and the store size should be equal to the NewVT width.
10777     while (NewBW < BitWidth &&
10778            (NewVT.getStoreSizeInBits() != NewBW ||
10779             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10780             !TLI.isNarrowingProfitable(VT, NewVT))) {
10781       NewBW = NextPowerOf2(NewBW);
10782       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10783     }
10784     if (NewBW >= BitWidth)
10785       return SDValue();
10786 
10787     // If the lsb changed does not start at the type bitwidth boundary,
10788     // start at the previous one.
10789     if (ShAmt % NewBW)
10790       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10791     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10792                                    std::min(BitWidth, ShAmt + NewBW));
10793     if ((Imm & Mask) == Imm) {
10794       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10795       if (Opc == ISD::AND)
10796         NewImm ^= APInt::getAllOnesValue(NewBW);
10797       uint64_t PtrOff = ShAmt / 8;
10798       // For big endian targets, we need to adjust the offset to the pointer to
10799       // load the correct bytes.
10800       if (DAG.getDataLayout().isBigEndian())
10801         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10802 
10803       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10804       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10805       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10806         return SDValue();
10807 
10808       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10809                                    Ptr.getValueType(), Ptr,
10810                                    DAG.getConstant(PtrOff, SDLoc(LD),
10811                                                    Ptr.getValueType()));
10812       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10813                                   LD->getChain(), NewPtr,
10814                                   LD->getPointerInfo().getWithOffset(PtrOff),
10815                                   LD->isVolatile(), LD->isNonTemporal(),
10816                                   LD->isInvariant(), NewAlign,
10817                                   LD->getAAInfo());
10818       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10819                                    DAG.getConstant(NewImm, SDLoc(Value),
10820                                                    NewVT));
10821       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10822                                    NewVal, NewPtr,
10823                                    ST->getPointerInfo().getWithOffset(PtrOff),
10824                                    false, false, NewAlign);
10825 
10826       AddToWorklist(NewPtr.getNode());
10827       AddToWorklist(NewLD.getNode());
10828       AddToWorklist(NewVal.getNode());
10829       WorklistRemover DeadNodes(*this);
10830       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10831       ++OpsNarrowed;
10832       return NewST;
10833     }
10834   }
10835 
10836   return SDValue();
10837 }
10838 
10839 /// For a given floating point load / store pair, if the load value isn't used
10840 /// by any other operations, then consider transforming the pair to integer
10841 /// load / store operations if the target deems the transformation profitable.
10842 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10843   StoreSDNode *ST  = cast<StoreSDNode>(N);
10844   SDValue Chain = ST->getChain();
10845   SDValue Value = ST->getValue();
10846   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10847       Value.hasOneUse() &&
10848       Chain == SDValue(Value.getNode(), 1)) {
10849     LoadSDNode *LD = cast<LoadSDNode>(Value);
10850     EVT VT = LD->getMemoryVT();
10851     if (!VT.isFloatingPoint() ||
10852         VT != ST->getMemoryVT() ||
10853         LD->isNonTemporal() ||
10854         ST->isNonTemporal() ||
10855         LD->getPointerInfo().getAddrSpace() != 0 ||
10856         ST->getPointerInfo().getAddrSpace() != 0)
10857       return SDValue();
10858 
10859     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10860     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10861         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10862         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10863         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10864       return SDValue();
10865 
10866     unsigned LDAlign = LD->getAlignment();
10867     unsigned STAlign = ST->getAlignment();
10868     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10869     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10870     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10871       return SDValue();
10872 
10873     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10874                                 LD->getChain(), LD->getBasePtr(),
10875                                 LD->getPointerInfo(),
10876                                 false, false, false, LDAlign);
10877 
10878     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10879                                  NewLD, ST->getBasePtr(),
10880                                  ST->getPointerInfo(),
10881                                  false, false, STAlign);
10882 
10883     AddToWorklist(NewLD.getNode());
10884     AddToWorklist(NewST.getNode());
10885     WorklistRemover DeadNodes(*this);
10886     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10887     ++LdStFP2Int;
10888     return NewST;
10889   }
10890 
10891   return SDValue();
10892 }
10893 
10894 namespace {
10895 /// Helper struct to parse and store a memory address as base + index + offset.
10896 /// We ignore sign extensions when it is safe to do so.
10897 /// The following two expressions are not equivalent. To differentiate we need
10898 /// to store whether there was a sign extension involved in the index
10899 /// computation.
10900 ///  (load (i64 add (i64 copyfromreg %c)
10901 ///                 (i64 signextend (add (i8 load %index)
10902 ///                                      (i8 1))))
10903 /// vs
10904 ///
10905 /// (load (i64 add (i64 copyfromreg %c)
10906 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10907 ///                                         (i32 1)))))
10908 struct BaseIndexOffset {
10909   SDValue Base;
10910   SDValue Index;
10911   int64_t Offset;
10912   bool IsIndexSignExt;
10913 
10914   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10915 
10916   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10917                   bool IsIndexSignExt) :
10918     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10919 
10920   bool equalBaseIndex(const BaseIndexOffset &Other) {
10921     return Other.Base == Base && Other.Index == Index &&
10922       Other.IsIndexSignExt == IsIndexSignExt;
10923   }
10924 
10925   /// Parses tree in Ptr for base, index, offset addresses.
10926   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
10927     bool IsIndexSignExt = false;
10928 
10929     // Split up a folded GlobalAddress+Offset into its component parts.
10930     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
10931       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
10932         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
10933                                                     SDLoc(GA),
10934                                                     GA->getValueType(0),
10935                                                     /*Offset=*/0,
10936                                                     /*isTargetGA=*/false,
10937                                                     GA->getTargetFlags()),
10938                                SDValue(),
10939                                GA->getOffset(),
10940                                IsIndexSignExt);
10941       }
10942 
10943     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10944     // instruction, then it could be just the BASE or everything else we don't
10945     // know how to handle. Just use Ptr as BASE and give up.
10946     if (Ptr->getOpcode() != ISD::ADD)
10947       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10948 
10949     // We know that we have at least an ADD instruction. Try to pattern match
10950     // the simple case of BASE + OFFSET.
10951     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10952       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10953       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10954                               IsIndexSignExt);
10955     }
10956 
10957     // Inside a loop the current BASE pointer is calculated using an ADD and a
10958     // MUL instruction. In this case Ptr is the actual BASE pointer.
10959     // (i64 add (i64 %array_ptr)
10960     //          (i64 mul (i64 %induction_var)
10961     //                   (i64 %element_size)))
10962     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10963       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10964 
10965     // Look at Base + Index + Offset cases.
10966     SDValue Base = Ptr->getOperand(0);
10967     SDValue IndexOffset = Ptr->getOperand(1);
10968 
10969     // Skip signextends.
10970     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10971       IndexOffset = IndexOffset->getOperand(0);
10972       IsIndexSignExt = true;
10973     }
10974 
10975     // Either the case of Base + Index (no offset) or something else.
10976     if (IndexOffset->getOpcode() != ISD::ADD)
10977       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10978 
10979     // Now we have the case of Base + Index + offset.
10980     SDValue Index = IndexOffset->getOperand(0);
10981     SDValue Offset = IndexOffset->getOperand(1);
10982 
10983     if (!isa<ConstantSDNode>(Offset))
10984       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10985 
10986     // Ignore signextends.
10987     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10988       Index = Index->getOperand(0);
10989       IsIndexSignExt = true;
10990     } else IsIndexSignExt = false;
10991 
10992     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10993     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10994   }
10995 };
10996 } // namespace
10997 
10998 // This is a helper function for visitMUL to check the profitability
10999 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11000 // MulNode is the original multiply, AddNode is (add x, c1),
11001 // and ConstNode is c2.
11002 //
11003 // If the (add x, c1) has multiple uses, we could increase
11004 // the number of adds if we make this transformation.
11005 // It would only be worth doing this if we can remove a
11006 // multiply in the process. Check for that here.
11007 // To illustrate:
11008 //     (A + c1) * c3
11009 //     (A + c2) * c3
11010 // We're checking for cases where we have common "c3 * A" expressions.
11011 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11012                                               SDValue &AddNode,
11013                                               SDValue &ConstNode) {
11014   APInt Val;
11015 
11016   // If the add only has one use, this would be OK to do.
11017   if (AddNode.getNode()->hasOneUse())
11018     return true;
11019 
11020   // Walk all the users of the constant with which we're multiplying.
11021   for (SDNode *Use : ConstNode->uses()) {
11022 
11023     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11024       continue;
11025 
11026     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11027       SDNode *OtherOp;
11028       SDNode *MulVar = AddNode.getOperand(0).getNode();
11029 
11030       // OtherOp is what we're multiplying against the constant.
11031       if (Use->getOperand(0) == ConstNode)
11032         OtherOp = Use->getOperand(1).getNode();
11033       else
11034         OtherOp = Use->getOperand(0).getNode();
11035 
11036       // Check to see if multiply is with the same operand of our "add".
11037       //
11038       //     ConstNode  = CONST
11039       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11040       //     ...
11041       //     AddNode  = (A + c1)  <-- MulVar is A.
11042       //         = AddNode * ConstNode   <-- current visiting instruction.
11043       //
11044       // If we make this transformation, we will have a common
11045       // multiply (ConstNode * A) that we can save.
11046       if (OtherOp == MulVar)
11047         return true;
11048 
11049       // Now check to see if a future expansion will give us a common
11050       // multiply.
11051       //
11052       //     ConstNode  = CONST
11053       //     AddNode    = (A + c1)
11054       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11055       //     ...
11056       //     OtherOp = (A + c2)
11057       //     Use     = OtherOp * ConstNode <-- visiting Use.
11058       //
11059       // If we make this transformation, we will have a common
11060       // multiply (CONST * A) after we also do the same transformation
11061       // to the "t2" instruction.
11062       if (OtherOp->getOpcode() == ISD::ADD &&
11063           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11064           OtherOp->getOperand(0).getNode() == MulVar)
11065         return true;
11066     }
11067   }
11068 
11069   // Didn't find a case where this would be profitable.
11070   return false;
11071 }
11072 
11073 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11074                                                   SDLoc SL,
11075                                                   ArrayRef<MemOpLink> Stores,
11076                                                   SmallVectorImpl<SDValue> &Chains,
11077                                                   EVT Ty) const {
11078   SmallVector<SDValue, 8> BuildVector;
11079 
11080   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11081     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11082     Chains.push_back(St->getChain());
11083     BuildVector.push_back(St->getValue());
11084   }
11085 
11086   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
11087 }
11088 
11089 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11090                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11091                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11092   // Make sure we have something to merge.
11093   if (NumStores < 2)
11094     return false;
11095 
11096   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11097   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11098   unsigned LatestNodeUsed = 0;
11099 
11100   for (unsigned i=0; i < NumStores; ++i) {
11101     // Find a chain for the new wide-store operand. Notice that some
11102     // of the store nodes that we found may not be selected for inclusion
11103     // in the wide store. The chain we use needs to be the chain of the
11104     // latest store node which is *used* and replaced by the wide store.
11105     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11106       LatestNodeUsed = i;
11107   }
11108 
11109   SmallVector<SDValue, 8> Chains;
11110 
11111   // The latest Node in the DAG.
11112   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11113   SDLoc DL(StoreNodes[0].MemNode);
11114 
11115   SDValue StoredVal;
11116   if (UseVector) {
11117     bool IsVec = MemVT.isVector();
11118     unsigned Elts = NumStores;
11119     if (IsVec) {
11120       // When merging vector stores, get the total number of elements.
11121       Elts *= MemVT.getVectorNumElements();
11122     }
11123     // Get the type for the merged vector store.
11124     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11125     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11126 
11127     if (IsConstantSrc) {
11128       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11129     } else {
11130       SmallVector<SDValue, 8> Ops;
11131       for (unsigned i = 0; i < NumStores; ++i) {
11132         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11133         SDValue Val = St->getValue();
11134         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11135         if (Val.getValueType() != MemVT)
11136           return false;
11137         Ops.push_back(Val);
11138         Chains.push_back(St->getChain());
11139       }
11140 
11141       // Build the extracted vector elements back into a vector.
11142       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11143                               DL, Ty, Ops);    }
11144   } else {
11145     // We should always use a vector store when merging extracted vector
11146     // elements, so this path implies a store of constants.
11147     assert(IsConstantSrc && "Merged vector elements should use vector store");
11148 
11149     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11150     APInt StoreInt(SizeInBits, 0);
11151 
11152     // Construct a single integer constant which is made of the smaller
11153     // constant inputs.
11154     bool IsLE = DAG.getDataLayout().isLittleEndian();
11155     for (unsigned i = 0; i < NumStores; ++i) {
11156       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11157       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11158       Chains.push_back(St->getChain());
11159 
11160       SDValue Val = St->getValue();
11161       StoreInt <<= ElementSizeBytes * 8;
11162       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11163         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11164       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11165         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11166       } else {
11167         llvm_unreachable("Invalid constant element type");
11168       }
11169     }
11170 
11171     // Create the new Load and Store operations.
11172     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11173     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11174   }
11175 
11176   assert(!Chains.empty());
11177 
11178   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11179   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11180                                   FirstInChain->getBasePtr(),
11181                                   FirstInChain->getPointerInfo(),
11182                                   false, false,
11183                                   FirstInChain->getAlignment());
11184 
11185   // Replace the last store with the new store
11186   CombineTo(LatestOp, NewStore);
11187   // Erase all other stores.
11188   for (unsigned i = 0; i < NumStores; ++i) {
11189     if (StoreNodes[i].MemNode == LatestOp)
11190       continue;
11191     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11192     // ReplaceAllUsesWith will replace all uses that existed when it was
11193     // called, but graph optimizations may cause new ones to appear. For
11194     // example, the case in pr14333 looks like
11195     //
11196     //  St's chain -> St -> another store -> X
11197     //
11198     // And the only difference from St to the other store is the chain.
11199     // When we change it's chain to be St's chain they become identical,
11200     // get CSEed and the net result is that X is now a use of St.
11201     // Since we know that St is redundant, just iterate.
11202     while (!St->use_empty())
11203       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11204     deleteAndRecombine(St);
11205   }
11206 
11207   return true;
11208 }
11209 
11210 void DAGCombiner::getStoreMergeAndAliasCandidates(
11211     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11212     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11213   // This holds the base pointer, index, and the offset in bytes from the base
11214   // pointer.
11215   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11216 
11217   // We must have a base and an offset.
11218   if (!BasePtr.Base.getNode())
11219     return;
11220 
11221   // Do not handle stores to undef base pointers.
11222   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11223     return;
11224 
11225   // Walk up the chain and look for nodes with offsets from the same
11226   // base pointer. Stop when reaching an instruction with a different kind
11227   // or instruction which has a different base pointer.
11228   EVT MemVT = St->getMemoryVT();
11229   unsigned Seq = 0;
11230   StoreSDNode *Index = St;
11231 
11232 
11233   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11234                                                   : DAG.getSubtarget().useAA();
11235 
11236   if (UseAA) {
11237     // Look at other users of the same chain. Stores on the same chain do not
11238     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11239     // to be on the same chain, so don't bother looking at adjacent chains.
11240 
11241     SDValue Chain = St->getChain();
11242     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11243       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11244         if (I.getOperandNo() != 0)
11245           continue;
11246 
11247         if (OtherST->isVolatile() || OtherST->isIndexed())
11248           continue;
11249 
11250         if (OtherST->getMemoryVT() != MemVT)
11251           continue;
11252 
11253         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11254 
11255         if (Ptr.equalBaseIndex(BasePtr))
11256           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11257       }
11258     }
11259 
11260     return;
11261   }
11262 
11263   while (Index) {
11264     // If the chain has more than one use, then we can't reorder the mem ops.
11265     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11266       break;
11267 
11268     // Find the base pointer and offset for this memory node.
11269     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11270 
11271     // Check that the base pointer is the same as the original one.
11272     if (!Ptr.equalBaseIndex(BasePtr))
11273       break;
11274 
11275     // The memory operands must not be volatile.
11276     if (Index->isVolatile() || Index->isIndexed())
11277       break;
11278 
11279     // No truncation.
11280     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11281       if (St->isTruncatingStore())
11282         break;
11283 
11284     // The stored memory type must be the same.
11285     if (Index->getMemoryVT() != MemVT)
11286       break;
11287 
11288     // We do not allow under-aligned stores in order to prevent
11289     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11290     // be irrelevant here; what MATTERS is that we not move memory
11291     // operations that potentially overlap past each-other.
11292     if (Index->getAlignment() < MemVT.getStoreSize())
11293       break;
11294 
11295     // We found a potential memory operand to merge.
11296     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11297 
11298     // Find the next memory operand in the chain. If the next operand in the
11299     // chain is a store then move up and continue the scan with the next
11300     // memory operand. If the next operand is a load save it and use alias
11301     // information to check if it interferes with anything.
11302     SDNode *NextInChain = Index->getChain().getNode();
11303     while (1) {
11304       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11305         // We found a store node. Use it for the next iteration.
11306         Index = STn;
11307         break;
11308       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11309         if (Ldn->isVolatile()) {
11310           Index = nullptr;
11311           break;
11312         }
11313 
11314         // Save the load node for later. Continue the scan.
11315         AliasLoadNodes.push_back(Ldn);
11316         NextInChain = Ldn->getChain().getNode();
11317         continue;
11318       } else {
11319         Index = nullptr;
11320         break;
11321       }
11322     }
11323   }
11324 }
11325 
11326 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11327   if (OptLevel == CodeGenOpt::None)
11328     return false;
11329 
11330   EVT MemVT = St->getMemoryVT();
11331   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11332   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11333       Attribute::NoImplicitFloat);
11334 
11335   // This function cannot currently deal with non-byte-sized memory sizes.
11336   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11337     return false;
11338 
11339   if (!MemVT.isSimple())
11340     return false;
11341 
11342   // Perform an early exit check. Do not bother looking at stored values that
11343   // are not constants, loads, or extracted vector elements.
11344   SDValue StoredVal = St->getValue();
11345   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11346   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11347                        isa<ConstantFPSDNode>(StoredVal);
11348   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11349                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11350 
11351   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11352     return false;
11353 
11354   // Don't merge vectors into wider vectors if the source data comes from loads.
11355   // TODO: This restriction can be lifted by using logic similar to the
11356   // ExtractVecSrc case.
11357   if (MemVT.isVector() && IsLoadSrc)
11358     return false;
11359 
11360   // Only look at ends of store sequences.
11361   SDValue Chain = SDValue(St, 0);
11362   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11363     return false;
11364 
11365   // Save the LoadSDNodes that we find in the chain.
11366   // We need to make sure that these nodes do not interfere with
11367   // any of the store nodes.
11368   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11369 
11370   // Save the StoreSDNodes that we find in the chain.
11371   SmallVector<MemOpLink, 8> StoreNodes;
11372 
11373   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11374 
11375   // Check if there is anything to merge.
11376   if (StoreNodes.size() < 2)
11377     return false;
11378 
11379   // Sort the memory operands according to their distance from the
11380   // base pointer.  As a secondary criteria: make sure stores coming
11381   // later in the code come first in the list. This is important for
11382   // the non-UseAA case, because we're merging stores into the FINAL
11383   // store along a chain which potentially contains aliasing stores.
11384   // Thus, if there are multiple stores to the same address, the last
11385   // one can be considered for merging but not the others.
11386   std::sort(StoreNodes.begin(), StoreNodes.end(),
11387             [](MemOpLink LHS, MemOpLink RHS) {
11388     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11389            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11390             LHS.SequenceNum < RHS.SequenceNum);
11391   });
11392 
11393   // Scan the memory operations on the chain and find the first non-consecutive
11394   // store memory address.
11395   unsigned LastConsecutiveStore = 0;
11396   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11397   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11398 
11399     // Check that the addresses are consecutive starting from the second
11400     // element in the list of stores.
11401     if (i > 0) {
11402       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11403       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11404         break;
11405     }
11406 
11407     // Check if this store interferes with any of the loads that we found.
11408     // If we find a load that alias with this store. Stop the sequence.
11409     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11410                     [&](LSBaseSDNode* Ldn) {
11411                       return isAlias(Ldn, StoreNodes[i].MemNode);
11412                     }))
11413       break;
11414 
11415     // Mark this node as useful.
11416     LastConsecutiveStore = i;
11417   }
11418 
11419   // The node with the lowest store address.
11420   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11421   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11422   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11423   LLVMContext &Context = *DAG.getContext();
11424   const DataLayout &DL = DAG.getDataLayout();
11425 
11426   // Store the constants into memory as one consecutive store.
11427   if (IsConstantSrc) {
11428     unsigned LastLegalType = 0;
11429     unsigned LastLegalVectorType = 0;
11430     bool NonZero = false;
11431     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11432       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11433       SDValue StoredVal = St->getValue();
11434 
11435       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11436         NonZero |= !C->isNullValue();
11437       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11438         NonZero |= !C->getConstantFPValue()->isNullValue();
11439       } else {
11440         // Non-constant.
11441         break;
11442       }
11443 
11444       // Find a legal type for the constant store.
11445       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11446       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11447       bool IsFast;
11448       if (TLI.isTypeLegal(StoreTy) &&
11449           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11450                                  FirstStoreAlign, &IsFast) && IsFast) {
11451         LastLegalType = i+1;
11452       // Or check whether a truncstore is legal.
11453       } else if (TLI.getTypeAction(Context, StoreTy) ==
11454                  TargetLowering::TypePromoteInteger) {
11455         EVT LegalizedStoredValueTy =
11456           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11457         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11458             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11459                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11460             IsFast) {
11461           LastLegalType = i + 1;
11462         }
11463       }
11464 
11465       // We only use vectors if the constant is known to be zero or the target
11466       // allows it and the function is not marked with the noimplicitfloat
11467       // attribute.
11468       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11469                                                         FirstStoreAS)) &&
11470           !NoVectors) {
11471         // Find a legal type for the vector store.
11472         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11473         if (TLI.isTypeLegal(Ty) &&
11474             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11475                                    FirstStoreAlign, &IsFast) && IsFast)
11476           LastLegalVectorType = i + 1;
11477       }
11478     }
11479 
11480     // Check if we found a legal integer type to store.
11481     if (LastLegalType == 0 && LastLegalVectorType == 0)
11482       return false;
11483 
11484     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11485     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11486 
11487     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11488                                            true, UseVector);
11489   }
11490 
11491   // When extracting multiple vector elements, try to store them
11492   // in one vector store rather than a sequence of scalar stores.
11493   if (IsExtractVecSrc) {
11494     unsigned NumStoresToMerge = 0;
11495     bool IsVec = MemVT.isVector();
11496     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11497       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11498       unsigned StoreValOpcode = St->getValue().getOpcode();
11499       // This restriction could be loosened.
11500       // Bail out if any stored values are not elements extracted from a vector.
11501       // It should be possible to handle mixed sources, but load sources need
11502       // more careful handling (see the block of code below that handles
11503       // consecutive loads).
11504       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11505           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11506         return false;
11507 
11508       // Find a legal type for the vector store.
11509       unsigned Elts = i + 1;
11510       if (IsVec) {
11511         // When merging vector stores, get the total number of elements.
11512         Elts *= MemVT.getVectorNumElements();
11513       }
11514       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11515       bool IsFast;
11516       if (TLI.isTypeLegal(Ty) &&
11517           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11518                                  FirstStoreAlign, &IsFast) && IsFast)
11519         NumStoresToMerge = i + 1;
11520     }
11521 
11522     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11523                                            false, true);
11524   }
11525 
11526   // Below we handle the case of multiple consecutive stores that
11527   // come from multiple consecutive loads. We merge them into a single
11528   // wide load and a single wide store.
11529 
11530   // Look for load nodes which are used by the stored values.
11531   SmallVector<MemOpLink, 8> LoadNodes;
11532 
11533   // Find acceptable loads. Loads need to have the same chain (token factor),
11534   // must not be zext, volatile, indexed, and they must be consecutive.
11535   BaseIndexOffset LdBasePtr;
11536   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11537     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11538     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11539     if (!Ld) break;
11540 
11541     // Loads must only have one use.
11542     if (!Ld->hasNUsesOfValue(1, 0))
11543       break;
11544 
11545     // The memory operands must not be volatile.
11546     if (Ld->isVolatile() || Ld->isIndexed())
11547       break;
11548 
11549     // We do not accept ext loads.
11550     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11551       break;
11552 
11553     // The stored memory type must be the same.
11554     if (Ld->getMemoryVT() != MemVT)
11555       break;
11556 
11557     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11558     // If this is not the first ptr that we check.
11559     if (LdBasePtr.Base.getNode()) {
11560       // The base ptr must be the same.
11561       if (!LdPtr.equalBaseIndex(LdBasePtr))
11562         break;
11563     } else {
11564       // Check that all other base pointers are the same as this one.
11565       LdBasePtr = LdPtr;
11566     }
11567 
11568     // We found a potential memory operand to merge.
11569     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11570   }
11571 
11572   if (LoadNodes.size() < 2)
11573     return false;
11574 
11575   // If we have load/store pair instructions and we only have two values,
11576   // don't bother.
11577   unsigned RequiredAlignment;
11578   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11579       St->getAlignment() >= RequiredAlignment)
11580     return false;
11581 
11582   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11583   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11584   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11585 
11586   // Scan the memory operations on the chain and find the first non-consecutive
11587   // load memory address. These variables hold the index in the store node
11588   // array.
11589   unsigned LastConsecutiveLoad = 0;
11590   // This variable refers to the size and not index in the array.
11591   unsigned LastLegalVectorType = 0;
11592   unsigned LastLegalIntegerType = 0;
11593   StartAddress = LoadNodes[0].OffsetFromBase;
11594   SDValue FirstChain = FirstLoad->getChain();
11595   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11596     // All loads must share the same chain.
11597     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11598       break;
11599 
11600     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11601     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11602       break;
11603     LastConsecutiveLoad = i;
11604     // Find a legal type for the vector store.
11605     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11606     bool IsFastSt, IsFastLd;
11607     if (TLI.isTypeLegal(StoreTy) &&
11608         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11609                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11610         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11611                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11612       LastLegalVectorType = i + 1;
11613     }
11614 
11615     // Find a legal type for the integer store.
11616     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11617     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11618     if (TLI.isTypeLegal(StoreTy) &&
11619         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11620                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11621         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11622                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11623       LastLegalIntegerType = i + 1;
11624     // Or check whether a truncstore and extload is legal.
11625     else if (TLI.getTypeAction(Context, StoreTy) ==
11626              TargetLowering::TypePromoteInteger) {
11627       EVT LegalizedStoredValueTy =
11628         TLI.getTypeToTransformTo(Context, StoreTy);
11629       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11630           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11631           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11632           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11633           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11634                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11635           IsFastSt &&
11636           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11637                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11638           IsFastLd)
11639         LastLegalIntegerType = i+1;
11640     }
11641   }
11642 
11643   // Only use vector types if the vector type is larger than the integer type.
11644   // If they are the same, use integers.
11645   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11646   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11647 
11648   // We add +1 here because the LastXXX variables refer to location while
11649   // the NumElem refers to array/index size.
11650   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11651   NumElem = std::min(LastLegalType, NumElem);
11652 
11653   if (NumElem < 2)
11654     return false;
11655 
11656   // Collect the chains from all merged stores.
11657   SmallVector<SDValue, 8> MergeStoreChains;
11658   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11659 
11660   // The latest Node in the DAG.
11661   unsigned LatestNodeUsed = 0;
11662   for (unsigned i=1; i<NumElem; ++i) {
11663     // Find a chain for the new wide-store operand. Notice that some
11664     // of the store nodes that we found may not be selected for inclusion
11665     // in the wide store. The chain we use needs to be the chain of the
11666     // latest store node which is *used* and replaced by the wide store.
11667     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11668       LatestNodeUsed = i;
11669 
11670     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11671   }
11672 
11673   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11674 
11675   // Find if it is better to use vectors or integers to load and store
11676   // to memory.
11677   EVT JointMemOpVT;
11678   if (UseVectorTy) {
11679     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11680   } else {
11681     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11682     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11683   }
11684 
11685   SDLoc LoadDL(LoadNodes[0].MemNode);
11686   SDLoc StoreDL(StoreNodes[0].MemNode);
11687 
11688   // The merged loads are required to have the same incoming chain, so
11689   // using the first's chain is acceptable.
11690   SDValue NewLoad = DAG.getLoad(
11691       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11692       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11693 
11694   SDValue NewStoreChain =
11695     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11696 
11697   SDValue NewStore = DAG.getStore(
11698     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11699       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11700 
11701   // Transfer chain users from old loads to the new load.
11702   for (unsigned i = 0; i < NumElem; ++i) {
11703     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11704     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11705                                   SDValue(NewLoad.getNode(), 1));
11706   }
11707 
11708   // Replace the last store with the new store.
11709   CombineTo(LatestOp, NewStore);
11710   // Erase all other stores.
11711   for (unsigned i = 0; i < NumElem ; ++i) {
11712     // Remove all Store nodes.
11713     if (StoreNodes[i].MemNode == LatestOp)
11714       continue;
11715     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11716     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11717     deleteAndRecombine(St);
11718   }
11719 
11720   return true;
11721 }
11722 
11723 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11724   SDLoc SL(ST);
11725   SDValue ReplStore;
11726 
11727   // Replace the chain to avoid dependency.
11728   if (ST->isTruncatingStore()) {
11729     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11730                                   ST->getBasePtr(), ST->getMemoryVT(),
11731                                   ST->getMemOperand());
11732   } else {
11733     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11734                              ST->getMemOperand());
11735   }
11736 
11737   // Create token to keep both nodes around.
11738   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11739                               MVT::Other, ST->getChain(), ReplStore);
11740 
11741   // Make sure the new and old chains are cleaned up.
11742   AddToWorklist(Token.getNode());
11743 
11744   // Don't add users to work list.
11745   return CombineTo(ST, Token, false);
11746 }
11747 
11748 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11749   SDValue Value = ST->getValue();
11750   if (Value.getOpcode() == ISD::TargetConstantFP)
11751     return SDValue();
11752 
11753   SDLoc DL(ST);
11754 
11755   SDValue Chain = ST->getChain();
11756   SDValue Ptr = ST->getBasePtr();
11757 
11758   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11759 
11760   // NOTE: If the original store is volatile, this transform must not increase
11761   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11762   // processor operation but an i64 (which is not legal) requires two.  So the
11763   // transform should not be done in this case.
11764 
11765   SDValue Tmp;
11766   switch (CFP->getSimpleValueType(0).SimpleTy) {
11767   default:
11768     llvm_unreachable("Unknown FP type");
11769   case MVT::f16:    // We don't do this for these yet.
11770   case MVT::f80:
11771   case MVT::f128:
11772   case MVT::ppcf128:
11773     return SDValue();
11774   case MVT::f32:
11775     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11776         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11777       ;
11778       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11779                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11780                             MVT::i32);
11781       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11782     }
11783 
11784     return SDValue();
11785   case MVT::f64:
11786     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11787          !ST->isVolatile()) ||
11788         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11789       ;
11790       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11791                             getZExtValue(), SDLoc(CFP), MVT::i64);
11792       return DAG.getStore(Chain, DL, Tmp,
11793                           Ptr, ST->getMemOperand());
11794     }
11795 
11796     if (!ST->isVolatile() &&
11797         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11798       // Many FP stores are not made apparent until after legalize, e.g. for
11799       // argument passing.  Since this is so common, custom legalize the
11800       // 64-bit integer store into two 32-bit stores.
11801       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11802       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11803       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11804       if (DAG.getDataLayout().isBigEndian())
11805         std::swap(Lo, Hi);
11806 
11807       unsigned Alignment = ST->getAlignment();
11808       bool isVolatile = ST->isVolatile();
11809       bool isNonTemporal = ST->isNonTemporal();
11810       AAMDNodes AAInfo = ST->getAAInfo();
11811 
11812       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11813                                  Ptr, ST->getPointerInfo(),
11814                                  isVolatile, isNonTemporal,
11815                                  ST->getAlignment(), AAInfo);
11816       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11817                         DAG.getConstant(4, DL, Ptr.getValueType()));
11818       Alignment = MinAlign(Alignment, 4U);
11819       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11820                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11821                                  isVolatile, isNonTemporal,
11822                                  Alignment, AAInfo);
11823       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11824                          St0, St1);
11825     }
11826 
11827     return SDValue();
11828   }
11829 }
11830 
11831 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11832   StoreSDNode *ST  = cast<StoreSDNode>(N);
11833   SDValue Chain = ST->getChain();
11834   SDValue Value = ST->getValue();
11835   SDValue Ptr   = ST->getBasePtr();
11836 
11837   // If this is a store of a bit convert, store the input value if the
11838   // resultant store does not need a higher alignment than the original.
11839   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11840       ST->isUnindexed()) {
11841     unsigned OrigAlign = ST->getAlignment();
11842     EVT SVT = Value.getOperand(0).getValueType();
11843     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11844         SVT.getTypeForEVT(*DAG.getContext()));
11845     if (Align <= OrigAlign &&
11846         ((!LegalOperations && !ST->isVolatile()) ||
11847          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11848       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11849                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11850                           ST->isNonTemporal(), OrigAlign,
11851                           ST->getAAInfo());
11852   }
11853 
11854   // Turn 'store undef, Ptr' -> nothing.
11855   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11856     return Chain;
11857 
11858   // Try to infer better alignment information than the store already has.
11859   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11860     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11861       if (Align > ST->getAlignment()) {
11862         SDValue NewStore =
11863                DAG.getTruncStore(Chain, SDLoc(N), Value,
11864                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11865                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11866                                  ST->getAAInfo());
11867         if (NewStore.getNode() != N)
11868           return CombineTo(ST, NewStore, true);
11869       }
11870     }
11871   }
11872 
11873   // Try transforming a pair floating point load / store ops to integer
11874   // load / store ops.
11875   if (SDValue NewST = TransformFPLoadStorePair(N))
11876     return NewST;
11877 
11878   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11879                                                   : DAG.getSubtarget().useAA();
11880 #ifndef NDEBUG
11881   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11882       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11883     UseAA = false;
11884 #endif
11885   if (UseAA && ST->isUnindexed()) {
11886     // FIXME: We should do this even without AA enabled. AA will just allow
11887     // FindBetterChain to work in more situations. The problem with this is that
11888     // any combine that expects memory operations to be on consecutive chains
11889     // first needs to be updated to look for users of the same chain.
11890 
11891     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11892     // adjacent stores.
11893     if (findBetterNeighborChains(ST)) {
11894       // replaceStoreChain uses CombineTo, which handled all of the worklist
11895       // manipulation. Return the original node to not do anything else.
11896       return SDValue(ST, 0);
11897     }
11898   }
11899 
11900   // Try transforming N to an indexed store.
11901   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11902     return SDValue(N, 0);
11903 
11904   // FIXME: is there such a thing as a truncating indexed store?
11905   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11906       Value.getValueType().isInteger()) {
11907     // See if we can simplify the input to this truncstore with knowledge that
11908     // only the low bits are being used.  For example:
11909     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11910     SDValue Shorter =
11911       GetDemandedBits(Value,
11912                       APInt::getLowBitsSet(
11913                         Value.getValueType().getScalarType().getSizeInBits(),
11914                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11915     AddToWorklist(Value.getNode());
11916     if (Shorter.getNode())
11917       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11918                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11919 
11920     // Otherwise, see if we can simplify the operation with
11921     // SimplifyDemandedBits, which only works if the value has a single use.
11922     if (SimplifyDemandedBits(Value,
11923                         APInt::getLowBitsSet(
11924                           Value.getValueType().getScalarType().getSizeInBits(),
11925                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11926       return SDValue(N, 0);
11927   }
11928 
11929   // If this is a load followed by a store to the same location, then the store
11930   // is dead/noop.
11931   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11932     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11933         ST->isUnindexed() && !ST->isVolatile() &&
11934         // There can't be any side effects between the load and store, such as
11935         // a call or store.
11936         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11937       // The store is dead, remove it.
11938       return Chain;
11939     }
11940   }
11941 
11942   // If this is a store followed by a store with the same value to the same
11943   // location, then the store is dead/noop.
11944   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11945     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11946         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11947         ST1->isUnindexed() && !ST1->isVolatile()) {
11948       // The store is dead, remove it.
11949       return Chain;
11950     }
11951   }
11952 
11953   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11954   // truncating store.  We can do this even if this is already a truncstore.
11955   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11956       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11957       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11958                             ST->getMemoryVT())) {
11959     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11960                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11961   }
11962 
11963   // Only perform this optimization before the types are legal, because we
11964   // don't want to perform this optimization on every DAGCombine invocation.
11965   if (!LegalTypes) {
11966     bool EverChanged = false;
11967 
11968     do {
11969       // There can be multiple store sequences on the same chain.
11970       // Keep trying to merge store sequences until we are unable to do so
11971       // or until we merge the last store on the chain.
11972       bool Changed = MergeConsecutiveStores(ST);
11973       EverChanged |= Changed;
11974       if (!Changed) break;
11975     } while (ST->getOpcode() != ISD::DELETED_NODE);
11976 
11977     if (EverChanged)
11978       return SDValue(N, 0);
11979   }
11980 
11981   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11982   //
11983   // Make sure to do this only after attempting to merge stores in order to
11984   //  avoid changing the types of some subset of stores due to visit order,
11985   //  preventing their merging.
11986   if (isa<ConstantFPSDNode>(Value)) {
11987     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11988       return NewSt;
11989   }
11990 
11991   return ReduceLoadOpStoreWidth(N);
11992 }
11993 
11994 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11995   SDValue InVec = N->getOperand(0);
11996   SDValue InVal = N->getOperand(1);
11997   SDValue EltNo = N->getOperand(2);
11998   SDLoc dl(N);
11999 
12000   // If the inserted element is an UNDEF, just use the input vector.
12001   if (InVal.getOpcode() == ISD::UNDEF)
12002     return InVec;
12003 
12004   EVT VT = InVec.getValueType();
12005 
12006   // If we can't generate a legal BUILD_VECTOR, exit
12007   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12008     return SDValue();
12009 
12010   // Check that we know which element is being inserted
12011   if (!isa<ConstantSDNode>(EltNo))
12012     return SDValue();
12013   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12014 
12015   // Canonicalize insert_vector_elt dag nodes.
12016   // Example:
12017   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12018   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12019   //
12020   // Do this only if the child insert_vector node has one use; also
12021   // do this only if indices are both constants and Idx1 < Idx0.
12022   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12023       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12024     unsigned OtherElt =
12025       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12026     if (Elt < OtherElt) {
12027       // Swap nodes.
12028       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12029                                   InVec.getOperand(0), InVal, EltNo);
12030       AddToWorklist(NewOp.getNode());
12031       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12032                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12033     }
12034   }
12035 
12036   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12037   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12038   // vector elements.
12039   SmallVector<SDValue, 8> Ops;
12040   // Do not combine these two vectors if the output vector will not replace
12041   // the input vector.
12042   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12043     Ops.append(InVec.getNode()->op_begin(),
12044                InVec.getNode()->op_end());
12045   } else if (InVec.getOpcode() == ISD::UNDEF) {
12046     unsigned NElts = VT.getVectorNumElements();
12047     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12048   } else {
12049     return SDValue();
12050   }
12051 
12052   // Insert the element
12053   if (Elt < Ops.size()) {
12054     // All the operands of BUILD_VECTOR must have the same type;
12055     // we enforce that here.
12056     EVT OpVT = Ops[0].getValueType();
12057     if (InVal.getValueType() != OpVT)
12058       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12059                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12060                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12061     Ops[Elt] = InVal;
12062   }
12063 
12064   // Return the new vector
12065   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
12066 }
12067 
12068 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12069     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12070   EVT ResultVT = EVE->getValueType(0);
12071   EVT VecEltVT = InVecVT.getVectorElementType();
12072   unsigned Align = OriginalLoad->getAlignment();
12073   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12074       VecEltVT.getTypeForEVT(*DAG.getContext()));
12075 
12076   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12077     return SDValue();
12078 
12079   Align = NewAlign;
12080 
12081   SDValue NewPtr = OriginalLoad->getBasePtr();
12082   SDValue Offset;
12083   EVT PtrType = NewPtr.getValueType();
12084   MachinePointerInfo MPI;
12085   SDLoc DL(EVE);
12086   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12087     int Elt = ConstEltNo->getZExtValue();
12088     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12089     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12090     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12091   } else {
12092     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12093     Offset = DAG.getNode(
12094         ISD::MUL, DL, PtrType, Offset,
12095         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12096     MPI = OriginalLoad->getPointerInfo();
12097   }
12098   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12099 
12100   // The replacement we need to do here is a little tricky: we need to
12101   // replace an extractelement of a load with a load.
12102   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12103   // Note that this replacement assumes that the extractvalue is the only
12104   // use of the load; that's okay because we don't want to perform this
12105   // transformation in other cases anyway.
12106   SDValue Load;
12107   SDValue Chain;
12108   if (ResultVT.bitsGT(VecEltVT)) {
12109     // If the result type of vextract is wider than the load, then issue an
12110     // extending load instead.
12111     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12112                                                   VecEltVT)
12113                                    ? ISD::ZEXTLOAD
12114                                    : ISD::EXTLOAD;
12115     Load = DAG.getExtLoad(
12116         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12117         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12118         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12119     Chain = Load.getValue(1);
12120   } else {
12121     Load = DAG.getLoad(
12122         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12123         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12124         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12125     Chain = Load.getValue(1);
12126     if (ResultVT.bitsLT(VecEltVT))
12127       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12128     else
12129       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12130   }
12131   WorklistRemover DeadNodes(*this);
12132   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12133   SDValue To[] = { Load, Chain };
12134   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12135   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12136   // worklist explicitly as well.
12137   AddToWorklist(Load.getNode());
12138   AddUsersToWorklist(Load.getNode()); // Add users too
12139   // Make sure to revisit this node to clean it up; it will usually be dead.
12140   AddToWorklist(EVE);
12141   ++OpsNarrowed;
12142   return SDValue(EVE, 0);
12143 }
12144 
12145 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12146   // (vextract (scalar_to_vector val, 0) -> val
12147   SDValue InVec = N->getOperand(0);
12148   EVT VT = InVec.getValueType();
12149   EVT NVT = N->getValueType(0);
12150 
12151   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12152     // Check if the result type doesn't match the inserted element type. A
12153     // SCALAR_TO_VECTOR may truncate the inserted element and the
12154     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12155     SDValue InOp = InVec.getOperand(0);
12156     if (InOp.getValueType() != NVT) {
12157       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12158       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12159     }
12160     return InOp;
12161   }
12162 
12163   SDValue EltNo = N->getOperand(1);
12164   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12165 
12166   // extract_vector_elt (build_vector x, y), 1 -> y
12167   if (ConstEltNo &&
12168       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12169       TLI.isTypeLegal(VT) &&
12170       (InVec.hasOneUse() ||
12171        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12172     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12173     EVT InEltVT = Elt.getValueType();
12174 
12175     // Sometimes build_vector's scalar input types do not match result type.
12176     if (NVT == InEltVT)
12177       return Elt;
12178 
12179     // TODO: It may be useful to truncate if free if the build_vector implicitly
12180     // converts.
12181   }
12182 
12183   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12184   // We only perform this optimization before the op legalization phase because
12185   // we may introduce new vector instructions which are not backed by TD
12186   // patterns. For example on AVX, extracting elements from a wide vector
12187   // without using extract_subvector. However, if we can find an underlying
12188   // scalar value, then we can always use that.
12189   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12190     int NumElem = VT.getVectorNumElements();
12191     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12192     // Find the new index to extract from.
12193     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12194 
12195     // Extracting an undef index is undef.
12196     if (OrigElt == -1)
12197       return DAG.getUNDEF(NVT);
12198 
12199     // Select the right vector half to extract from.
12200     SDValue SVInVec;
12201     if (OrigElt < NumElem) {
12202       SVInVec = InVec->getOperand(0);
12203     } else {
12204       SVInVec = InVec->getOperand(1);
12205       OrigElt -= NumElem;
12206     }
12207 
12208     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12209       SDValue InOp = SVInVec.getOperand(OrigElt);
12210       if (InOp.getValueType() != NVT) {
12211         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12212         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12213       }
12214 
12215       return InOp;
12216     }
12217 
12218     // FIXME: We should handle recursing on other vector shuffles and
12219     // scalar_to_vector here as well.
12220 
12221     if (!LegalOperations) {
12222       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12223       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12224                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12225     }
12226   }
12227 
12228   bool BCNumEltsChanged = false;
12229   EVT ExtVT = VT.getVectorElementType();
12230   EVT LVT = ExtVT;
12231 
12232   // If the result of load has to be truncated, then it's not necessarily
12233   // profitable.
12234   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12235     return SDValue();
12236 
12237   if (InVec.getOpcode() == ISD::BITCAST) {
12238     // Don't duplicate a load with other uses.
12239     if (!InVec.hasOneUse())
12240       return SDValue();
12241 
12242     EVT BCVT = InVec.getOperand(0).getValueType();
12243     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12244       return SDValue();
12245     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12246       BCNumEltsChanged = true;
12247     InVec = InVec.getOperand(0);
12248     ExtVT = BCVT.getVectorElementType();
12249   }
12250 
12251   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12252   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12253       ISD::isNormalLoad(InVec.getNode()) &&
12254       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12255     SDValue Index = N->getOperand(1);
12256     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12257       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12258                                                            OrigLoad);
12259   }
12260 
12261   // Perform only after legalization to ensure build_vector / vector_shuffle
12262   // optimizations have already been done.
12263   if (!LegalOperations) return SDValue();
12264 
12265   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12266   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12267   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12268 
12269   if (ConstEltNo) {
12270     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12271 
12272     LoadSDNode *LN0 = nullptr;
12273     const ShuffleVectorSDNode *SVN = nullptr;
12274     if (ISD::isNormalLoad(InVec.getNode())) {
12275       LN0 = cast<LoadSDNode>(InVec);
12276     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12277                InVec.getOperand(0).getValueType() == ExtVT &&
12278                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12279       // Don't duplicate a load with other uses.
12280       if (!InVec.hasOneUse())
12281         return SDValue();
12282 
12283       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12284     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12285       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12286       // =>
12287       // (load $addr+1*size)
12288 
12289       // Don't duplicate a load with other uses.
12290       if (!InVec.hasOneUse())
12291         return SDValue();
12292 
12293       // If the bit convert changed the number of elements, it is unsafe
12294       // to examine the mask.
12295       if (BCNumEltsChanged)
12296         return SDValue();
12297 
12298       // Select the input vector, guarding against out of range extract vector.
12299       unsigned NumElems = VT.getVectorNumElements();
12300       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12301       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12302 
12303       if (InVec.getOpcode() == ISD::BITCAST) {
12304         // Don't duplicate a load with other uses.
12305         if (!InVec.hasOneUse())
12306           return SDValue();
12307 
12308         InVec = InVec.getOperand(0);
12309       }
12310       if (ISD::isNormalLoad(InVec.getNode())) {
12311         LN0 = cast<LoadSDNode>(InVec);
12312         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12313         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12314       }
12315     }
12316 
12317     // Make sure we found a non-volatile load and the extractelement is
12318     // the only use.
12319     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12320       return SDValue();
12321 
12322     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12323     if (Elt == -1)
12324       return DAG.getUNDEF(LVT);
12325 
12326     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12327   }
12328 
12329   return SDValue();
12330 }
12331 
12332 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12333 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12334   // We perform this optimization post type-legalization because
12335   // the type-legalizer often scalarizes integer-promoted vectors.
12336   // Performing this optimization before may create bit-casts which
12337   // will be type-legalized to complex code sequences.
12338   // We perform this optimization only before the operation legalizer because we
12339   // may introduce illegal operations.
12340   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12341     return SDValue();
12342 
12343   unsigned NumInScalars = N->getNumOperands();
12344   SDLoc dl(N);
12345   EVT VT = N->getValueType(0);
12346 
12347   // Check to see if this is a BUILD_VECTOR of a bunch of values
12348   // which come from any_extend or zero_extend nodes. If so, we can create
12349   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12350   // optimizations. We do not handle sign-extend because we can't fill the sign
12351   // using shuffles.
12352   EVT SourceType = MVT::Other;
12353   bool AllAnyExt = true;
12354 
12355   for (unsigned i = 0; i != NumInScalars; ++i) {
12356     SDValue In = N->getOperand(i);
12357     // Ignore undef inputs.
12358     if (In.getOpcode() == ISD::UNDEF) continue;
12359 
12360     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12361     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12362 
12363     // Abort if the element is not an extension.
12364     if (!ZeroExt && !AnyExt) {
12365       SourceType = MVT::Other;
12366       break;
12367     }
12368 
12369     // The input is a ZeroExt or AnyExt. Check the original type.
12370     EVT InTy = In.getOperand(0).getValueType();
12371 
12372     // Check that all of the widened source types are the same.
12373     if (SourceType == MVT::Other)
12374       // First time.
12375       SourceType = InTy;
12376     else if (InTy != SourceType) {
12377       // Multiple income types. Abort.
12378       SourceType = MVT::Other;
12379       break;
12380     }
12381 
12382     // Check if all of the extends are ANY_EXTENDs.
12383     AllAnyExt &= AnyExt;
12384   }
12385 
12386   // In order to have valid types, all of the inputs must be extended from the
12387   // same source type and all of the inputs must be any or zero extend.
12388   // Scalar sizes must be a power of two.
12389   EVT OutScalarTy = VT.getScalarType();
12390   bool ValidTypes = SourceType != MVT::Other &&
12391                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12392                  isPowerOf2_32(SourceType.getSizeInBits());
12393 
12394   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12395   // turn into a single shuffle instruction.
12396   if (!ValidTypes)
12397     return SDValue();
12398 
12399   bool isLE = DAG.getDataLayout().isLittleEndian();
12400   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12401   assert(ElemRatio > 1 && "Invalid element size ratio");
12402   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12403                                DAG.getConstant(0, SDLoc(N), SourceType);
12404 
12405   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12406   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12407 
12408   // Populate the new build_vector
12409   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12410     SDValue Cast = N->getOperand(i);
12411     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12412             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12413             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12414     SDValue In;
12415     if (Cast.getOpcode() == ISD::UNDEF)
12416       In = DAG.getUNDEF(SourceType);
12417     else
12418       In = Cast->getOperand(0);
12419     unsigned Index = isLE ? (i * ElemRatio) :
12420                             (i * ElemRatio + (ElemRatio - 1));
12421 
12422     assert(Index < Ops.size() && "Invalid index");
12423     Ops[Index] = In;
12424   }
12425 
12426   // The type of the new BUILD_VECTOR node.
12427   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12428   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12429          "Invalid vector size");
12430   // Check if the new vector type is legal.
12431   if (!isTypeLegal(VecVT)) return SDValue();
12432 
12433   // Make the new BUILD_VECTOR.
12434   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12435 
12436   // The new BUILD_VECTOR node has the potential to be further optimized.
12437   AddToWorklist(BV.getNode());
12438   // Bitcast to the desired type.
12439   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12440 }
12441 
12442 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12443   EVT VT = N->getValueType(0);
12444 
12445   unsigned NumInScalars = N->getNumOperands();
12446   SDLoc dl(N);
12447 
12448   EVT SrcVT = MVT::Other;
12449   unsigned Opcode = ISD::DELETED_NODE;
12450   unsigned NumDefs = 0;
12451 
12452   for (unsigned i = 0; i != NumInScalars; ++i) {
12453     SDValue In = N->getOperand(i);
12454     unsigned Opc = In.getOpcode();
12455 
12456     if (Opc == ISD::UNDEF)
12457       continue;
12458 
12459     // If all scalar values are floats and converted from integers.
12460     if (Opcode == ISD::DELETED_NODE &&
12461         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12462       Opcode = Opc;
12463     }
12464 
12465     if (Opc != Opcode)
12466       return SDValue();
12467 
12468     EVT InVT = In.getOperand(0).getValueType();
12469 
12470     // If all scalar values are typed differently, bail out. It's chosen to
12471     // simplify BUILD_VECTOR of integer types.
12472     if (SrcVT == MVT::Other)
12473       SrcVT = InVT;
12474     if (SrcVT != InVT)
12475       return SDValue();
12476     NumDefs++;
12477   }
12478 
12479   // If the vector has just one element defined, it's not worth to fold it into
12480   // a vectorized one.
12481   if (NumDefs < 2)
12482     return SDValue();
12483 
12484   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12485          && "Should only handle conversion from integer to float.");
12486   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12487 
12488   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12489 
12490   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12491     return SDValue();
12492 
12493   // Just because the floating-point vector type is legal does not necessarily
12494   // mean that the corresponding integer vector type is.
12495   if (!isTypeLegal(NVT))
12496     return SDValue();
12497 
12498   SmallVector<SDValue, 8> Opnds;
12499   for (unsigned i = 0; i != NumInScalars; ++i) {
12500     SDValue In = N->getOperand(i);
12501 
12502     if (In.getOpcode() == ISD::UNDEF)
12503       Opnds.push_back(DAG.getUNDEF(SrcVT));
12504     else
12505       Opnds.push_back(In.getOperand(0));
12506   }
12507   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12508   AddToWorklist(BV.getNode());
12509 
12510   return DAG.getNode(Opcode, dl, VT, BV);
12511 }
12512 
12513 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12514   unsigned NumInScalars = N->getNumOperands();
12515   SDLoc dl(N);
12516   EVT VT = N->getValueType(0);
12517 
12518   // A vector built entirely of undefs is undef.
12519   if (ISD::allOperandsUndef(N))
12520     return DAG.getUNDEF(VT);
12521 
12522   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12523     return V;
12524 
12525   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12526     return V;
12527 
12528   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12529   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12530   // at most two distinct vectors, turn this into a shuffle node.
12531 
12532   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12533   if (!isTypeLegal(VT))
12534     return SDValue();
12535 
12536   // May only combine to shuffle after legalize if shuffle is legal.
12537   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12538     return SDValue();
12539 
12540   SDValue VecIn1, VecIn2;
12541   bool UsesZeroVector = false;
12542   for (unsigned i = 0; i != NumInScalars; ++i) {
12543     SDValue Op = N->getOperand(i);
12544     // Ignore undef inputs.
12545     if (Op.getOpcode() == ISD::UNDEF) continue;
12546 
12547     // See if we can combine this build_vector into a blend with a zero vector.
12548     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12549       UsesZeroVector = true;
12550       continue;
12551     }
12552 
12553     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12554     // constant index, bail out.
12555     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12556         !isa<ConstantSDNode>(Op.getOperand(1))) {
12557       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12558       break;
12559     }
12560 
12561     // We allow up to two distinct input vectors.
12562     SDValue ExtractedFromVec = Op.getOperand(0);
12563     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12564       continue;
12565 
12566     if (!VecIn1.getNode()) {
12567       VecIn1 = ExtractedFromVec;
12568     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12569       VecIn2 = ExtractedFromVec;
12570     } else {
12571       // Too many inputs.
12572       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12573       break;
12574     }
12575   }
12576 
12577   // If everything is good, we can make a shuffle operation.
12578   if (VecIn1.getNode()) {
12579     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12580     SmallVector<int, 8> Mask;
12581     for (unsigned i = 0; i != NumInScalars; ++i) {
12582       unsigned Opcode = N->getOperand(i).getOpcode();
12583       if (Opcode == ISD::UNDEF) {
12584         Mask.push_back(-1);
12585         continue;
12586       }
12587 
12588       // Operands can also be zero.
12589       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12590         assert(UsesZeroVector &&
12591                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12592                "Unexpected node found!");
12593         Mask.push_back(NumInScalars+i);
12594         continue;
12595       }
12596 
12597       // If extracting from the first vector, just use the index directly.
12598       SDValue Extract = N->getOperand(i);
12599       SDValue ExtVal = Extract.getOperand(1);
12600       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12601       if (Extract.getOperand(0) == VecIn1) {
12602         Mask.push_back(ExtIndex);
12603         continue;
12604       }
12605 
12606       // Otherwise, use InIdx + InputVecSize
12607       Mask.push_back(InNumElements + ExtIndex);
12608     }
12609 
12610     // Avoid introducing illegal shuffles with zero.
12611     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12612       return SDValue();
12613 
12614     // We can't generate a shuffle node with mismatched input and output types.
12615     // Attempt to transform a single input vector to the correct type.
12616     if ((VT != VecIn1.getValueType())) {
12617       // If the input vector type has a different base type to the output
12618       // vector type, bail out.
12619       EVT VTElemType = VT.getVectorElementType();
12620       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12621           (VecIn2.getNode() &&
12622            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12623         return SDValue();
12624 
12625       // If the input vector is too small, widen it.
12626       // We only support widening of vectors which are half the size of the
12627       // output registers. For example XMM->YMM widening on X86 with AVX.
12628       EVT VecInT = VecIn1.getValueType();
12629       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12630         // If we only have one small input, widen it by adding undef values.
12631         if (!VecIn2.getNode())
12632           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12633                                DAG.getUNDEF(VecIn1.getValueType()));
12634         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12635           // If we have two small inputs of the same type, try to concat them.
12636           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12637           VecIn2 = SDValue(nullptr, 0);
12638         } else
12639           return SDValue();
12640       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12641         // If the input vector is too large, try to split it.
12642         // We don't support having two input vectors that are too large.
12643         // If the zero vector was used, we can not split the vector,
12644         // since we'd need 3 inputs.
12645         if (UsesZeroVector || VecIn2.getNode())
12646           return SDValue();
12647 
12648         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12649           return SDValue();
12650 
12651         // Try to replace VecIn1 with two extract_subvectors
12652         // No need to update the masks, they should still be correct.
12653         VecIn2 = DAG.getNode(
12654             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12655             DAG.getConstant(VT.getVectorNumElements(), dl,
12656                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12657         VecIn1 = DAG.getNode(
12658             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12659             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12660       } else
12661         return SDValue();
12662     }
12663 
12664     if (UsesZeroVector)
12665       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12666                                 DAG.getConstantFP(0.0, dl, VT);
12667     else
12668       // If VecIn2 is unused then change it to undef.
12669       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12670 
12671     // Check that we were able to transform all incoming values to the same
12672     // type.
12673     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12674         VecIn1.getValueType() != VT)
12675           return SDValue();
12676 
12677     // Return the new VECTOR_SHUFFLE node.
12678     SDValue Ops[2];
12679     Ops[0] = VecIn1;
12680     Ops[1] = VecIn2;
12681     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12682   }
12683 
12684   return SDValue();
12685 }
12686 
12687 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12689   EVT OpVT = N->getOperand(0).getValueType();
12690 
12691   // If the operands are legal vectors, leave them alone.
12692   if (TLI.isTypeLegal(OpVT))
12693     return SDValue();
12694 
12695   SDLoc DL(N);
12696   EVT VT = N->getValueType(0);
12697   SmallVector<SDValue, 8> Ops;
12698 
12699   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12700   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12701 
12702   // Keep track of what we encounter.
12703   bool AnyInteger = false;
12704   bool AnyFP = false;
12705   for (const SDValue &Op : N->ops()) {
12706     if (ISD::BITCAST == Op.getOpcode() &&
12707         !Op.getOperand(0).getValueType().isVector())
12708       Ops.push_back(Op.getOperand(0));
12709     else if (ISD::UNDEF == Op.getOpcode())
12710       Ops.push_back(ScalarUndef);
12711     else
12712       return SDValue();
12713 
12714     // Note whether we encounter an integer or floating point scalar.
12715     // If it's neither, bail out, it could be something weird like x86mmx.
12716     EVT LastOpVT = Ops.back().getValueType();
12717     if (LastOpVT.isFloatingPoint())
12718       AnyFP = true;
12719     else if (LastOpVT.isInteger())
12720       AnyInteger = true;
12721     else
12722       return SDValue();
12723   }
12724 
12725   // If any of the operands is a floating point scalar bitcast to a vector,
12726   // use floating point types throughout, and bitcast everything.
12727   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12728   if (AnyFP) {
12729     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12730     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12731     if (AnyInteger) {
12732       for (SDValue &Op : Ops) {
12733         if (Op.getValueType() == SVT)
12734           continue;
12735         if (Op.getOpcode() == ISD::UNDEF)
12736           Op = ScalarUndef;
12737         else
12738           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12739       }
12740     }
12741   }
12742 
12743   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12744                                VT.getSizeInBits() / SVT.getSizeInBits());
12745   return DAG.getNode(ISD::BITCAST, DL, VT,
12746                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12747 }
12748 
12749 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12750 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12751 // most two distinct vectors the same size as the result, attempt to turn this
12752 // into a legal shuffle.
12753 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12754   EVT VT = N->getValueType(0);
12755   EVT OpVT = N->getOperand(0).getValueType();
12756   int NumElts = VT.getVectorNumElements();
12757   int NumOpElts = OpVT.getVectorNumElements();
12758 
12759   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12760   SmallVector<int, 8> Mask;
12761 
12762   for (SDValue Op : N->ops()) {
12763     // Peek through any bitcast.
12764     while (Op.getOpcode() == ISD::BITCAST)
12765       Op = Op.getOperand(0);
12766 
12767     // UNDEF nodes convert to UNDEF shuffle mask values.
12768     if (Op.getOpcode() == ISD::UNDEF) {
12769       Mask.append((unsigned)NumOpElts, -1);
12770       continue;
12771     }
12772 
12773     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12774       return SDValue();
12775 
12776     // What vector are we extracting the subvector from and at what index?
12777     SDValue ExtVec = Op.getOperand(0);
12778 
12779     // We want the EVT of the original extraction to correctly scale the
12780     // extraction index.
12781     EVT ExtVT = ExtVec.getValueType();
12782 
12783     // Peek through any bitcast.
12784     while (ExtVec.getOpcode() == ISD::BITCAST)
12785       ExtVec = ExtVec.getOperand(0);
12786 
12787     // UNDEF nodes convert to UNDEF shuffle mask values.
12788     if (ExtVec.getOpcode() == ISD::UNDEF) {
12789       Mask.append((unsigned)NumOpElts, -1);
12790       continue;
12791     }
12792 
12793     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12794       return SDValue();
12795     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12796 
12797     // Ensure that we are extracting a subvector from a vector the same
12798     // size as the result.
12799     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12800       return SDValue();
12801 
12802     // Scale the subvector index to account for any bitcast.
12803     int NumExtElts = ExtVT.getVectorNumElements();
12804     if (0 == (NumExtElts % NumElts))
12805       ExtIdx /= (NumExtElts / NumElts);
12806     else if (0 == (NumElts % NumExtElts))
12807       ExtIdx *= (NumElts / NumExtElts);
12808     else
12809       return SDValue();
12810 
12811     // At most we can reference 2 inputs in the final shuffle.
12812     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12813       SV0 = ExtVec;
12814       for (int i = 0; i != NumOpElts; ++i)
12815         Mask.push_back(i + ExtIdx);
12816     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12817       SV1 = ExtVec;
12818       for (int i = 0; i != NumOpElts; ++i)
12819         Mask.push_back(i + ExtIdx + NumElts);
12820     } else {
12821       return SDValue();
12822     }
12823   }
12824 
12825   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12826     return SDValue();
12827 
12828   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12829                               DAG.getBitcast(VT, SV1), Mask);
12830 }
12831 
12832 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12833   // If we only have one input vector, we don't need to do any concatenation.
12834   if (N->getNumOperands() == 1)
12835     return N->getOperand(0);
12836 
12837   // Check if all of the operands are undefs.
12838   EVT VT = N->getValueType(0);
12839   if (ISD::allOperandsUndef(N))
12840     return DAG.getUNDEF(VT);
12841 
12842   // Optimize concat_vectors where all but the first of the vectors are undef.
12843   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12844         return Op.getOpcode() == ISD::UNDEF;
12845       })) {
12846     SDValue In = N->getOperand(0);
12847     assert(In.getValueType().isVector() && "Must concat vectors");
12848 
12849     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12850     if (In->getOpcode() == ISD::BITCAST &&
12851         !In->getOperand(0)->getValueType(0).isVector()) {
12852       SDValue Scalar = In->getOperand(0);
12853 
12854       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12855       // look through the trunc so we can still do the transform:
12856       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12857       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12858           !TLI.isTypeLegal(Scalar.getValueType()) &&
12859           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12860         Scalar = Scalar->getOperand(0);
12861 
12862       EVT SclTy = Scalar->getValueType(0);
12863 
12864       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12865         return SDValue();
12866 
12867       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12868                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12869       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12870         return SDValue();
12871 
12872       SDLoc dl = SDLoc(N);
12873       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12874       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12875     }
12876   }
12877 
12878   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12879   // We have already tested above for an UNDEF only concatenation.
12880   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12881   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12882   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12883     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12884   };
12885   bool AllBuildVectorsOrUndefs =
12886       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12887   if (AllBuildVectorsOrUndefs) {
12888     SmallVector<SDValue, 8> Opnds;
12889     EVT SVT = VT.getScalarType();
12890 
12891     EVT MinVT = SVT;
12892     if (!SVT.isFloatingPoint()) {
12893       // If BUILD_VECTOR are from built from integer, they may have different
12894       // operand types. Get the smallest type and truncate all operands to it.
12895       bool FoundMinVT = false;
12896       for (const SDValue &Op : N->ops())
12897         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12898           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12899           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12900           FoundMinVT = true;
12901         }
12902       assert(FoundMinVT && "Concat vector type mismatch");
12903     }
12904 
12905     for (const SDValue &Op : N->ops()) {
12906       EVT OpVT = Op.getValueType();
12907       unsigned NumElts = OpVT.getVectorNumElements();
12908 
12909       if (ISD::UNDEF == Op.getOpcode())
12910         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12911 
12912       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12913         if (SVT.isFloatingPoint()) {
12914           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12915           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12916         } else {
12917           for (unsigned i = 0; i != NumElts; ++i)
12918             Opnds.push_back(
12919                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12920         }
12921       }
12922     }
12923 
12924     assert(VT.getVectorNumElements() == Opnds.size() &&
12925            "Concat vector type mismatch");
12926     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12927   }
12928 
12929   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12930   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12931     return V;
12932 
12933   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12934   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12935     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12936       return V;
12937 
12938   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12939   // nodes often generate nop CONCAT_VECTOR nodes.
12940   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12941   // place the incoming vectors at the exact same location.
12942   SDValue SingleSource = SDValue();
12943   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12944 
12945   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12946     SDValue Op = N->getOperand(i);
12947 
12948     if (Op.getOpcode() == ISD::UNDEF)
12949       continue;
12950 
12951     // Check if this is the identity extract:
12952     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12953       return SDValue();
12954 
12955     // Find the single incoming vector for the extract_subvector.
12956     if (SingleSource.getNode()) {
12957       if (Op.getOperand(0) != SingleSource)
12958         return SDValue();
12959     } else {
12960       SingleSource = Op.getOperand(0);
12961 
12962       // Check the source type is the same as the type of the result.
12963       // If not, this concat may extend the vector, so we can not
12964       // optimize it away.
12965       if (SingleSource.getValueType() != N->getValueType(0))
12966         return SDValue();
12967     }
12968 
12969     unsigned IdentityIndex = i * PartNumElem;
12970     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12971     // The extract index must be constant.
12972     if (!CS)
12973       return SDValue();
12974 
12975     // Check that we are reading from the identity index.
12976     if (CS->getZExtValue() != IdentityIndex)
12977       return SDValue();
12978   }
12979 
12980   if (SingleSource.getNode())
12981     return SingleSource;
12982 
12983   return SDValue();
12984 }
12985 
12986 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12987   EVT NVT = N->getValueType(0);
12988   SDValue V = N->getOperand(0);
12989 
12990   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12991     // Combine:
12992     //    (extract_subvec (concat V1, V2, ...), i)
12993     // Into:
12994     //    Vi if possible
12995     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12996     // type.
12997     if (V->getOperand(0).getValueType() != NVT)
12998       return SDValue();
12999     unsigned Idx = N->getConstantOperandVal(1);
13000     unsigned NumElems = NVT.getVectorNumElements();
13001     assert((Idx % NumElems) == 0 &&
13002            "IDX in concat is not a multiple of the result vector length.");
13003     return V->getOperand(Idx / NumElems);
13004   }
13005 
13006   // Skip bitcasting
13007   if (V->getOpcode() == ISD::BITCAST)
13008     V = V.getOperand(0);
13009 
13010   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13011     SDLoc dl(N);
13012     // Handle only simple case where vector being inserted and vector
13013     // being extracted are of same type, and are half size of larger vectors.
13014     EVT BigVT = V->getOperand(0).getValueType();
13015     EVT SmallVT = V->getOperand(1).getValueType();
13016     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13017       return SDValue();
13018 
13019     // Only handle cases where both indexes are constants with the same type.
13020     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13021     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13022 
13023     if (InsIdx && ExtIdx &&
13024         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13025         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13026       // Combine:
13027       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13028       // Into:
13029       //    indices are equal or bit offsets are equal => V1
13030       //    otherwise => (extract_subvec V1, ExtIdx)
13031       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13032           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13033         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13034       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13035                          DAG.getNode(ISD::BITCAST, dl,
13036                                      N->getOperand(0).getValueType(),
13037                                      V->getOperand(0)), N->getOperand(1));
13038     }
13039   }
13040 
13041   return SDValue();
13042 }
13043 
13044 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13045                                                  SDValue V, SelectionDAG &DAG) {
13046   SDLoc DL(V);
13047   EVT VT = V.getValueType();
13048 
13049   switch (V.getOpcode()) {
13050   default:
13051     return V;
13052 
13053   case ISD::CONCAT_VECTORS: {
13054     EVT OpVT = V->getOperand(0).getValueType();
13055     int OpSize = OpVT.getVectorNumElements();
13056     SmallBitVector OpUsedElements(OpSize, false);
13057     bool FoundSimplification = false;
13058     SmallVector<SDValue, 4> NewOps;
13059     NewOps.reserve(V->getNumOperands());
13060     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13061       SDValue Op = V->getOperand(i);
13062       bool OpUsed = false;
13063       for (int j = 0; j < OpSize; ++j)
13064         if (UsedElements[i * OpSize + j]) {
13065           OpUsedElements[j] = true;
13066           OpUsed = true;
13067         }
13068       NewOps.push_back(
13069           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13070                  : DAG.getUNDEF(OpVT));
13071       FoundSimplification |= Op == NewOps.back();
13072       OpUsedElements.reset();
13073     }
13074     if (FoundSimplification)
13075       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13076     return V;
13077   }
13078 
13079   case ISD::INSERT_SUBVECTOR: {
13080     SDValue BaseV = V->getOperand(0);
13081     SDValue SubV = V->getOperand(1);
13082     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13083     if (!IdxN)
13084       return V;
13085 
13086     int SubSize = SubV.getValueType().getVectorNumElements();
13087     int Idx = IdxN->getZExtValue();
13088     bool SubVectorUsed = false;
13089     SmallBitVector SubUsedElements(SubSize, false);
13090     for (int i = 0; i < SubSize; ++i)
13091       if (UsedElements[i + Idx]) {
13092         SubVectorUsed = true;
13093         SubUsedElements[i] = true;
13094         UsedElements[i + Idx] = false;
13095       }
13096 
13097     // Now recurse on both the base and sub vectors.
13098     SDValue SimplifiedSubV =
13099         SubVectorUsed
13100             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13101             : DAG.getUNDEF(SubV.getValueType());
13102     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13103     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13104       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13105                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13106     return V;
13107   }
13108   }
13109 }
13110 
13111 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13112                                        SDValue N1, SelectionDAG &DAG) {
13113   EVT VT = SVN->getValueType(0);
13114   int NumElts = VT.getVectorNumElements();
13115   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13116   for (int M : SVN->getMask())
13117     if (M >= 0 && M < NumElts)
13118       N0UsedElements[M] = true;
13119     else if (M >= NumElts)
13120       N1UsedElements[M - NumElts] = true;
13121 
13122   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13123   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13124   if (S0 == N0 && S1 == N1)
13125     return SDValue();
13126 
13127   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13128 }
13129 
13130 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13131 // or turn a shuffle of a single concat into simpler shuffle then concat.
13132 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13133   EVT VT = N->getValueType(0);
13134   unsigned NumElts = VT.getVectorNumElements();
13135 
13136   SDValue N0 = N->getOperand(0);
13137   SDValue N1 = N->getOperand(1);
13138   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13139 
13140   SmallVector<SDValue, 4> Ops;
13141   EVT ConcatVT = N0.getOperand(0).getValueType();
13142   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13143   unsigned NumConcats = NumElts / NumElemsPerConcat;
13144 
13145   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13146   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13147   // half vector elements.
13148   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13149       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13150                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13151     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13152                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13153     N1 = DAG.getUNDEF(ConcatVT);
13154     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13155   }
13156 
13157   // Look at every vector that's inserted. We're looking for exact
13158   // subvector-sized copies from a concatenated vector
13159   for (unsigned I = 0; I != NumConcats; ++I) {
13160     // Make sure we're dealing with a copy.
13161     unsigned Begin = I * NumElemsPerConcat;
13162     bool AllUndef = true, NoUndef = true;
13163     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13164       if (SVN->getMaskElt(J) >= 0)
13165         AllUndef = false;
13166       else
13167         NoUndef = false;
13168     }
13169 
13170     if (NoUndef) {
13171       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13172         return SDValue();
13173 
13174       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13175         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13176           return SDValue();
13177 
13178       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13179       if (FirstElt < N0.getNumOperands())
13180         Ops.push_back(N0.getOperand(FirstElt));
13181       else
13182         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13183 
13184     } else if (AllUndef) {
13185       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13186     } else { // Mixed with general masks and undefs, can't do optimization.
13187       return SDValue();
13188     }
13189   }
13190 
13191   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13192 }
13193 
13194 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13195   EVT VT = N->getValueType(0);
13196   unsigned NumElts = VT.getVectorNumElements();
13197 
13198   SDValue N0 = N->getOperand(0);
13199   SDValue N1 = N->getOperand(1);
13200 
13201   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13202 
13203   // Canonicalize shuffle undef, undef -> undef
13204   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13205     return DAG.getUNDEF(VT);
13206 
13207   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13208 
13209   // Canonicalize shuffle v, v -> v, undef
13210   if (N0 == N1) {
13211     SmallVector<int, 8> NewMask;
13212     for (unsigned i = 0; i != NumElts; ++i) {
13213       int Idx = SVN->getMaskElt(i);
13214       if (Idx >= (int)NumElts) Idx -= NumElts;
13215       NewMask.push_back(Idx);
13216     }
13217     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13218                                 &NewMask[0]);
13219   }
13220 
13221   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13222   if (N0.getOpcode() == ISD::UNDEF) {
13223     SmallVector<int, 8> NewMask;
13224     for (unsigned i = 0; i != NumElts; ++i) {
13225       int Idx = SVN->getMaskElt(i);
13226       if (Idx >= 0) {
13227         if (Idx >= (int)NumElts)
13228           Idx -= NumElts;
13229         else
13230           Idx = -1; // remove reference to lhs
13231       }
13232       NewMask.push_back(Idx);
13233     }
13234     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13235                                 &NewMask[0]);
13236   }
13237 
13238   // Remove references to rhs if it is undef
13239   if (N1.getOpcode() == ISD::UNDEF) {
13240     bool Changed = false;
13241     SmallVector<int, 8> NewMask;
13242     for (unsigned i = 0; i != NumElts; ++i) {
13243       int Idx = SVN->getMaskElt(i);
13244       if (Idx >= (int)NumElts) {
13245         Idx = -1;
13246         Changed = true;
13247       }
13248       NewMask.push_back(Idx);
13249     }
13250     if (Changed)
13251       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13252   }
13253 
13254   // If it is a splat, check if the argument vector is another splat or a
13255   // build_vector.
13256   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13257     SDNode *V = N0.getNode();
13258 
13259     // If this is a bit convert that changes the element type of the vector but
13260     // not the number of vector elements, look through it.  Be careful not to
13261     // look though conversions that change things like v4f32 to v2f64.
13262     if (V->getOpcode() == ISD::BITCAST) {
13263       SDValue ConvInput = V->getOperand(0);
13264       if (ConvInput.getValueType().isVector() &&
13265           ConvInput.getValueType().getVectorNumElements() == NumElts)
13266         V = ConvInput.getNode();
13267     }
13268 
13269     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13270       assert(V->getNumOperands() == NumElts &&
13271              "BUILD_VECTOR has wrong number of operands");
13272       SDValue Base;
13273       bool AllSame = true;
13274       for (unsigned i = 0; i != NumElts; ++i) {
13275         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13276           Base = V->getOperand(i);
13277           break;
13278         }
13279       }
13280       // Splat of <u, u, u, u>, return <u, u, u, u>
13281       if (!Base.getNode())
13282         return N0;
13283       for (unsigned i = 0; i != NumElts; ++i) {
13284         if (V->getOperand(i) != Base) {
13285           AllSame = false;
13286           break;
13287         }
13288       }
13289       // Splat of <x, x, x, x>, return <x, x, x, x>
13290       if (AllSame)
13291         return N0;
13292 
13293       // Canonicalize any other splat as a build_vector.
13294       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13295       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13296       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13297                                   V->getValueType(0), Ops);
13298 
13299       // We may have jumped through bitcasts, so the type of the
13300       // BUILD_VECTOR may not match the type of the shuffle.
13301       if (V->getValueType(0) != VT)
13302         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13303       return NewBV;
13304     }
13305   }
13306 
13307   // There are various patterns used to build up a vector from smaller vectors,
13308   // subvectors, or elements. Scan chains of these and replace unused insertions
13309   // or components with undef.
13310   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13311     return S;
13312 
13313   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13314       Level < AfterLegalizeVectorOps &&
13315       (N1.getOpcode() == ISD::UNDEF ||
13316       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13317        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13318     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13319       return V;
13320   }
13321 
13322   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13323   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13324   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13325     SmallVector<SDValue, 8> Ops;
13326     for (int M : SVN->getMask()) {
13327       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13328       if (M >= 0) {
13329         int Idx = M % NumElts;
13330         SDValue &S = (M < (int)NumElts ? N0 : N1);
13331         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13332           Op = S.getOperand(Idx);
13333         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13334           if (Idx == 0)
13335             Op = S.getOperand(0);
13336         } else {
13337           // Operand can't be combined - bail out.
13338           break;
13339         }
13340       }
13341       Ops.push_back(Op);
13342     }
13343     if (Ops.size() == VT.getVectorNumElements()) {
13344       // BUILD_VECTOR requires all inputs to be of the same type, find the
13345       // maximum type and extend them all.
13346       EVT SVT = VT.getScalarType();
13347       if (SVT.isInteger())
13348         for (SDValue &Op : Ops)
13349           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13350       if (SVT != VT.getScalarType())
13351         for (SDValue &Op : Ops)
13352           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13353                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13354                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13355       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13356     }
13357   }
13358 
13359   // If this shuffle only has a single input that is a bitcasted shuffle,
13360   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13361   // back to their original types.
13362   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13363       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13364       TLI.isTypeLegal(VT)) {
13365 
13366     // Peek through the bitcast only if there is one user.
13367     SDValue BC0 = N0;
13368     while (BC0.getOpcode() == ISD::BITCAST) {
13369       if (!BC0.hasOneUse())
13370         break;
13371       BC0 = BC0.getOperand(0);
13372     }
13373 
13374     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13375       if (Scale == 1)
13376         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13377 
13378       SmallVector<int, 8> NewMask;
13379       for (int M : Mask)
13380         for (int s = 0; s != Scale; ++s)
13381           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13382       return NewMask;
13383     };
13384 
13385     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13386       EVT SVT = VT.getScalarType();
13387       EVT InnerVT = BC0->getValueType(0);
13388       EVT InnerSVT = InnerVT.getScalarType();
13389 
13390       // Determine which shuffle works with the smaller scalar type.
13391       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13392       EVT ScaleSVT = ScaleVT.getScalarType();
13393 
13394       if (TLI.isTypeLegal(ScaleVT) &&
13395           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13396           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13397 
13398         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13399         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13400 
13401         // Scale the shuffle masks to the smaller scalar type.
13402         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13403         SmallVector<int, 8> InnerMask =
13404             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13405         SmallVector<int, 8> OuterMask =
13406             ScaleShuffleMask(SVN->getMask(), OuterScale);
13407 
13408         // Merge the shuffle masks.
13409         SmallVector<int, 8> NewMask;
13410         for (int M : OuterMask)
13411           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13412 
13413         // Test for shuffle mask legality over both commutations.
13414         SDValue SV0 = BC0->getOperand(0);
13415         SDValue SV1 = BC0->getOperand(1);
13416         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13417         if (!LegalMask) {
13418           std::swap(SV0, SV1);
13419           ShuffleVectorSDNode::commuteMask(NewMask);
13420           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13421         }
13422 
13423         if (LegalMask) {
13424           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13425           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13426           return DAG.getNode(
13427               ISD::BITCAST, SDLoc(N), VT,
13428               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13429         }
13430       }
13431     }
13432   }
13433 
13434   // Canonicalize shuffles according to rules:
13435   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13436   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13437   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13438   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13439       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13440       TLI.isTypeLegal(VT)) {
13441     // The incoming shuffle must be of the same type as the result of the
13442     // current shuffle.
13443     assert(N1->getOperand(0).getValueType() == VT &&
13444            "Shuffle types don't match");
13445 
13446     SDValue SV0 = N1->getOperand(0);
13447     SDValue SV1 = N1->getOperand(1);
13448     bool HasSameOp0 = N0 == SV0;
13449     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13450     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13451       // Commute the operands of this shuffle so that next rule
13452       // will trigger.
13453       return DAG.getCommutedVectorShuffle(*SVN);
13454   }
13455 
13456   // Try to fold according to rules:
13457   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13458   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13459   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13460   // Don't try to fold shuffles with illegal type.
13461   // Only fold if this shuffle is the only user of the other shuffle.
13462   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13463       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13464     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13465 
13466     // The incoming shuffle must be of the same type as the result of the
13467     // current shuffle.
13468     assert(OtherSV->getOperand(0).getValueType() == VT &&
13469            "Shuffle types don't match");
13470 
13471     SDValue SV0, SV1;
13472     SmallVector<int, 4> Mask;
13473     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13474     // operand, and SV1 as the second operand.
13475     for (unsigned i = 0; i != NumElts; ++i) {
13476       int Idx = SVN->getMaskElt(i);
13477       if (Idx < 0) {
13478         // Propagate Undef.
13479         Mask.push_back(Idx);
13480         continue;
13481       }
13482 
13483       SDValue CurrentVec;
13484       if (Idx < (int)NumElts) {
13485         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13486         // shuffle mask to identify which vector is actually referenced.
13487         Idx = OtherSV->getMaskElt(Idx);
13488         if (Idx < 0) {
13489           // Propagate Undef.
13490           Mask.push_back(Idx);
13491           continue;
13492         }
13493 
13494         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13495                                            : OtherSV->getOperand(1);
13496       } else {
13497         // This shuffle index references an element within N1.
13498         CurrentVec = N1;
13499       }
13500 
13501       // Simple case where 'CurrentVec' is UNDEF.
13502       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13503         Mask.push_back(-1);
13504         continue;
13505       }
13506 
13507       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13508       // will be the first or second operand of the combined shuffle.
13509       Idx = Idx % NumElts;
13510       if (!SV0.getNode() || SV0 == CurrentVec) {
13511         // Ok. CurrentVec is the left hand side.
13512         // Update the mask accordingly.
13513         SV0 = CurrentVec;
13514         Mask.push_back(Idx);
13515         continue;
13516       }
13517 
13518       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13519       if (SV1.getNode() && SV1 != CurrentVec)
13520         return SDValue();
13521 
13522       // Ok. CurrentVec is the right hand side.
13523       // Update the mask accordingly.
13524       SV1 = CurrentVec;
13525       Mask.push_back(Idx + NumElts);
13526     }
13527 
13528     // Check if all indices in Mask are Undef. In case, propagate Undef.
13529     bool isUndefMask = true;
13530     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13531       isUndefMask &= Mask[i] < 0;
13532 
13533     if (isUndefMask)
13534       return DAG.getUNDEF(VT);
13535 
13536     if (!SV0.getNode())
13537       SV0 = DAG.getUNDEF(VT);
13538     if (!SV1.getNode())
13539       SV1 = DAG.getUNDEF(VT);
13540 
13541     // Avoid introducing shuffles with illegal mask.
13542     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13543       ShuffleVectorSDNode::commuteMask(Mask);
13544 
13545       if (!TLI.isShuffleMaskLegal(Mask, VT))
13546         return SDValue();
13547 
13548       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13549       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13550       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13551       std::swap(SV0, SV1);
13552     }
13553 
13554     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13555     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13556     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13557     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13558   }
13559 
13560   return SDValue();
13561 }
13562 
13563 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13564   SDValue InVal = N->getOperand(0);
13565   EVT VT = N->getValueType(0);
13566 
13567   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13568   // with a VECTOR_SHUFFLE.
13569   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13570     SDValue InVec = InVal->getOperand(0);
13571     SDValue EltNo = InVal->getOperand(1);
13572 
13573     // FIXME: We could support implicit truncation if the shuffle can be
13574     // scaled to a smaller vector scalar type.
13575     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13576     if (C0 && VT == InVec.getValueType() &&
13577         VT.getScalarType() == InVal.getValueType()) {
13578       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13579       int Elt = C0->getZExtValue();
13580       NewMask[0] = Elt;
13581 
13582       if (TLI.isShuffleMaskLegal(NewMask, VT))
13583         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13584                                     NewMask);
13585     }
13586   }
13587 
13588   return SDValue();
13589 }
13590 
13591 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13592   SDValue N0 = N->getOperand(0);
13593   SDValue N2 = N->getOperand(2);
13594 
13595   // If the input vector is a concatenation, and the insert replaces
13596   // one of the halves, we can optimize into a single concat_vectors.
13597   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13598       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13599     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13600     EVT VT = N->getValueType(0);
13601 
13602     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13603     // (concat_vectors Z, Y)
13604     if (InsIdx == 0)
13605       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13606                          N->getOperand(1), N0.getOperand(1));
13607 
13608     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13609     // (concat_vectors X, Z)
13610     if (InsIdx == VT.getVectorNumElements()/2)
13611       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13612                          N0.getOperand(0), N->getOperand(1));
13613   }
13614 
13615   return SDValue();
13616 }
13617 
13618 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13619   SDValue N0 = N->getOperand(0);
13620 
13621   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13622   if (N0->getOpcode() == ISD::FP16_TO_FP)
13623     return N0->getOperand(0);
13624 
13625   return SDValue();
13626 }
13627 
13628 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13629   SDValue N0 = N->getOperand(0);
13630 
13631   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13632   if (N0->getOpcode() == ISD::AND) {
13633     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13634     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13635       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13636                          N0.getOperand(0));
13637     }
13638   }
13639 
13640   return SDValue();
13641 }
13642 
13643 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13644 /// with the destination vector and a zero vector.
13645 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13646 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13647 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13648   EVT VT = N->getValueType(0);
13649   SDValue LHS = N->getOperand(0);
13650   SDValue RHS = N->getOperand(1);
13651   SDLoc dl(N);
13652 
13653   // Make sure we're not running after operation legalization where it
13654   // may have custom lowered the vector shuffles.
13655   if (LegalOperations)
13656     return SDValue();
13657 
13658   if (N->getOpcode() != ISD::AND)
13659     return SDValue();
13660 
13661   if (RHS.getOpcode() == ISD::BITCAST)
13662     RHS = RHS.getOperand(0);
13663 
13664   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13665     return SDValue();
13666 
13667   EVT RVT = RHS.getValueType();
13668   unsigned NumElts = RHS.getNumOperands();
13669 
13670   // Attempt to create a valid clear mask, splitting the mask into
13671   // sub elements and checking to see if each is
13672   // all zeros or all ones - suitable for shuffle masking.
13673   auto BuildClearMask = [&](int Split) {
13674     int NumSubElts = NumElts * Split;
13675     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13676 
13677     SmallVector<int, 8> Indices;
13678     for (int i = 0; i != NumSubElts; ++i) {
13679       int EltIdx = i / Split;
13680       int SubIdx = i % Split;
13681       SDValue Elt = RHS.getOperand(EltIdx);
13682       if (Elt.getOpcode() == ISD::UNDEF) {
13683         Indices.push_back(-1);
13684         continue;
13685       }
13686 
13687       APInt Bits;
13688       if (isa<ConstantSDNode>(Elt))
13689         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13690       else if (isa<ConstantFPSDNode>(Elt))
13691         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13692       else
13693         return SDValue();
13694 
13695       // Extract the sub element from the constant bit mask.
13696       if (DAG.getDataLayout().isBigEndian()) {
13697         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13698       } else {
13699         Bits = Bits.lshr(SubIdx * NumSubBits);
13700       }
13701 
13702       if (Split > 1)
13703         Bits = Bits.trunc(NumSubBits);
13704 
13705       if (Bits.isAllOnesValue())
13706         Indices.push_back(i);
13707       else if (Bits == 0)
13708         Indices.push_back(i + NumSubElts);
13709       else
13710         return SDValue();
13711     }
13712 
13713     // Let's see if the target supports this vector_shuffle.
13714     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13715     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13716     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13717       return SDValue();
13718 
13719     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13720     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13721                                                    DAG.getBitcast(ClearVT, LHS),
13722                                                    Zero, &Indices[0]));
13723   };
13724 
13725   // Determine maximum split level (byte level masking).
13726   int MaxSplit = 1;
13727   if (RVT.getScalarSizeInBits() % 8 == 0)
13728     MaxSplit = RVT.getScalarSizeInBits() / 8;
13729 
13730   for (int Split = 1; Split <= MaxSplit; ++Split)
13731     if (RVT.getScalarSizeInBits() % Split == 0)
13732       if (SDValue S = BuildClearMask(Split))
13733         return S;
13734 
13735   return SDValue();
13736 }
13737 
13738 /// Visit a binary vector operation, like ADD.
13739 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13740   assert(N->getValueType(0).isVector() &&
13741          "SimplifyVBinOp only works on vectors!");
13742 
13743   SDValue LHS = N->getOperand(0);
13744   SDValue RHS = N->getOperand(1);
13745   SDValue Ops[] = {LHS, RHS};
13746 
13747   // See if we can constant fold the vector operation.
13748   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13749           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13750     return Fold;
13751 
13752   // Try to convert a constant mask AND into a shuffle clear mask.
13753   if (SDValue Shuffle = XformToShuffleWithZero(N))
13754     return Shuffle;
13755 
13756   // Type legalization might introduce new shuffles in the DAG.
13757   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13758   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13759   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13760       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13761       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13762       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13763     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13764     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13765 
13766     if (SVN0->getMask().equals(SVN1->getMask())) {
13767       EVT VT = N->getValueType(0);
13768       SDValue UndefVector = LHS.getOperand(1);
13769       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13770                                      LHS.getOperand(0), RHS.getOperand(0),
13771                                      N->getFlags());
13772       AddUsersToWorklist(N);
13773       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13774                                   &SVN0->getMask()[0]);
13775     }
13776   }
13777 
13778   return SDValue();
13779 }
13780 
13781 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13782                                     SDValue N1, SDValue N2){
13783   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13784 
13785   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13786                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13787 
13788   // If we got a simplified select_cc node back from SimplifySelectCC, then
13789   // break it down into a new SETCC node, and a new SELECT node, and then return
13790   // the SELECT node, since we were called with a SELECT node.
13791   if (SCC.getNode()) {
13792     // Check to see if we got a select_cc back (to turn into setcc/select).
13793     // Otherwise, just return whatever node we got back, like fabs.
13794     if (SCC.getOpcode() == ISD::SELECT_CC) {
13795       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13796                                   N0.getValueType(),
13797                                   SCC.getOperand(0), SCC.getOperand(1),
13798                                   SCC.getOperand(4));
13799       AddToWorklist(SETCC.getNode());
13800       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13801                            SCC.getOperand(2), SCC.getOperand(3));
13802     }
13803 
13804     return SCC;
13805   }
13806   return SDValue();
13807 }
13808 
13809 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13810 /// being selected between, see if we can simplify the select.  Callers of this
13811 /// should assume that TheSelect is deleted if this returns true.  As such, they
13812 /// should return the appropriate thing (e.g. the node) back to the top-level of
13813 /// the DAG combiner loop to avoid it being looked at.
13814 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13815                                     SDValue RHS) {
13816 
13817   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
13818   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
13819   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13820     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13821       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13822       SDValue Sqrt = RHS;
13823       ISD::CondCode CC;
13824       SDValue CmpLHS;
13825       const ConstantFPSDNode *Zero = nullptr;
13826 
13827       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13828         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13829         CmpLHS = TheSelect->getOperand(0);
13830         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13831       } else {
13832         // SELECT or VSELECT
13833         SDValue Cmp = TheSelect->getOperand(0);
13834         if (Cmp.getOpcode() == ISD::SETCC) {
13835           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13836           CmpLHS = Cmp.getOperand(0);
13837           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
13838         }
13839       }
13840       if (Zero && Zero->isZero() &&
13841           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13842           CC == ISD::SETULT || CC == ISD::SETLT)) {
13843         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
13844         CombineTo(TheSelect, Sqrt);
13845         return true;
13846       }
13847     }
13848   }
13849   // Cannot simplify select with vector condition
13850   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13851 
13852   // If this is a select from two identical things, try to pull the operation
13853   // through the select.
13854   if (LHS.getOpcode() != RHS.getOpcode() ||
13855       !LHS.hasOneUse() || !RHS.hasOneUse())
13856     return false;
13857 
13858   // If this is a load and the token chain is identical, replace the select
13859   // of two loads with a load through a select of the address to load from.
13860   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13861   // constants have been dropped into the constant pool.
13862   if (LHS.getOpcode() == ISD::LOAD) {
13863     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13864     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13865 
13866     // Token chains must be identical.
13867     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13868         // Do not let this transformation reduce the number of volatile loads.
13869         LLD->isVolatile() || RLD->isVolatile() ||
13870         // FIXME: If either is a pre/post inc/dec load,
13871         // we'd need to split out the address adjustment.
13872         LLD->isIndexed() || RLD->isIndexed() ||
13873         // If this is an EXTLOAD, the VT's must match.
13874         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13875         // If this is an EXTLOAD, the kind of extension must match.
13876         (LLD->getExtensionType() != RLD->getExtensionType() &&
13877          // The only exception is if one of the extensions is anyext.
13878          LLD->getExtensionType() != ISD::EXTLOAD &&
13879          RLD->getExtensionType() != ISD::EXTLOAD) ||
13880         // FIXME: this discards src value information.  This is
13881         // over-conservative. It would be beneficial to be able to remember
13882         // both potential memory locations.  Since we are discarding
13883         // src value info, don't do the transformation if the memory
13884         // locations are not in the default address space.
13885         LLD->getPointerInfo().getAddrSpace() != 0 ||
13886         RLD->getPointerInfo().getAddrSpace() != 0 ||
13887         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13888                                       LLD->getBasePtr().getValueType()))
13889       return false;
13890 
13891     // Check that the select condition doesn't reach either load.  If so,
13892     // folding this will induce a cycle into the DAG.  If not, this is safe to
13893     // xform, so create a select of the addresses.
13894     SDValue Addr;
13895     if (TheSelect->getOpcode() == ISD::SELECT) {
13896       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13897       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13898           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13899         return false;
13900       // The loads must not depend on one another.
13901       if (LLD->isPredecessorOf(RLD) ||
13902           RLD->isPredecessorOf(LLD))
13903         return false;
13904       Addr = DAG.getSelect(SDLoc(TheSelect),
13905                            LLD->getBasePtr().getValueType(),
13906                            TheSelect->getOperand(0), LLD->getBasePtr(),
13907                            RLD->getBasePtr());
13908     } else {  // Otherwise SELECT_CC
13909       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13910       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13911 
13912       if ((LLD->hasAnyUseOfValue(1) &&
13913            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13914           (RLD->hasAnyUseOfValue(1) &&
13915            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13916         return false;
13917 
13918       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13919                          LLD->getBasePtr().getValueType(),
13920                          TheSelect->getOperand(0),
13921                          TheSelect->getOperand(1),
13922                          LLD->getBasePtr(), RLD->getBasePtr(),
13923                          TheSelect->getOperand(4));
13924     }
13925 
13926     SDValue Load;
13927     // It is safe to replace the two loads if they have different alignments,
13928     // but the new load must be the minimum (most restrictive) alignment of the
13929     // inputs.
13930     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13931     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13932     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13933       Load = DAG.getLoad(TheSelect->getValueType(0),
13934                          SDLoc(TheSelect),
13935                          // FIXME: Discards pointer and AA info.
13936                          LLD->getChain(), Addr, MachinePointerInfo(),
13937                          LLD->isVolatile(), LLD->isNonTemporal(),
13938                          isInvariant, Alignment);
13939     } else {
13940       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13941                             RLD->getExtensionType() : LLD->getExtensionType(),
13942                             SDLoc(TheSelect),
13943                             TheSelect->getValueType(0),
13944                             // FIXME: Discards pointer and AA info.
13945                             LLD->getChain(), Addr, MachinePointerInfo(),
13946                             LLD->getMemoryVT(), LLD->isVolatile(),
13947                             LLD->isNonTemporal(), isInvariant, Alignment);
13948     }
13949 
13950     // Users of the select now use the result of the load.
13951     CombineTo(TheSelect, Load);
13952 
13953     // Users of the old loads now use the new load's chain.  We know the
13954     // old-load value is dead now.
13955     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13956     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13957     return true;
13958   }
13959 
13960   return false;
13961 }
13962 
13963 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13964 /// where 'cond' is the comparison specified by CC.
13965 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13966                                       SDValue N2, SDValue N3,
13967                                       ISD::CondCode CC, bool NotExtCompare) {
13968   // (x ? y : y) -> y.
13969   if (N2 == N3) return N2;
13970 
13971   EVT VT = N2.getValueType();
13972   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13973   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13974 
13975   // Determine if the condition we're dealing with is constant
13976   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13977                               N0, N1, CC, DL, false);
13978   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13979 
13980   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13981     // fold select_cc true, x, y -> x
13982     // fold select_cc false, x, y -> y
13983     return !SCCC->isNullValue() ? N2 : N3;
13984   }
13985 
13986   // Check to see if we can simplify the select into an fabs node
13987   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13988     // Allow either -0.0 or 0.0
13989     if (CFP->isZero()) {
13990       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13991       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13992           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13993           N2 == N3.getOperand(0))
13994         return DAG.getNode(ISD::FABS, DL, VT, N0);
13995 
13996       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13997       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13998           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13999           N2.getOperand(0) == N3)
14000         return DAG.getNode(ISD::FABS, DL, VT, N3);
14001     }
14002   }
14003 
14004   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14005   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14006   // in it.  This is a win when the constant is not otherwise available because
14007   // it replaces two constant pool loads with one.  We only do this if the FP
14008   // type is known to be legal, because if it isn't, then we are before legalize
14009   // types an we want the other legalization to happen first (e.g. to avoid
14010   // messing with soft float) and if the ConstantFP is not legal, because if
14011   // it is legal, we may not need to store the FP constant in a constant pool.
14012   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14013     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14014       if (TLI.isTypeLegal(N2.getValueType()) &&
14015           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14016                TargetLowering::Legal &&
14017            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14018            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14019           // If both constants have multiple uses, then we won't need to do an
14020           // extra load, they are likely around in registers for other users.
14021           (TV->hasOneUse() || FV->hasOneUse())) {
14022         Constant *Elts[] = {
14023           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14024           const_cast<ConstantFP*>(TV->getConstantFPValue())
14025         };
14026         Type *FPTy = Elts[0]->getType();
14027         const DataLayout &TD = DAG.getDataLayout();
14028 
14029         // Create a ConstantArray of the two constants.
14030         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14031         SDValue CPIdx =
14032             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14033                                 TD.getPrefTypeAlignment(FPTy));
14034         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14035 
14036         // Get the offsets to the 0 and 1 element of the array so that we can
14037         // select between them.
14038         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14039         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14040         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14041 
14042         SDValue Cond = DAG.getSetCC(DL,
14043                                     getSetCCResultType(N0.getValueType()),
14044                                     N0, N1, CC);
14045         AddToWorklist(Cond.getNode());
14046         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14047                                           Cond, One, Zero);
14048         AddToWorklist(CstOffset.getNode());
14049         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14050                             CstOffset);
14051         AddToWorklist(CPIdx.getNode());
14052         return DAG.getLoad(
14053             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14054             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14055             false, false, false, Alignment);
14056       }
14057     }
14058 
14059   // Check to see if we can perform the "gzip trick", transforming
14060   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14061   if (isNullConstant(N3) && CC == ISD::SETLT &&
14062       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14063        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14064     EVT XType = N0.getValueType();
14065     EVT AType = N2.getValueType();
14066     if (XType.bitsGE(AType)) {
14067       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14068       // single-bit constant.
14069       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14070         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14071         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14072         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14073                                        getShiftAmountTy(N0.getValueType()));
14074         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14075                                     XType, N0, ShCt);
14076         AddToWorklist(Shift.getNode());
14077 
14078         if (XType.bitsGT(AType)) {
14079           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14080           AddToWorklist(Shift.getNode());
14081         }
14082 
14083         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14084       }
14085 
14086       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14087                                   XType, N0,
14088                                   DAG.getConstant(XType.getSizeInBits() - 1,
14089                                                   SDLoc(N0),
14090                                          getShiftAmountTy(N0.getValueType())));
14091       AddToWorklist(Shift.getNode());
14092 
14093       if (XType.bitsGT(AType)) {
14094         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14095         AddToWorklist(Shift.getNode());
14096       }
14097 
14098       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14099     }
14100   }
14101 
14102   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14103   // where y is has a single bit set.
14104   // A plaintext description would be, we can turn the SELECT_CC into an AND
14105   // when the condition can be materialized as an all-ones register.  Any
14106   // single bit-test can be materialized as an all-ones register with
14107   // shift-left and shift-right-arith.
14108   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14109       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14110     SDValue AndLHS = N0->getOperand(0);
14111     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14112     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14113       // Shift the tested bit over the sign bit.
14114       APInt AndMask = ConstAndRHS->getAPIntValue();
14115       SDValue ShlAmt =
14116         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14117                         getShiftAmountTy(AndLHS.getValueType()));
14118       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14119 
14120       // Now arithmetic right shift it all the way over, so the result is either
14121       // all-ones, or zero.
14122       SDValue ShrAmt =
14123         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14124                         getShiftAmountTy(Shl.getValueType()));
14125       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14126 
14127       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14128     }
14129   }
14130 
14131   // fold select C, 16, 0 -> shl C, 4
14132   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14133       TLI.getBooleanContents(N0.getValueType()) ==
14134           TargetLowering::ZeroOrOneBooleanContent) {
14135 
14136     // If the caller doesn't want us to simplify this into a zext of a compare,
14137     // don't do it.
14138     if (NotExtCompare && N2C->isOne())
14139       return SDValue();
14140 
14141     // Get a SetCC of the condition
14142     // NOTE: Don't create a SETCC if it's not legal on this target.
14143     if (!LegalOperations ||
14144         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14145       SDValue Temp, SCC;
14146       // cast from setcc result type to select result type
14147       if (LegalTypes) {
14148         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14149                             N0, N1, CC);
14150         if (N2.getValueType().bitsLT(SCC.getValueType()))
14151           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14152                                         N2.getValueType());
14153         else
14154           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14155                              N2.getValueType(), SCC);
14156       } else {
14157         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14158         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14159                            N2.getValueType(), SCC);
14160       }
14161 
14162       AddToWorklist(SCC.getNode());
14163       AddToWorklist(Temp.getNode());
14164 
14165       if (N2C->isOne())
14166         return Temp;
14167 
14168       // shl setcc result by log2 n2c
14169       return DAG.getNode(
14170           ISD::SHL, DL, N2.getValueType(), Temp,
14171           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14172                           getShiftAmountTy(Temp.getValueType())));
14173     }
14174   }
14175 
14176   // Check to see if this is an integer abs.
14177   // select_cc setg[te] X,  0,  X, -X ->
14178   // select_cc setgt    X, -1,  X, -X ->
14179   // select_cc setl[te] X,  0, -X,  X ->
14180   // select_cc setlt    X,  1, -X,  X ->
14181   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14182   if (N1C) {
14183     ConstantSDNode *SubC = nullptr;
14184     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14185          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14186         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14187       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14188     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14189               (N1C->isOne() && CC == ISD::SETLT)) &&
14190              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14191       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14192 
14193     EVT XType = N0.getValueType();
14194     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14195       SDLoc DL(N0);
14196       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14197                                   N0,
14198                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14199                                          getShiftAmountTy(N0.getValueType())));
14200       SDValue Add = DAG.getNode(ISD::ADD, DL,
14201                                 XType, N0, Shift);
14202       AddToWorklist(Shift.getNode());
14203       AddToWorklist(Add.getNode());
14204       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14205     }
14206   }
14207 
14208   return SDValue();
14209 }
14210 
14211 /// This is a stub for TargetLowering::SimplifySetCC.
14212 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14213                                    SDValue N1, ISD::CondCode Cond,
14214                                    SDLoc DL, bool foldBooleans) {
14215   TargetLowering::DAGCombinerInfo
14216     DagCombineInfo(DAG, Level, false, this);
14217   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14218 }
14219 
14220 /// Given an ISD::SDIV node expressing a divide by constant, return
14221 /// a DAG expression to select that will generate the same value by multiplying
14222 /// by a magic number.
14223 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14224 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14225   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14226   if (!C)
14227     return SDValue();
14228 
14229   // Avoid division by zero.
14230   if (C->isNullValue())
14231     return SDValue();
14232 
14233   std::vector<SDNode*> Built;
14234   SDValue S =
14235       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14236 
14237   for (SDNode *N : Built)
14238     AddToWorklist(N);
14239   return S;
14240 }
14241 
14242 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14243 /// DAG expression that will generate the same value by right shifting.
14244 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14245   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14246   if (!C)
14247     return SDValue();
14248 
14249   // Avoid division by zero.
14250   if (C->isNullValue())
14251     return SDValue();
14252 
14253   std::vector<SDNode *> Built;
14254   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14255 
14256   for (SDNode *N : Built)
14257     AddToWorklist(N);
14258   return S;
14259 }
14260 
14261 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14262 /// expression that will generate the same value by multiplying by a magic
14263 /// number.
14264 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14265 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14266   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14267   if (!C)
14268     return SDValue();
14269 
14270   // Avoid division by zero.
14271   if (C->isNullValue())
14272     return SDValue();
14273 
14274   std::vector<SDNode*> Built;
14275   SDValue S =
14276       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14277 
14278   for (SDNode *N : Built)
14279     AddToWorklist(N);
14280   return S;
14281 }
14282 
14283 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14284   if (Level >= AfterLegalizeDAG)
14285     return SDValue();
14286 
14287   // Expose the DAG combiner to the target combiner implementations.
14288   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14289 
14290   unsigned Iterations = 0;
14291   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14292     if (Iterations) {
14293       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14294       // For the reciprocal, we need to find the zero of the function:
14295       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14296       //     =>
14297       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14298       //     does not require additional intermediate precision]
14299       EVT VT = Op.getValueType();
14300       SDLoc DL(Op);
14301       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14302 
14303       AddToWorklist(Est.getNode());
14304 
14305       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14306       for (unsigned i = 0; i < Iterations; ++i) {
14307         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14308         AddToWorklist(NewEst.getNode());
14309 
14310         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14311         AddToWorklist(NewEst.getNode());
14312 
14313         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14314         AddToWorklist(NewEst.getNode());
14315 
14316         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14317         AddToWorklist(Est.getNode());
14318       }
14319     }
14320     return Est;
14321   }
14322 
14323   return SDValue();
14324 }
14325 
14326 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14327 /// For the reciprocal sqrt, we need to find the zero of the function:
14328 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14329 ///     =>
14330 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14331 /// As a result, we precompute A/2 prior to the iteration loop.
14332 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14333                                           unsigned Iterations,
14334                                           SDNodeFlags *Flags) {
14335   EVT VT = Arg.getValueType();
14336   SDLoc DL(Arg);
14337   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14338 
14339   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14340   // this entire sequence requires only one FP constant.
14341   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14342   AddToWorklist(HalfArg.getNode());
14343 
14344   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14345   AddToWorklist(HalfArg.getNode());
14346 
14347   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14348   for (unsigned i = 0; i < Iterations; ++i) {
14349     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14350     AddToWorklist(NewEst.getNode());
14351 
14352     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14353     AddToWorklist(NewEst.getNode());
14354 
14355     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14356     AddToWorklist(NewEst.getNode());
14357 
14358     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14359     AddToWorklist(Est.getNode());
14360   }
14361   return Est;
14362 }
14363 
14364 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14365 /// For the reciprocal sqrt, we need to find the zero of the function:
14366 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14367 ///     =>
14368 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14369 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14370                                           unsigned Iterations,
14371                                           SDNodeFlags *Flags) {
14372   EVT VT = Arg.getValueType();
14373   SDLoc DL(Arg);
14374   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14375   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14376 
14377   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14378   for (unsigned i = 0; i < Iterations; ++i) {
14379     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14380     AddToWorklist(HalfEst.getNode());
14381 
14382     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14383     AddToWorklist(Est.getNode());
14384 
14385     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14386     AddToWorklist(Est.getNode());
14387 
14388     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14389     AddToWorklist(Est.getNode());
14390 
14391     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14392     AddToWorklist(Est.getNode());
14393   }
14394   return Est;
14395 }
14396 
14397 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14398   if (Level >= AfterLegalizeDAG)
14399     return SDValue();
14400 
14401   // Expose the DAG combiner to the target combiner implementations.
14402   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14403   unsigned Iterations = 0;
14404   bool UseOneConstNR = false;
14405   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14406     AddToWorklist(Est.getNode());
14407     if (Iterations) {
14408       Est = UseOneConstNR ?
14409         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14410         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14411     }
14412     return Est;
14413   }
14414 
14415   return SDValue();
14416 }
14417 
14418 /// Return true if base is a frame index, which is known not to alias with
14419 /// anything but itself.  Provides base object and offset as results.
14420 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14421                            const GlobalValue *&GV, const void *&CV) {
14422   // Assume it is a primitive operation.
14423   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14424 
14425   // If it's an adding a simple constant then integrate the offset.
14426   if (Base.getOpcode() == ISD::ADD) {
14427     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14428       Base = Base.getOperand(0);
14429       Offset += C->getZExtValue();
14430     }
14431   }
14432 
14433   // Return the underlying GlobalValue, and update the Offset.  Return false
14434   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14435   // by multiple nodes with different offsets.
14436   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14437     GV = G->getGlobal();
14438     Offset += G->getOffset();
14439     return false;
14440   }
14441 
14442   // Return the underlying Constant value, and update the Offset.  Return false
14443   // for ConstantSDNodes since the same constant pool entry may be represented
14444   // by multiple nodes with different offsets.
14445   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14446     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14447                                          : (const void *)C->getConstVal();
14448     Offset += C->getOffset();
14449     return false;
14450   }
14451   // If it's any of the following then it can't alias with anything but itself.
14452   return isa<FrameIndexSDNode>(Base);
14453 }
14454 
14455 /// Return true if there is any possibility that the two addresses overlap.
14456 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14457   // If they are the same then they must be aliases.
14458   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14459 
14460   // If they are both volatile then they cannot be reordered.
14461   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14462 
14463   // If one operation reads from invariant memory, and the other may store, they
14464   // cannot alias. These should really be checking the equivalent of mayWrite,
14465   // but it only matters for memory nodes other than load /store.
14466   if (Op0->isInvariant() && Op1->writeMem())
14467     return false;
14468 
14469   if (Op1->isInvariant() && Op0->writeMem())
14470     return false;
14471 
14472   // Gather base node and offset information.
14473   SDValue Base1, Base2;
14474   int64_t Offset1, Offset2;
14475   const GlobalValue *GV1, *GV2;
14476   const void *CV1, *CV2;
14477   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14478                                       Base1, Offset1, GV1, CV1);
14479   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14480                                       Base2, Offset2, GV2, CV2);
14481 
14482   // If they have a same base address then check to see if they overlap.
14483   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14484     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14485              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14486 
14487   // It is possible for different frame indices to alias each other, mostly
14488   // when tail call optimization reuses return address slots for arguments.
14489   // To catch this case, look up the actual index of frame indices to compute
14490   // the real alias relationship.
14491   if (isFrameIndex1 && isFrameIndex2) {
14492     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14493     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14494     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14495     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14496              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14497   }
14498 
14499   // Otherwise, if we know what the bases are, and they aren't identical, then
14500   // we know they cannot alias.
14501   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14502     return false;
14503 
14504   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14505   // compared to the size and offset of the access, we may be able to prove they
14506   // do not alias.  This check is conservative for now to catch cases created by
14507   // splitting vector types.
14508   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14509       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14510       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14511        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14512       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14513     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14514     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14515 
14516     // There is no overlap between these relatively aligned accesses of similar
14517     // size, return no alias.
14518     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14519         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14520       return false;
14521   }
14522 
14523   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14524                    ? CombinerGlobalAA
14525                    : DAG.getSubtarget().useAA();
14526 #ifndef NDEBUG
14527   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14528       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14529     UseAA = false;
14530 #endif
14531   if (UseAA &&
14532       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14533     // Use alias analysis information.
14534     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14535                                  Op1->getSrcValueOffset());
14536     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14537         Op0->getSrcValueOffset() - MinOffset;
14538     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14539         Op1->getSrcValueOffset() - MinOffset;
14540     AliasResult AAResult =
14541         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14542                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14543                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14544                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14545     if (AAResult == NoAlias)
14546       return false;
14547   }
14548 
14549   // Otherwise we have to assume they alias.
14550   return true;
14551 }
14552 
14553 /// Walk up chain skipping non-aliasing memory nodes,
14554 /// looking for aliasing nodes and adding them to the Aliases vector.
14555 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14556                                    SmallVectorImpl<SDValue> &Aliases) {
14557   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14558   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14559 
14560   // Get alias information for node.
14561   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14562 
14563   // Starting off.
14564   Chains.push_back(OriginalChain);
14565   unsigned Depth = 0;
14566 
14567   // Look at each chain and determine if it is an alias.  If so, add it to the
14568   // aliases list.  If not, then continue up the chain looking for the next
14569   // candidate.
14570   while (!Chains.empty()) {
14571     SDValue Chain = Chains.pop_back_val();
14572 
14573     // For TokenFactor nodes, look at each operand and only continue up the
14574     // chain until we reach the depth limit.
14575     //
14576     // FIXME: The depth check could be made to return the last non-aliasing
14577     // chain we found before we hit a tokenfactor rather than the original
14578     // chain.
14579     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14580       Aliases.clear();
14581       Aliases.push_back(OriginalChain);
14582       return;
14583     }
14584 
14585     // Don't bother if we've been before.
14586     if (!Visited.insert(Chain.getNode()).second)
14587       continue;
14588 
14589     switch (Chain.getOpcode()) {
14590     case ISD::EntryToken:
14591       // Entry token is ideal chain operand, but handled in FindBetterChain.
14592       break;
14593 
14594     case ISD::LOAD:
14595     case ISD::STORE: {
14596       // Get alias information for Chain.
14597       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14598           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14599 
14600       // If chain is alias then stop here.
14601       if (!(IsLoad && IsOpLoad) &&
14602           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14603         Aliases.push_back(Chain);
14604       } else {
14605         // Look further up the chain.
14606         Chains.push_back(Chain.getOperand(0));
14607         ++Depth;
14608       }
14609       break;
14610     }
14611 
14612     case ISD::TokenFactor:
14613       // We have to check each of the operands of the token factor for "small"
14614       // token factors, so we queue them up.  Adding the operands to the queue
14615       // (stack) in reverse order maintains the original order and increases the
14616       // likelihood that getNode will find a matching token factor (CSE.)
14617       if (Chain.getNumOperands() > 16) {
14618         Aliases.push_back(Chain);
14619         break;
14620       }
14621       for (unsigned n = Chain.getNumOperands(); n;)
14622         Chains.push_back(Chain.getOperand(--n));
14623       ++Depth;
14624       break;
14625 
14626     default:
14627       // For all other instructions we will just have to take what we can get.
14628       Aliases.push_back(Chain);
14629       break;
14630     }
14631   }
14632 
14633   // We need to be careful here to also search for aliases through the
14634   // value operand of a store, etc. Consider the following situation:
14635   //   Token1 = ...
14636   //   L1 = load Token1, %52
14637   //   S1 = store Token1, L1, %51
14638   //   L2 = load Token1, %52+8
14639   //   S2 = store Token1, L2, %51+8
14640   //   Token2 = Token(S1, S2)
14641   //   L3 = load Token2, %53
14642   //   S3 = store Token2, L3, %52
14643   //   L4 = load Token2, %53+8
14644   //   S4 = store Token2, L4, %52+8
14645   // If we search for aliases of S3 (which loads address %52), and we look
14646   // only through the chain, then we'll miss the trivial dependence on L1
14647   // (which also loads from %52). We then might change all loads and
14648   // stores to use Token1 as their chain operand, which could result in
14649   // copying %53 into %52 before copying %52 into %51 (which should
14650   // happen first).
14651   //
14652   // The problem is, however, that searching for such data dependencies
14653   // can become expensive, and the cost is not directly related to the
14654   // chain depth. Instead, we'll rule out such configurations here by
14655   // insisting that we've visited all chain users (except for users
14656   // of the original chain, which is not necessary). When doing this,
14657   // we need to look through nodes we don't care about (otherwise, things
14658   // like register copies will interfere with trivial cases).
14659 
14660   SmallVector<const SDNode *, 16> Worklist;
14661   for (const SDNode *N : Visited)
14662     if (N != OriginalChain.getNode())
14663       Worklist.push_back(N);
14664 
14665   while (!Worklist.empty()) {
14666     const SDNode *M = Worklist.pop_back_val();
14667 
14668     // We have already visited M, and want to make sure we've visited any uses
14669     // of M that we care about. For uses that we've not visisted, and don't
14670     // care about, queue them to the worklist.
14671 
14672     for (SDNode::use_iterator UI = M->use_begin(),
14673          UIE = M->use_end(); UI != UIE; ++UI)
14674       if (UI.getUse().getValueType() == MVT::Other &&
14675           Visited.insert(*UI).second) {
14676         if (isa<MemSDNode>(*UI)) {
14677           // We've not visited this use, and we care about it (it could have an
14678           // ordering dependency with the original node).
14679           Aliases.clear();
14680           Aliases.push_back(OriginalChain);
14681           return;
14682         }
14683 
14684         // We've not visited this use, but we don't care about it. Mark it as
14685         // visited and enqueue it to the worklist.
14686         Worklist.push_back(*UI);
14687       }
14688   }
14689 }
14690 
14691 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14692 /// (aliasing node.)
14693 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14694   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14695 
14696   // Accumulate all the aliases to this node.
14697   GatherAllAliases(N, OldChain, Aliases);
14698 
14699   // If no operands then chain to entry token.
14700   if (Aliases.size() == 0)
14701     return DAG.getEntryNode();
14702 
14703   // If a single operand then chain to it.  We don't need to revisit it.
14704   if (Aliases.size() == 1)
14705     return Aliases[0];
14706 
14707   // Construct a custom tailored token factor.
14708   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14709 }
14710 
14711 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14712   // This holds the base pointer, index, and the offset in bytes from the base
14713   // pointer.
14714   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
14715 
14716   // We must have a base and an offset.
14717   if (!BasePtr.Base.getNode())
14718     return false;
14719 
14720   // Do not handle stores to undef base pointers.
14721   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14722     return false;
14723 
14724   SmallVector<StoreSDNode *, 8> ChainedStores;
14725   ChainedStores.push_back(St);
14726 
14727   // Walk up the chain and look for nodes with offsets from the same
14728   // base pointer. Stop when reaching an instruction with a different kind
14729   // or instruction which has a different base pointer.
14730   StoreSDNode *Index = St;
14731   while (Index) {
14732     // If the chain has more than one use, then we can't reorder the mem ops.
14733     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14734       break;
14735 
14736     if (Index->isVolatile() || Index->isIndexed())
14737       break;
14738 
14739     // Find the base pointer and offset for this memory node.
14740     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
14741 
14742     // Check that the base pointer is the same as the original one.
14743     if (!Ptr.equalBaseIndex(BasePtr))
14744       break;
14745 
14746     // Find the next memory operand in the chain. If the next operand in the
14747     // chain is a store then move up and continue the scan with the next
14748     // memory operand. If the next operand is a load save it and use alias
14749     // information to check if it interferes with anything.
14750     SDNode *NextInChain = Index->getChain().getNode();
14751     while (true) {
14752       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14753         // We found a store node. Use it for the next iteration.
14754         if (STn->isVolatile() || STn->isIndexed()) {
14755           Index = nullptr;
14756           break;
14757         }
14758         ChainedStores.push_back(STn);
14759         Index = STn;
14760         break;
14761       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14762         NextInChain = Ldn->getChain().getNode();
14763         continue;
14764       } else {
14765         Index = nullptr;
14766         break;
14767       }
14768     }
14769   }
14770 
14771   bool MadeChange = false;
14772   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14773 
14774   for (StoreSDNode *ChainedStore : ChainedStores) {
14775     SDValue Chain = ChainedStore->getChain();
14776     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14777 
14778     if (Chain != BetterChain) {
14779       MadeChange = true;
14780       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14781     }
14782   }
14783 
14784   // Do all replacements after finding the replacements to make to avoid making
14785   // the chains more complicated by introducing new TokenFactors.
14786   for (auto Replacement : BetterChains)
14787     replaceStoreChain(Replacement.first, Replacement.second);
14788 
14789   return MadeChange;
14790 }
14791 
14792 /// This is the entry point for the file.
14793 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14794                            CodeGenOpt::Level OptLevel) {
14795   /// This is the main entry point to this class.
14796   DAGCombiner(*this, AA, OptLevel).Run(Level);
14797 }
14798