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/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "dagcombine"
45 
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52 
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65 
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72 
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80 
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84 
85 //------------------------------ DAGCombiner ---------------------------------//
86 
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95 
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104 
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111 
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117 
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120 
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127 
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130 
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139 
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143 
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147 
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151 
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156 
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159 
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163 
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168 
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175 
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 
178   private:
179 
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188 
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195 
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214 
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
216                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
217                          ISD::NodeType ExtType);
218 
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223 
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitCTLZ(SDNode *N);
263     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTTZ(SDNode *N);
265     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
266     SDValue visitCTPOP(SDNode *N);
267     SDValue visitSELECT(SDNode *N);
268     SDValue visitVSELECT(SDNode *N);
269     SDValue visitSELECT_CC(SDNode *N);
270     SDValue visitSETCC(SDNode *N);
271     SDValue visitSETCCE(SDNode *N);
272     SDValue visitSIGN_EXTEND(SDNode *N);
273     SDValue visitZERO_EXTEND(SDNode *N);
274     SDValue visitANY_EXTEND(SDNode *N);
275     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
276     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
277     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitTRUNCATE(SDNode *N);
279     SDValue visitBITCAST(SDNode *N);
280     SDValue visitBUILD_PAIR(SDNode *N);
281     SDValue visitFADD(SDNode *N);
282     SDValue visitFSUB(SDNode *N);
283     SDValue visitFMUL(SDNode *N);
284     SDValue visitFMA(SDNode *N);
285     SDValue visitFDIV(SDNode *N);
286     SDValue visitFREM(SDNode *N);
287     SDValue visitFSQRT(SDNode *N);
288     SDValue visitFCOPYSIGN(SDNode *N);
289     SDValue visitSINT_TO_FP(SDNode *N);
290     SDValue visitUINT_TO_FP(SDNode *N);
291     SDValue visitFP_TO_SINT(SDNode *N);
292     SDValue visitFP_TO_UINT(SDNode *N);
293     SDValue visitFP_ROUND(SDNode *N);
294     SDValue visitFP_ROUND_INREG(SDNode *N);
295     SDValue visitFP_EXTEND(SDNode *N);
296     SDValue visitFNEG(SDNode *N);
297     SDValue visitFABS(SDNode *N);
298     SDValue visitFCEIL(SDNode *N);
299     SDValue visitFTRUNC(SDNode *N);
300     SDValue visitFFLOOR(SDNode *N);
301     SDValue visitFMINNUM(SDNode *N);
302     SDValue visitFMAXNUM(SDNode *N);
303     SDValue visitBRCOND(SDNode *N);
304     SDValue visitBR_CC(SDNode *N);
305     SDValue visitLOAD(SDNode *N);
306 
307     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
308     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
309 
310     SDValue visitSTORE(SDNode *N);
311     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
312     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
313     SDValue visitBUILD_VECTOR(SDNode *N);
314     SDValue visitCONCAT_VECTORS(SDNode *N);
315     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
316     SDValue visitVECTOR_SHUFFLE(SDNode *N);
317     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
318     SDValue visitINSERT_SUBVECTOR(SDNode *N);
319     SDValue visitMLOAD(SDNode *N);
320     SDValue visitMSTORE(SDNode *N);
321     SDValue visitMGATHER(SDNode *N);
322     SDValue visitMSCATTER(SDNode *N);
323     SDValue visitFP_TO_FP16(SDNode *N);
324     SDValue visitFP16_TO_FP(SDNode *N);
325 
326     SDValue visitFADDForFMACombine(SDNode *N);
327     SDValue visitFSUBForFMACombine(SDNode *N);
328     SDValue visitFMULForFMACombine(SDNode *N);
329 
330     SDValue XformToShuffleWithZero(SDNode *N);
331     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
332 
333     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
334 
335     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
336     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
337     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
338     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
339                              SDValue N3, ISD::CondCode CC,
340                              bool NotExtCompare = false);
341     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
342                           SDLoc DL, bool foldBooleans = true);
343 
344     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
345                            SDValue &CC) const;
346     bool isOneUseSetCC(SDValue N) const;
347 
348     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
349                                          unsigned HiOp);
350     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
351     SDValue CombineExtLoad(SDNode *N);
352     SDValue combineRepeatedFPDivisors(SDNode *N);
353     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
354     SDValue BuildSDIV(SDNode *N);
355     SDValue BuildSDIVPow2(SDNode *N);
356     SDValue BuildUDIV(SDNode *N);
357     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
358     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
359     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
360                                  SDNodeFlags *Flags);
361     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
362                                  SDNodeFlags *Flags);
363     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
364                                bool DemandHighBits = true);
365     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
366     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
367                               SDValue InnerPos, SDValue InnerNeg,
368                               unsigned PosOpcode, unsigned NegOpcode,
369                               SDLoc DL);
370     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
371     SDValue ReduceLoadWidth(SDNode *N);
372     SDValue ReduceLoadOpStoreWidth(SDNode *N);
373     SDValue TransformFPLoadStorePair(SDNode *N);
374     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
375     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
376 
377     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
378 
379     /// Walk up chain skipping non-aliasing memory nodes,
380     /// looking for aliasing nodes and adding them to the Aliases vector.
381     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
382                           SmallVectorImpl<SDValue> &Aliases);
383 
384     /// Return true if there is any possibility that the two addresses overlap.
385     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
386 
387     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
388     /// chain (aliasing node.)
389     SDValue FindBetterChain(SDNode *N, SDValue Chain);
390 
391     /// Do FindBetterChain for a store and any possibly adjacent stores on
392     /// consecutive chains.
393     bool findBetterNeighborChains(StoreSDNode *St);
394 
395     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
396     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
397 
398     /// Holds a pointer to an LSBaseSDNode as well as information on where it
399     /// is located in a sequence of memory operations connected by a chain.
400     struct MemOpLink {
401       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
402       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
403       // Ptr to the mem node.
404       LSBaseSDNode *MemNode;
405       // Offset from the base ptr.
406       int64_t OffsetFromBase;
407       // What is the sequence number of this mem node.
408       // Lowest mem operand in the DAG starts at zero.
409       unsigned SequenceNum;
410     };
411 
412     /// This is a helper function for visitMUL to check the profitability
413     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
414     /// MulNode is the original multiply, AddNode is (add x, c1),
415     /// and ConstNode is c2.
416     bool isMulAddWithConstProfitable(SDNode *MulNode,
417                                      SDValue &AddNode,
418                                      SDValue &ConstNode);
419 
420     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
421     /// constant build_vector of the stored constant values in Stores.
422     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
423                                          SDLoc SL,
424                                          ArrayRef<MemOpLink> Stores,
425                                          SmallVectorImpl<SDValue> &Chains,
426                                          EVT Ty) const;
427 
428     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
429     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
430     /// the type of the loaded value to be extended.  LoadedVT returns the type
431     /// of the original loaded value.  NarrowLoad returns whether the load would
432     /// need to be narrowed in order to match.
433     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
434                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
435                           bool &NarrowLoad);
436 
437     /// This is a helper function for MergeConsecutiveStores. When the source
438     /// elements of the consecutive stores are all constants or all extracted
439     /// vector elements, try to merge them into one larger store.
440     /// \return True if a merged store was created.
441     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
442                                          EVT MemVT, unsigned NumStores,
443                                          bool IsConstantSrc, bool UseVector);
444 
445     /// This is a helper function for MergeConsecutiveStores.
446     /// Stores that may be merged are placed in StoreNodes.
447     /// Loads that may alias with those stores are placed in AliasLoadNodes.
448     void getStoreMergeAndAliasCandidates(
449         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
450         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
451 
452     /// Helper function for MergeConsecutiveStores. Checks if
453     /// Candidate stores have indirect dependency through their
454     /// operands. \return True if safe to merge
455     bool checkMergeStoreCandidatesForDependencies(
456         SmallVectorImpl<MemOpLink> &StoreNodes);
457 
458     /// Merge consecutive store operations into a wide store.
459     /// This optimization uses wide integers or vectors when possible.
460     /// \return True if some memory operations were changed.
461     bool MergeConsecutiveStores(StoreSDNode *N);
462 
463     /// \brief Try to transform a truncation where C is a constant:
464     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
465     ///
466     /// \p N needs to be a truncation and its first operand an AND. Other
467     /// requirements are checked by the function (e.g. that trunc is
468     /// single-use) and if missed an empty SDValue is returned.
469     SDValue distributeTruncateThroughAnd(SDNode *N);
470 
471   public:
472     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
473         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
474           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
475       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
476     }
477 
478     /// Runs the dag combiner on all nodes in the work list
479     void Run(CombineLevel AtLevel);
480 
481     SelectionDAG &getDAG() const { return DAG; }
482 
483     /// Returns a type large enough to hold any valid shift amount - before type
484     /// legalization these can be huge.
485     EVT getShiftAmountTy(EVT LHSTy) {
486       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
487       if (LHSTy.isVector())
488         return LHSTy;
489       auto &DL = DAG.getDataLayout();
490       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
491                         : TLI.getPointerTy(DL);
492     }
493 
494     /// This method returns true if we are running before type legalization or
495     /// if the specified VT is legal.
496     bool isTypeLegal(const EVT &VT) {
497       if (!LegalTypes) return true;
498       return TLI.isTypeLegal(VT);
499     }
500 
501     /// Convenience wrapper around TargetLowering::getSetCCResultType
502     EVT getSetCCResultType(EVT VT) const {
503       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
504     }
505   };
506 }
507 
508 
509 namespace {
510 /// This class is a DAGUpdateListener that removes any deleted
511 /// nodes from the worklist.
512 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
513   DAGCombiner &DC;
514 public:
515   explicit WorklistRemover(DAGCombiner &dc)
516     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
517 
518   void NodeDeleted(SDNode *N, SDNode *E) override {
519     DC.removeFromWorklist(N);
520   }
521 };
522 }
523 
524 //===----------------------------------------------------------------------===//
525 //  TargetLowering::DAGCombinerInfo implementation
526 //===----------------------------------------------------------------------===//
527 
528 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
529   ((DAGCombiner*)DC)->AddToWorklist(N);
530 }
531 
532 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
533   ((DAGCombiner*)DC)->removeFromWorklist(N);
534 }
535 
536 SDValue TargetLowering::DAGCombinerInfo::
537 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
538   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
539 }
540 
541 SDValue TargetLowering::DAGCombinerInfo::
542 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
543   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
544 }
545 
546 
547 SDValue TargetLowering::DAGCombinerInfo::
548 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
549   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
550 }
551 
552 void TargetLowering::DAGCombinerInfo::
553 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
554   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
555 }
556 
557 //===----------------------------------------------------------------------===//
558 // Helper Functions
559 //===----------------------------------------------------------------------===//
560 
561 void DAGCombiner::deleteAndRecombine(SDNode *N) {
562   removeFromWorklist(N);
563 
564   // If the operands of this node are only used by the node, they will now be
565   // dead. Make sure to re-visit them and recursively delete dead nodes.
566   for (const SDValue &Op : N->ops())
567     // For an operand generating multiple values, one of the values may
568     // become dead allowing further simplification (e.g. split index
569     // arithmetic from an indexed load).
570     if (Op->hasOneUse() || Op->getNumValues() > 1)
571       AddToWorklist(Op.getNode());
572 
573   DAG.DeleteNode(N);
574 }
575 
576 /// Return 1 if we can compute the negated form of the specified expression for
577 /// the same cost as the expression itself, or 2 if we can compute the negated
578 /// form more cheaply than the expression itself.
579 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
580                                const TargetLowering &TLI,
581                                const TargetOptions *Options,
582                                unsigned Depth = 0) {
583   // fneg is removable even if it has multiple uses.
584   if (Op.getOpcode() == ISD::FNEG) return 2;
585 
586   // Don't allow anything with multiple uses.
587   if (!Op.hasOneUse()) return 0;
588 
589   // Don't recurse exponentially.
590   if (Depth > 6) return 0;
591 
592   switch (Op.getOpcode()) {
593   default: return false;
594   case ISD::ConstantFP:
595     // Don't invert constant FP values after legalize.  The negated constant
596     // isn't necessarily legal.
597     return LegalOperations ? 0 : 1;
598   case ISD::FADD:
599     // FIXME: determine better conditions for this xform.
600     if (!Options->UnsafeFPMath) return 0;
601 
602     // After operation legalization, it might not be legal to create new FSUBs.
603     if (LegalOperations &&
604         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
605       return 0;
606 
607     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
608     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
609                                     Options, Depth + 1))
610       return V;
611     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
612     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
613                               Depth + 1);
614   case ISD::FSUB:
615     // We can't turn -(A-B) into B-A when we honor signed zeros.
616     if (!Options->UnsafeFPMath) return 0;
617 
618     // fold (fneg (fsub A, B)) -> (fsub B, A)
619     return 1;
620 
621   case ISD::FMUL:
622   case ISD::FDIV:
623     if (Options->HonorSignDependentRoundingFPMath()) return 0;
624 
625     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
626     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
627                                     Options, Depth + 1))
628       return V;
629 
630     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
631                               Depth + 1);
632 
633   case ISD::FP_EXTEND:
634   case ISD::FP_ROUND:
635   case ISD::FSIN:
636     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
637                               Depth + 1);
638   }
639 }
640 
641 /// If isNegatibleForFree returns true, return the newly negated expression.
642 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
643                                     bool LegalOperations, unsigned Depth = 0) {
644   const TargetOptions &Options = DAG.getTarget().Options;
645   // fneg is removable even if it has multiple uses.
646   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
647 
648   // Don't allow anything with multiple uses.
649   assert(Op.hasOneUse() && "Unknown reuse!");
650 
651   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
652 
653   const SDNodeFlags *Flags = Op.getNode()->getFlags();
654 
655   switch (Op.getOpcode()) {
656   default: llvm_unreachable("Unknown code");
657   case ISD::ConstantFP: {
658     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
659     V.changeSign();
660     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
661   }
662   case ISD::FADD:
663     // FIXME: determine better conditions for this xform.
664     assert(Options.UnsafeFPMath);
665 
666     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
667     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
668                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
669       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
670                          GetNegatedExpression(Op.getOperand(0), DAG,
671                                               LegalOperations, Depth+1),
672                          Op.getOperand(1), Flags);
673     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
674     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
675                        GetNegatedExpression(Op.getOperand(1), DAG,
676                                             LegalOperations, Depth+1),
677                        Op.getOperand(0), Flags);
678   case ISD::FSUB:
679     // We can't turn -(A-B) into B-A when we honor signed zeros.
680     assert(Options.UnsafeFPMath);
681 
682     // fold (fneg (fsub 0, B)) -> B
683     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
684       if (N0CFP->isZero())
685         return Op.getOperand(1);
686 
687     // fold (fneg (fsub A, B)) -> (fsub B, A)
688     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
689                        Op.getOperand(1), Op.getOperand(0), Flags);
690 
691   case ISD::FMUL:
692   case ISD::FDIV:
693     assert(!Options.HonorSignDependentRoundingFPMath());
694 
695     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
696     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
697                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
698       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
699                          GetNegatedExpression(Op.getOperand(0), DAG,
700                                               LegalOperations, Depth+1),
701                          Op.getOperand(1), Flags);
702 
703     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
704     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
705                        Op.getOperand(0),
706                        GetNegatedExpression(Op.getOperand(1), DAG,
707                                             LegalOperations, Depth+1), Flags);
708 
709   case ISD::FP_EXTEND:
710   case ISD::FSIN:
711     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
712                        GetNegatedExpression(Op.getOperand(0), DAG,
713                                             LegalOperations, Depth+1));
714   case ISD::FP_ROUND:
715       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
716                          GetNegatedExpression(Op.getOperand(0), DAG,
717                                               LegalOperations, Depth+1),
718                          Op.getOperand(1));
719   }
720 }
721 
722 // Return true if this node is a setcc, or is a select_cc
723 // that selects between the target values used for true and false, making it
724 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
725 // the appropriate nodes based on the type of node we are checking. This
726 // simplifies life a bit for the callers.
727 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
728                                     SDValue &CC) const {
729   if (N.getOpcode() == ISD::SETCC) {
730     LHS = N.getOperand(0);
731     RHS = N.getOperand(1);
732     CC  = N.getOperand(2);
733     return true;
734   }
735 
736   if (N.getOpcode() != ISD::SELECT_CC ||
737       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
738       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
739     return false;
740 
741   if (TLI.getBooleanContents(N.getValueType()) ==
742       TargetLowering::UndefinedBooleanContent)
743     return false;
744 
745   LHS = N.getOperand(0);
746   RHS = N.getOperand(1);
747   CC  = N.getOperand(4);
748   return true;
749 }
750 
751 /// Return true if this is a SetCC-equivalent operation with only one use.
752 /// If this is true, it allows the users to invert the operation for free when
753 /// it is profitable to do so.
754 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
755   SDValue N0, N1, N2;
756   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
757     return true;
758   return false;
759 }
760 
761 /// Returns true if N is a BUILD_VECTOR node whose
762 /// elements are all the same constant or undefined.
763 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
764   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
765   if (!C)
766     return false;
767 
768   APInt SplatUndef;
769   unsigned SplatBitSize;
770   bool HasAnyUndefs;
771   EVT EltVT = N->getValueType(0).getVectorElementType();
772   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
773                              HasAnyUndefs) &&
774           EltVT.getSizeInBits() >= SplatBitSize);
775 }
776 
777 // \brief Returns the SDNode if it is a constant float BuildVector
778 // or constant float.
779 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
780   if (isa<ConstantFPSDNode>(N))
781     return N.getNode();
782   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
783     return N.getNode();
784   return nullptr;
785 }
786 
787 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
788 // int.
789 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
790   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
791     return CN;
792 
793   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
794     BitVector UndefElements;
795     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
796 
797     // BuildVectors can truncate their operands. Ignore that case here.
798     // FIXME: We blindly ignore splats which include undef which is overly
799     // pessimistic.
800     if (CN && UndefElements.none() &&
801         CN->getValueType(0) == N.getValueType().getScalarType())
802       return CN;
803   }
804 
805   return nullptr;
806 }
807 
808 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
809 // float.
810 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
811   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
812     return CN;
813 
814   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
815     BitVector UndefElements;
816     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
817 
818     if (CN && UndefElements.none())
819       return CN;
820   }
821 
822   return nullptr;
823 }
824 
825 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
826                                     SDValue N0, SDValue N1) {
827   EVT VT = N0.getValueType();
828   if (N0.getOpcode() == Opc) {
829     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
830       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
831         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
832         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
833           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
834         return SDValue();
835       }
836       if (N0.hasOneUse()) {
837         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
838         // use
839         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
840         if (!OpNode.getNode())
841           return SDValue();
842         AddToWorklist(OpNode.getNode());
843         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
844       }
845     }
846   }
847 
848   if (N1.getOpcode() == Opc) {
849     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
850       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
851         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
852         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
853           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
854         return SDValue();
855       }
856       if (N1.hasOneUse()) {
857         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
858         // use
859         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
860         if (!OpNode.getNode())
861           return SDValue();
862         AddToWorklist(OpNode.getNode());
863         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
864       }
865     }
866   }
867 
868   return SDValue();
869 }
870 
871 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
872                                bool AddTo) {
873   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
874   ++NodesCombined;
875   DEBUG(dbgs() << "\nReplacing.1 ";
876         N->dump(&DAG);
877         dbgs() << "\nWith: ";
878         To[0].getNode()->dump(&DAG);
879         dbgs() << " and " << NumTo-1 << " other values\n");
880   for (unsigned i = 0, e = NumTo; i != e; ++i)
881     assert((!To[i].getNode() ||
882             N->getValueType(i) == To[i].getValueType()) &&
883            "Cannot combine value to value of different type!");
884 
885   WorklistRemover DeadNodes(*this);
886   DAG.ReplaceAllUsesWith(N, To);
887   if (AddTo) {
888     // Push the new nodes and any users onto the worklist
889     for (unsigned i = 0, e = NumTo; i != e; ++i) {
890       if (To[i].getNode()) {
891         AddToWorklist(To[i].getNode());
892         AddUsersToWorklist(To[i].getNode());
893       }
894     }
895   }
896 
897   // Finally, if the node is now dead, remove it from the graph.  The node
898   // may not be dead if the replacement process recursively simplified to
899   // something else needing this node.
900   if (N->use_empty())
901     deleteAndRecombine(N);
902   return SDValue(N, 0);
903 }
904 
905 void DAGCombiner::
906 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
907   // Replace all uses.  If any nodes become isomorphic to other nodes and
908   // are deleted, make sure to remove them from our worklist.
909   WorklistRemover DeadNodes(*this);
910   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
911 
912   // Push the new node and any (possibly new) users onto the worklist.
913   AddToWorklist(TLO.New.getNode());
914   AddUsersToWorklist(TLO.New.getNode());
915 
916   // Finally, if the node is now dead, remove it from the graph.  The node
917   // may not be dead if the replacement process recursively simplified to
918   // something else needing this node.
919   if (TLO.Old.getNode()->use_empty())
920     deleteAndRecombine(TLO.Old.getNode());
921 }
922 
923 /// Check the specified integer node value to see if it can be simplified or if
924 /// things it uses can be simplified by bit propagation. If so, return true.
925 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
926   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
927   APInt KnownZero, KnownOne;
928   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
929     return false;
930 
931   // Revisit the node.
932   AddToWorklist(Op.getNode());
933 
934   // Replace the old value with the new one.
935   ++NodesCombined;
936   DEBUG(dbgs() << "\nReplacing.2 ";
937         TLO.Old.getNode()->dump(&DAG);
938         dbgs() << "\nWith: ";
939         TLO.New.getNode()->dump(&DAG);
940         dbgs() << '\n');
941 
942   CommitTargetLoweringOpt(TLO);
943   return true;
944 }
945 
946 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
947   SDLoc dl(Load);
948   EVT VT = Load->getValueType(0);
949   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
950 
951   DEBUG(dbgs() << "\nReplacing.9 ";
952         Load->dump(&DAG);
953         dbgs() << "\nWith: ";
954         Trunc.getNode()->dump(&DAG);
955         dbgs() << '\n');
956   WorklistRemover DeadNodes(*this);
957   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
958   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
959   deleteAndRecombine(Load);
960   AddToWorklist(Trunc.getNode());
961 }
962 
963 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
964   Replace = false;
965   SDLoc dl(Op);
966   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
967     LoadSDNode *LD = cast<LoadSDNode>(Op);
968     EVT MemVT = LD->getMemoryVT();
969     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
970       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
971                                                        : ISD::EXTLOAD)
972       : LD->getExtensionType();
973     Replace = true;
974     return DAG.getExtLoad(ExtType, dl, PVT,
975                           LD->getChain(), LD->getBasePtr(),
976                           MemVT, LD->getMemOperand());
977   }
978 
979   unsigned Opc = Op.getOpcode();
980   switch (Opc) {
981   default: break;
982   case ISD::AssertSext:
983     return DAG.getNode(ISD::AssertSext, dl, PVT,
984                        SExtPromoteOperand(Op.getOperand(0), PVT),
985                        Op.getOperand(1));
986   case ISD::AssertZext:
987     return DAG.getNode(ISD::AssertZext, dl, PVT,
988                        ZExtPromoteOperand(Op.getOperand(0), PVT),
989                        Op.getOperand(1));
990   case ISD::Constant: {
991     unsigned ExtOpc =
992       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
993     return DAG.getNode(ExtOpc, dl, PVT, Op);
994   }
995   }
996 
997   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
998     return SDValue();
999   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1000 }
1001 
1002 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1003   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1004     return SDValue();
1005   EVT OldVT = Op.getValueType();
1006   SDLoc dl(Op);
1007   bool Replace = false;
1008   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1009   if (!NewOp.getNode())
1010     return SDValue();
1011   AddToWorklist(NewOp.getNode());
1012 
1013   if (Replace)
1014     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1015   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1016                      DAG.getValueType(OldVT));
1017 }
1018 
1019 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1020   EVT OldVT = Op.getValueType();
1021   SDLoc dl(Op);
1022   bool Replace = false;
1023   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1024   if (!NewOp.getNode())
1025     return SDValue();
1026   AddToWorklist(NewOp.getNode());
1027 
1028   if (Replace)
1029     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1030   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1031 }
1032 
1033 /// Promote the specified integer binary operation if the target indicates it is
1034 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1035 /// i32 since i16 instructions are longer.
1036 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1037   if (!LegalOperations)
1038     return SDValue();
1039 
1040   EVT VT = Op.getValueType();
1041   if (VT.isVector() || !VT.isInteger())
1042     return SDValue();
1043 
1044   // If operation type is 'undesirable', e.g. i16 on x86, consider
1045   // promoting it.
1046   unsigned Opc = Op.getOpcode();
1047   if (TLI.isTypeDesirableForOp(Opc, VT))
1048     return SDValue();
1049 
1050   EVT PVT = VT;
1051   // Consult target whether it is a good idea to promote this operation and
1052   // what's the right type to promote it to.
1053   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1054     assert(PVT != VT && "Don't know what type to promote to!");
1055 
1056     bool Replace0 = false;
1057     SDValue N0 = Op.getOperand(0);
1058     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1059     if (!NN0.getNode())
1060       return SDValue();
1061 
1062     bool Replace1 = false;
1063     SDValue N1 = Op.getOperand(1);
1064     SDValue NN1;
1065     if (N0 == N1)
1066       NN1 = NN0;
1067     else {
1068       NN1 = PromoteOperand(N1, PVT, Replace1);
1069       if (!NN1.getNode())
1070         return SDValue();
1071     }
1072 
1073     AddToWorklist(NN0.getNode());
1074     if (NN1.getNode())
1075       AddToWorklist(NN1.getNode());
1076 
1077     if (Replace0)
1078       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1079     if (Replace1)
1080       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1081 
1082     DEBUG(dbgs() << "\nPromoting ";
1083           Op.getNode()->dump(&DAG));
1084     SDLoc dl(Op);
1085     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1086                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1087   }
1088   return SDValue();
1089 }
1090 
1091 /// Promote the specified integer shift operation if the target indicates it is
1092 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1093 /// i32 since i16 instructions are longer.
1094 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1095   if (!LegalOperations)
1096     return SDValue();
1097 
1098   EVT VT = Op.getValueType();
1099   if (VT.isVector() || !VT.isInteger())
1100     return SDValue();
1101 
1102   // If operation type is 'undesirable', e.g. i16 on x86, consider
1103   // promoting it.
1104   unsigned Opc = Op.getOpcode();
1105   if (TLI.isTypeDesirableForOp(Opc, VT))
1106     return SDValue();
1107 
1108   EVT PVT = VT;
1109   // Consult target whether it is a good idea to promote this operation and
1110   // what's the right type to promote it to.
1111   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1112     assert(PVT != VT && "Don't know what type to promote to!");
1113 
1114     bool Replace = false;
1115     SDValue N0 = Op.getOperand(0);
1116     if (Opc == ISD::SRA)
1117       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1118     else if (Opc == ISD::SRL)
1119       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1120     else
1121       N0 = PromoteOperand(N0, PVT, Replace);
1122     if (!N0.getNode())
1123       return SDValue();
1124 
1125     AddToWorklist(N0.getNode());
1126     if (Replace)
1127       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1128 
1129     DEBUG(dbgs() << "\nPromoting ";
1130           Op.getNode()->dump(&DAG));
1131     SDLoc dl(Op);
1132     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1133                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1134   }
1135   return SDValue();
1136 }
1137 
1138 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1139   if (!LegalOperations)
1140     return SDValue();
1141 
1142   EVT VT = Op.getValueType();
1143   if (VT.isVector() || !VT.isInteger())
1144     return SDValue();
1145 
1146   // If operation type is 'undesirable', e.g. i16 on x86, consider
1147   // promoting it.
1148   unsigned Opc = Op.getOpcode();
1149   if (TLI.isTypeDesirableForOp(Opc, VT))
1150     return SDValue();
1151 
1152   EVT PVT = VT;
1153   // Consult target whether it is a good idea to promote this operation and
1154   // what's the right type to promote it to.
1155   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1156     assert(PVT != VT && "Don't know what type to promote to!");
1157     // fold (aext (aext x)) -> (aext x)
1158     // fold (aext (zext x)) -> (zext x)
1159     // fold (aext (sext x)) -> (sext x)
1160     DEBUG(dbgs() << "\nPromoting ";
1161           Op.getNode()->dump(&DAG));
1162     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1163   }
1164   return SDValue();
1165 }
1166 
1167 bool DAGCombiner::PromoteLoad(SDValue Op) {
1168   if (!LegalOperations)
1169     return false;
1170 
1171   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1172     return false;
1173 
1174   EVT VT = Op.getValueType();
1175   if (VT.isVector() || !VT.isInteger())
1176     return false;
1177 
1178   // If operation type is 'undesirable', e.g. i16 on x86, consider
1179   // promoting it.
1180   unsigned Opc = Op.getOpcode();
1181   if (TLI.isTypeDesirableForOp(Opc, VT))
1182     return false;
1183 
1184   EVT PVT = VT;
1185   // Consult target whether it is a good idea to promote this operation and
1186   // what's the right type to promote it to.
1187   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1188     assert(PVT != VT && "Don't know what type to promote to!");
1189 
1190     SDLoc dl(Op);
1191     SDNode *N = Op.getNode();
1192     LoadSDNode *LD = cast<LoadSDNode>(N);
1193     EVT MemVT = LD->getMemoryVT();
1194     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1195       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1196                                                        : ISD::EXTLOAD)
1197       : LD->getExtensionType();
1198     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1199                                    LD->getChain(), LD->getBasePtr(),
1200                                    MemVT, LD->getMemOperand());
1201     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1202 
1203     DEBUG(dbgs() << "\nPromoting ";
1204           N->dump(&DAG);
1205           dbgs() << "\nTo: ";
1206           Result.getNode()->dump(&DAG);
1207           dbgs() << '\n');
1208     WorklistRemover DeadNodes(*this);
1209     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1210     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1211     deleteAndRecombine(N);
1212     AddToWorklist(Result.getNode());
1213     return true;
1214   }
1215   return false;
1216 }
1217 
1218 /// \brief Recursively delete a node which has no uses and any operands for
1219 /// which it is the only use.
1220 ///
1221 /// Note that this both deletes the nodes and removes them from the worklist.
1222 /// It also adds any nodes who have had a user deleted to the worklist as they
1223 /// may now have only one use and subject to other combines.
1224 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1225   if (!N->use_empty())
1226     return false;
1227 
1228   SmallSetVector<SDNode *, 16> Nodes;
1229   Nodes.insert(N);
1230   do {
1231     N = Nodes.pop_back_val();
1232     if (!N)
1233       continue;
1234 
1235     if (N->use_empty()) {
1236       for (const SDValue &ChildN : N->op_values())
1237         Nodes.insert(ChildN.getNode());
1238 
1239       removeFromWorklist(N);
1240       DAG.DeleteNode(N);
1241     } else {
1242       AddToWorklist(N);
1243     }
1244   } while (!Nodes.empty());
1245   return true;
1246 }
1247 
1248 //===----------------------------------------------------------------------===//
1249 //  Main DAG Combiner implementation
1250 //===----------------------------------------------------------------------===//
1251 
1252 void DAGCombiner::Run(CombineLevel AtLevel) {
1253   // set the instance variables, so that the various visit routines may use it.
1254   Level = AtLevel;
1255   LegalOperations = Level >= AfterLegalizeVectorOps;
1256   LegalTypes = Level >= AfterLegalizeTypes;
1257 
1258   // Add all the dag nodes to the worklist.
1259   for (SDNode &Node : DAG.allnodes())
1260     AddToWorklist(&Node);
1261 
1262   // Create a dummy node (which is not added to allnodes), that adds a reference
1263   // to the root node, preventing it from being deleted, and tracking any
1264   // changes of the root.
1265   HandleSDNode Dummy(DAG.getRoot());
1266 
1267   // While the worklist isn't empty, find a node and try to combine it.
1268   while (!WorklistMap.empty()) {
1269     SDNode *N;
1270     // The Worklist holds the SDNodes in order, but it may contain null entries.
1271     do {
1272       N = Worklist.pop_back_val();
1273     } while (!N);
1274 
1275     bool GoodWorklistEntry = WorklistMap.erase(N);
1276     (void)GoodWorklistEntry;
1277     assert(GoodWorklistEntry &&
1278            "Found a worklist entry without a corresponding map entry!");
1279 
1280     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1281     // N is deleted from the DAG, since they too may now be dead or may have a
1282     // reduced number of uses, allowing other xforms.
1283     if (recursivelyDeleteUnusedNodes(N))
1284       continue;
1285 
1286     WorklistRemover DeadNodes(*this);
1287 
1288     // If this combine is running after legalizing the DAG, re-legalize any
1289     // nodes pulled off the worklist.
1290     if (Level == AfterLegalizeDAG) {
1291       SmallSetVector<SDNode *, 16> UpdatedNodes;
1292       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1293 
1294       for (SDNode *LN : UpdatedNodes) {
1295         AddToWorklist(LN);
1296         AddUsersToWorklist(LN);
1297       }
1298       if (!NIsValid)
1299         continue;
1300     }
1301 
1302     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1303 
1304     // Add any operands of the new node which have not yet been combined to the
1305     // worklist as well. Because the worklist uniques things already, this
1306     // won't repeatedly process the same operand.
1307     CombinedNodes.insert(N);
1308     for (const SDValue &ChildN : N->op_values())
1309       if (!CombinedNodes.count(ChildN.getNode()))
1310         AddToWorklist(ChildN.getNode());
1311 
1312     SDValue RV = combine(N);
1313 
1314     if (!RV.getNode())
1315       continue;
1316 
1317     ++NodesCombined;
1318 
1319     // If we get back the same node we passed in, rather than a new node or
1320     // zero, we know that the node must have defined multiple values and
1321     // CombineTo was used.  Since CombineTo takes care of the worklist
1322     // mechanics for us, we have no work to do in this case.
1323     if (RV.getNode() == N)
1324       continue;
1325 
1326     assert(N->getOpcode() != ISD::DELETED_NODE &&
1327            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1328            "Node was deleted but visit returned new node!");
1329 
1330     DEBUG(dbgs() << " ... into: ";
1331           RV.getNode()->dump(&DAG));
1332 
1333     // Transfer debug value.
1334     DAG.TransferDbgValues(SDValue(N, 0), RV);
1335     if (N->getNumValues() == RV.getNode()->getNumValues())
1336       DAG.ReplaceAllUsesWith(N, RV.getNode());
1337     else {
1338       assert(N->getValueType(0) == RV.getValueType() &&
1339              N->getNumValues() == 1 && "Type mismatch");
1340       SDValue OpV = RV;
1341       DAG.ReplaceAllUsesWith(N, &OpV);
1342     }
1343 
1344     // Push the new node and any users onto the worklist
1345     AddToWorklist(RV.getNode());
1346     AddUsersToWorklist(RV.getNode());
1347 
1348     // Finally, if the node is now dead, remove it from the graph.  The node
1349     // may not be dead if the replacement process recursively simplified to
1350     // something else needing this node. This will also take care of adding any
1351     // operands which have lost a user to the worklist.
1352     recursivelyDeleteUnusedNodes(N);
1353   }
1354 
1355   // If the root changed (e.g. it was a dead load, update the root).
1356   DAG.setRoot(Dummy.getValue());
1357   DAG.RemoveDeadNodes();
1358 }
1359 
1360 SDValue DAGCombiner::visit(SDNode *N) {
1361   switch (N->getOpcode()) {
1362   default: break;
1363   case ISD::TokenFactor:        return visitTokenFactor(N);
1364   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1365   case ISD::ADD:                return visitADD(N);
1366   case ISD::SUB:                return visitSUB(N);
1367   case ISD::ADDC:               return visitADDC(N);
1368   case ISD::SUBC:               return visitSUBC(N);
1369   case ISD::ADDE:               return visitADDE(N);
1370   case ISD::SUBE:               return visitSUBE(N);
1371   case ISD::MUL:                return visitMUL(N);
1372   case ISD::SDIV:               return visitSDIV(N);
1373   case ISD::UDIV:               return visitUDIV(N);
1374   case ISD::SREM:
1375   case ISD::UREM:               return visitREM(N);
1376   case ISD::MULHU:              return visitMULHU(N);
1377   case ISD::MULHS:              return visitMULHS(N);
1378   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1379   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1380   case ISD::SMULO:              return visitSMULO(N);
1381   case ISD::UMULO:              return visitUMULO(N);
1382   case ISD::SMIN:
1383   case ISD::SMAX:
1384   case ISD::UMIN:
1385   case ISD::UMAX:               return visitIMINMAX(N);
1386   case ISD::AND:                return visitAND(N);
1387   case ISD::OR:                 return visitOR(N);
1388   case ISD::XOR:                return visitXOR(N);
1389   case ISD::SHL:                return visitSHL(N);
1390   case ISD::SRA:                return visitSRA(N);
1391   case ISD::SRL:                return visitSRL(N);
1392   case ISD::ROTR:
1393   case ISD::ROTL:               return visitRotate(N);
1394   case ISD::BSWAP:              return visitBSWAP(N);
1395   case ISD::CTLZ:               return visitCTLZ(N);
1396   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1397   case ISD::CTTZ:               return visitCTTZ(N);
1398   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1399   case ISD::CTPOP:              return visitCTPOP(N);
1400   case ISD::SELECT:             return visitSELECT(N);
1401   case ISD::VSELECT:            return visitVSELECT(N);
1402   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1403   case ISD::SETCC:              return visitSETCC(N);
1404   case ISD::SETCCE:             return visitSETCCE(N);
1405   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1406   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1407   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1408   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1409   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1410   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1411   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1412   case ISD::BITCAST:            return visitBITCAST(N);
1413   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1414   case ISD::FADD:               return visitFADD(N);
1415   case ISD::FSUB:               return visitFSUB(N);
1416   case ISD::FMUL:               return visitFMUL(N);
1417   case ISD::FMA:                return visitFMA(N);
1418   case ISD::FDIV:               return visitFDIV(N);
1419   case ISD::FREM:               return visitFREM(N);
1420   case ISD::FSQRT:              return visitFSQRT(N);
1421   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1422   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1423   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1424   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1425   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1426   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1427   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1428   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1429   case ISD::FNEG:               return visitFNEG(N);
1430   case ISD::FABS:               return visitFABS(N);
1431   case ISD::FFLOOR:             return visitFFLOOR(N);
1432   case ISD::FMINNUM:            return visitFMINNUM(N);
1433   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1434   case ISD::FCEIL:              return visitFCEIL(N);
1435   case ISD::FTRUNC:             return visitFTRUNC(N);
1436   case ISD::BRCOND:             return visitBRCOND(N);
1437   case ISD::BR_CC:              return visitBR_CC(N);
1438   case ISD::LOAD:               return visitLOAD(N);
1439   case ISD::STORE:              return visitSTORE(N);
1440   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1441   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1442   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1443   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1444   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1445   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1446   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1447   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1448   case ISD::MGATHER:            return visitMGATHER(N);
1449   case ISD::MLOAD:              return visitMLOAD(N);
1450   case ISD::MSCATTER:           return visitMSCATTER(N);
1451   case ISD::MSTORE:             return visitMSTORE(N);
1452   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1453   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1454   }
1455   return SDValue();
1456 }
1457 
1458 SDValue DAGCombiner::combine(SDNode *N) {
1459   SDValue RV = visit(N);
1460 
1461   // If nothing happened, try a target-specific DAG combine.
1462   if (!RV.getNode()) {
1463     assert(N->getOpcode() != ISD::DELETED_NODE &&
1464            "Node was deleted but visit returned NULL!");
1465 
1466     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1467         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1468 
1469       // Expose the DAG combiner to the target combiner impls.
1470       TargetLowering::DAGCombinerInfo
1471         DagCombineInfo(DAG, Level, false, this);
1472 
1473       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1474     }
1475   }
1476 
1477   // If nothing happened still, try promoting the operation.
1478   if (!RV.getNode()) {
1479     switch (N->getOpcode()) {
1480     default: break;
1481     case ISD::ADD:
1482     case ISD::SUB:
1483     case ISD::MUL:
1484     case ISD::AND:
1485     case ISD::OR:
1486     case ISD::XOR:
1487       RV = PromoteIntBinOp(SDValue(N, 0));
1488       break;
1489     case ISD::SHL:
1490     case ISD::SRA:
1491     case ISD::SRL:
1492       RV = PromoteIntShiftOp(SDValue(N, 0));
1493       break;
1494     case ISD::SIGN_EXTEND:
1495     case ISD::ZERO_EXTEND:
1496     case ISD::ANY_EXTEND:
1497       RV = PromoteExtend(SDValue(N, 0));
1498       break;
1499     case ISD::LOAD:
1500       if (PromoteLoad(SDValue(N, 0)))
1501         RV = SDValue(N, 0);
1502       break;
1503     }
1504   }
1505 
1506   // If N is a commutative binary node, try commuting it to enable more
1507   // sdisel CSE.
1508   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1509       N->getNumValues() == 1) {
1510     SDValue N0 = N->getOperand(0);
1511     SDValue N1 = N->getOperand(1);
1512 
1513     // Constant operands are canonicalized to RHS.
1514     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1515       SDValue Ops[] = {N1, N0};
1516       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1517                                             N->getFlags());
1518       if (CSENode)
1519         return SDValue(CSENode, 0);
1520     }
1521   }
1522 
1523   return RV;
1524 }
1525 
1526 /// Given a node, return its input chain if it has one, otherwise return a null
1527 /// sd operand.
1528 static SDValue getInputChainForNode(SDNode *N) {
1529   if (unsigned NumOps = N->getNumOperands()) {
1530     if (N->getOperand(0).getValueType() == MVT::Other)
1531       return N->getOperand(0);
1532     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1533       return N->getOperand(NumOps-1);
1534     for (unsigned i = 1; i < NumOps-1; ++i)
1535       if (N->getOperand(i).getValueType() == MVT::Other)
1536         return N->getOperand(i);
1537   }
1538   return SDValue();
1539 }
1540 
1541 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1542   // If N has two operands, where one has an input chain equal to the other,
1543   // the 'other' chain is redundant.
1544   if (N->getNumOperands() == 2) {
1545     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1546       return N->getOperand(0);
1547     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1548       return N->getOperand(1);
1549   }
1550 
1551   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1552   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1553   SmallPtrSet<SDNode*, 16> SeenOps;
1554   bool Changed = false;             // If we should replace this token factor.
1555 
1556   // Start out with this token factor.
1557   TFs.push_back(N);
1558 
1559   // Iterate through token factors.  The TFs grows when new token factors are
1560   // encountered.
1561   for (unsigned i = 0; i < TFs.size(); ++i) {
1562     SDNode *TF = TFs[i];
1563 
1564     // Check each of the operands.
1565     for (const SDValue &Op : TF->op_values()) {
1566 
1567       switch (Op.getOpcode()) {
1568       case ISD::EntryToken:
1569         // Entry tokens don't need to be added to the list. They are
1570         // redundant.
1571         Changed = true;
1572         break;
1573 
1574       case ISD::TokenFactor:
1575         if (Op.hasOneUse() &&
1576             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1577           // Queue up for processing.
1578           TFs.push_back(Op.getNode());
1579           // Clean up in case the token factor is removed.
1580           AddToWorklist(Op.getNode());
1581           Changed = true;
1582           break;
1583         }
1584         // Fall thru
1585 
1586       default:
1587         // Only add if it isn't already in the list.
1588         if (SeenOps.insert(Op.getNode()).second)
1589           Ops.push_back(Op);
1590         else
1591           Changed = true;
1592         break;
1593       }
1594     }
1595   }
1596 
1597   SDValue Result;
1598 
1599   // If we've changed things around then replace token factor.
1600   if (Changed) {
1601     if (Ops.empty()) {
1602       // The entry token is the only possible outcome.
1603       Result = DAG.getEntryNode();
1604     } else {
1605       // New and improved token factor.
1606       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1607     }
1608 
1609     // Add users to worklist if AA is enabled, since it may introduce
1610     // a lot of new chained token factors while removing memory deps.
1611     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1612       : DAG.getSubtarget().useAA();
1613     return CombineTo(N, Result, UseAA /*add to worklist*/);
1614   }
1615 
1616   return Result;
1617 }
1618 
1619 /// MERGE_VALUES can always be eliminated.
1620 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1621   WorklistRemover DeadNodes(*this);
1622   // Replacing results may cause a different MERGE_VALUES to suddenly
1623   // be CSE'd with N, and carry its uses with it. Iterate until no
1624   // uses remain, to ensure that the node can be safely deleted.
1625   // First add the users of this node to the work list so that they
1626   // can be tried again once they have new operands.
1627   AddUsersToWorklist(N);
1628   do {
1629     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1630       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1631   } while (!N->use_empty());
1632   deleteAndRecombine(N);
1633   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1634 }
1635 
1636 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1637 /// ConstantSDNode pointer else nullptr.
1638 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1639   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1640   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1641 }
1642 
1643 SDValue DAGCombiner::visitADD(SDNode *N) {
1644   SDValue N0 = N->getOperand(0);
1645   SDValue N1 = N->getOperand(1);
1646   EVT VT = N0.getValueType();
1647 
1648   // fold vector ops
1649   if (VT.isVector()) {
1650     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1651       return FoldedVOp;
1652 
1653     // fold (add x, 0) -> x, vector edition
1654     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1655       return N0;
1656     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1657       return N1;
1658   }
1659 
1660   // fold (add x, undef) -> undef
1661   if (N0.isUndef())
1662     return N0;
1663   if (N1.isUndef())
1664     return N1;
1665   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1666     // canonicalize constant to RHS
1667     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1668       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1669     // fold (add c1, c2) -> c1+c2
1670     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1671                                       N0.getNode(), N1.getNode());
1672   }
1673   // fold (add x, 0) -> x
1674   if (isNullConstant(N1))
1675     return N0;
1676   // fold ((c1-A)+c2) -> (c1+c2)-A
1677   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1678     if (N0.getOpcode() == ISD::SUB)
1679       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1680         SDLoc DL(N);
1681         return DAG.getNode(ISD::SUB, DL, VT,
1682                            DAG.getConstant(N1C->getAPIntValue()+
1683                                            N0C->getAPIntValue(), DL, VT),
1684                            N0.getOperand(1));
1685       }
1686   }
1687   // reassociate add
1688   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1689     return RADD;
1690   // fold ((0-A) + B) -> B-A
1691   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693   // fold (A + (0-B)) -> A-B
1694   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696   // fold (A+(B-A)) -> B
1697   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698     return N1.getOperand(0);
1699   // fold ((B-A)+A) -> B
1700   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701     return N0.getOperand(0);
1702   // fold (A+(B-(A+C))) to (B-C)
1703   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704       N0 == N1.getOperand(1).getOperand(0))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706                        N1.getOperand(1).getOperand(1));
1707   // fold (A+(B-(C+A))) to (B-C)
1708   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709       N0 == N1.getOperand(1).getOperand(1))
1710     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711                        N1.getOperand(1).getOperand(0));
1712   // fold (A+((B-A)+or-C)) to (B+or-C)
1713   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714       N1.getOperand(0).getOpcode() == ISD::SUB &&
1715       N0 == N1.getOperand(0).getOperand(1))
1716     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1718 
1719   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721     SDValue N00 = N0.getOperand(0);
1722     SDValue N01 = N0.getOperand(1);
1723     SDValue N10 = N1.getOperand(0);
1724     SDValue N11 = N1.getOperand(1);
1725 
1726     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1730   }
1731 
1732   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733     return SDValue(N, 0);
1734 
1735   // fold (a+b) -> (a|b) iff a and b share no bits.
1736   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) &&
1737       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1738     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1739 
1740   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1741   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1742       isNullConstant(N1.getOperand(0).getOperand(0)))
1743     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1744                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745                                    N1.getOperand(0).getOperand(1),
1746                                    N1.getOperand(1)));
1747   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1748       isNullConstant(N0.getOperand(0).getOperand(0)))
1749     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1750                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751                                    N0.getOperand(0).getOperand(1),
1752                                    N0.getOperand(1)));
1753 
1754   if (N1.getOpcode() == ISD::AND) {
1755     SDValue AndOp0 = N1.getOperand(0);
1756     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1757     unsigned DestBits = VT.getScalarType().getSizeInBits();
1758 
1759     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1760     // and similar xforms where the inner op is either ~0 or 0.
1761     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1762       SDLoc DL(N);
1763       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1764     }
1765   }
1766 
1767   // add (sext i1), X -> sub X, (zext i1)
1768   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1769       N0.getOperand(0).getValueType() == MVT::i1 &&
1770       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1771     SDLoc DL(N);
1772     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1773     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1774   }
1775 
1776   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1777   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1778     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1779     if (TN->getVT() == MVT::i1) {
1780       SDLoc DL(N);
1781       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1782                                  DAG.getConstant(1, DL, VT));
1783       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1784     }
1785   }
1786 
1787   return SDValue();
1788 }
1789 
1790 SDValue DAGCombiner::visitADDC(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   EVT VT = N0.getValueType();
1794 
1795   // If the flag result is dead, turn this into an ADD.
1796   if (!N->hasAnyUseOfValue(1))
1797     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1798                      DAG.getNode(ISD::CARRY_FALSE,
1799                                  SDLoc(N), MVT::Glue));
1800 
1801   // canonicalize constant to RHS.
1802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804   if (N0C && !N1C)
1805     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1806 
1807   // fold (addc x, 0) -> x + no carry out
1808   if (isNullConstant(N1))
1809     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1810                                         SDLoc(N), MVT::Glue));
1811 
1812   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1813   APInt LHSZero, LHSOne;
1814   APInt RHSZero, RHSOne;
1815   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1816 
1817   if (LHSZero.getBoolValue()) {
1818     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1819 
1820     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1821     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1822     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1823       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1824                        DAG.getNode(ISD::CARRY_FALSE,
1825                                    SDLoc(N), MVT::Glue));
1826   }
1827 
1828   return SDValue();
1829 }
1830 
1831 SDValue DAGCombiner::visitADDE(SDNode *N) {
1832   SDValue N0 = N->getOperand(0);
1833   SDValue N1 = N->getOperand(1);
1834   SDValue CarryIn = N->getOperand(2);
1835 
1836   // canonicalize constant to RHS
1837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839   if (N0C && !N1C)
1840     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1841                        N1, N0, CarryIn);
1842 
1843   // fold (adde x, y, false) -> (addc x, y)
1844   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1845     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1846 
1847   return SDValue();
1848 }
1849 
1850 // Since it may not be valid to emit a fold to zero for vector initializers
1851 // check if we can before folding.
1852 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1853                              SelectionDAG &DAG,
1854                              bool LegalOperations, bool LegalTypes) {
1855   if (!VT.isVector())
1856     return DAG.getConstant(0, DL, VT);
1857   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1858     return DAG.getConstant(0, DL, VT);
1859   return SDValue();
1860 }
1861 
1862 SDValue DAGCombiner::visitSUB(SDNode *N) {
1863   SDValue N0 = N->getOperand(0);
1864   SDValue N1 = N->getOperand(1);
1865   EVT VT = N0.getValueType();
1866 
1867   // fold vector ops
1868   if (VT.isVector()) {
1869     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1870       return FoldedVOp;
1871 
1872     // fold (sub x, 0) -> x, vector edition
1873     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1874       return N0;
1875   }
1876 
1877   // fold (sub x, x) -> 0
1878   // FIXME: Refactor this and xor and other similar operations together.
1879   if (N0 == N1)
1880     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1881   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1882       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1883     // fold (sub c1, c2) -> c1-c2
1884     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT,
1885                                       N0.getNode(), N1.getNode());
1886   }
1887   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1888   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1889   // fold (sub x, c) -> (add x, -c)
1890   if (N1C) {
1891     SDLoc DL(N);
1892     return DAG.getNode(ISD::ADD, DL, VT, N0,
1893                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1894   }
1895   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1896   if (isAllOnesConstant(N0))
1897     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1898   // fold A-(A-B) -> B
1899   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1900     return N1.getOperand(1);
1901   // fold (A+B)-A -> B
1902   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1903     return N0.getOperand(1);
1904   // fold (A+B)-B -> A
1905   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1906     return N0.getOperand(0);
1907   // fold C2-(A+C1) -> (C2-C1)-A
1908   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1909     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1910   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1911     SDLoc DL(N);
1912     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1913                                    DL, VT);
1914     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1915                        N1.getOperand(0));
1916   }
1917   // fold ((A+(B+or-C))-B) -> A+or-C
1918   if (N0.getOpcode() == ISD::ADD &&
1919       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1920        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1921       N0.getOperand(1).getOperand(0) == N1)
1922     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1923                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1924   // fold ((A+(C+B))-B) -> A+C
1925   if (N0.getOpcode() == ISD::ADD &&
1926       N0.getOperand(1).getOpcode() == ISD::ADD &&
1927       N0.getOperand(1).getOperand(1) == N1)
1928     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1929                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1930   // fold ((A-(B-C))-C) -> A-B
1931   if (N0.getOpcode() == ISD::SUB &&
1932       N0.getOperand(1).getOpcode() == ISD::SUB &&
1933       N0.getOperand(1).getOperand(1) == N1)
1934     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1935                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1936 
1937   // If either operand of a sub is undef, the result is undef
1938   if (N0.isUndef())
1939     return N0;
1940   if (N1.isUndef())
1941     return N1;
1942 
1943   // If the relocation model supports it, consider symbol offsets.
1944   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1945     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1946       // fold (sub Sym, c) -> Sym-c
1947       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1948         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1949                                     GA->getOffset() -
1950                                       (uint64_t)N1C->getSExtValue());
1951       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1952       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1953         if (GA->getGlobal() == GB->getGlobal())
1954           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1955                                  SDLoc(N), VT);
1956     }
1957 
1958   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1959   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1960     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1961     if (TN->getVT() == MVT::i1) {
1962       SDLoc DL(N);
1963       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1964                                  DAG.getConstant(1, DL, VT));
1965       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1966     }
1967   }
1968 
1969   return SDValue();
1970 }
1971 
1972 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   EVT VT = N0.getValueType();
1976   SDLoc DL(N);
1977 
1978   // If the flag result is dead, turn this into an SUB.
1979   if (!N->hasAnyUseOfValue(1))
1980     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1981                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1982 
1983   // fold (subc x, x) -> 0 + no borrow
1984   if (N0 == N1)
1985     return CombineTo(N, DAG.getConstant(0, DL, VT),
1986                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1987 
1988   // fold (subc x, 0) -> x + no borrow
1989   if (isNullConstant(N1))
1990     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1991 
1992   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1993   if (isAllOnesConstant(N0))
1994     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1995                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1996 
1997   return SDValue();
1998 }
1999 
2000 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2001   SDValue N0 = N->getOperand(0);
2002   SDValue N1 = N->getOperand(1);
2003   SDValue CarryIn = N->getOperand(2);
2004 
2005   // fold (sube x, y, false) -> (subc x, y)
2006   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2007     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2008 
2009   return SDValue();
2010 }
2011 
2012 SDValue DAGCombiner::visitMUL(SDNode *N) {
2013   SDValue N0 = N->getOperand(0);
2014   SDValue N1 = N->getOperand(1);
2015   EVT VT = N0.getValueType();
2016 
2017   // fold (mul x, undef) -> 0
2018   if (N0.isUndef() || N1.isUndef())
2019     return DAG.getConstant(0, SDLoc(N), VT);
2020 
2021   bool N0IsConst = false;
2022   bool N1IsConst = false;
2023   bool N1IsOpaqueConst = false;
2024   bool N0IsOpaqueConst = false;
2025   APInt ConstValue0, ConstValue1;
2026   // fold vector ops
2027   if (VT.isVector()) {
2028     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2029       return FoldedVOp;
2030 
2031     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2032     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2033   } else {
2034     N0IsConst = isa<ConstantSDNode>(N0);
2035     if (N0IsConst) {
2036       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2037       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2038     }
2039     N1IsConst = isa<ConstantSDNode>(N1);
2040     if (N1IsConst) {
2041       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2042       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2043     }
2044   }
2045 
2046   // fold (mul c1, c2) -> c1*c2
2047   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2048     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2049                                       N0.getNode(), N1.getNode());
2050 
2051   // canonicalize constant to RHS (vector doesn't have to splat)
2052   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2053      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2054     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2055   // fold (mul x, 0) -> 0
2056   if (N1IsConst && ConstValue1 == 0)
2057     return N1;
2058   // We require a splat of the entire scalar bit width for non-contiguous
2059   // bit patterns.
2060   bool IsFullSplat =
2061     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2062   // fold (mul x, 1) -> x
2063   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2064     return N0;
2065   // fold (mul x, -1) -> 0-x
2066   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2067     SDLoc DL(N);
2068     return DAG.getNode(ISD::SUB, DL, VT,
2069                        DAG.getConstant(0, DL, VT), N0);
2070   }
2071   // fold (mul x, (1 << c)) -> x << c
2072   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2073       IsFullSplat) {
2074     SDLoc DL(N);
2075     return DAG.getNode(ISD::SHL, DL, VT, N0,
2076                        DAG.getConstant(ConstValue1.logBase2(), DL,
2077                                        getShiftAmountTy(N0.getValueType())));
2078   }
2079   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2080   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2081       IsFullSplat) {
2082     unsigned Log2Val = (-ConstValue1).logBase2();
2083     SDLoc DL(N);
2084     // FIXME: If the input is something that is easily negated (e.g. a
2085     // single-use add), we should put the negate there.
2086     return DAG.getNode(ISD::SUB, DL, VT,
2087                        DAG.getConstant(0, DL, VT),
2088                        DAG.getNode(ISD::SHL, DL, VT, N0,
2089                             DAG.getConstant(Log2Val, DL,
2090                                       getShiftAmountTy(N0.getValueType()))));
2091   }
2092 
2093   APInt Val;
2094   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2095   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2096       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2097                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2098     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2099                              N1, N0.getOperand(1));
2100     AddToWorklist(C3.getNode());
2101     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2102                        N0.getOperand(0), C3);
2103   }
2104 
2105   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2106   // use.
2107   {
2108     SDValue Sh(nullptr,0), Y(nullptr,0);
2109     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2110     if (N0.getOpcode() == ISD::SHL &&
2111         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2112                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2113         N0.getNode()->hasOneUse()) {
2114       Sh = N0; Y = N1;
2115     } else if (N1.getOpcode() == ISD::SHL &&
2116                isa<ConstantSDNode>(N1.getOperand(1)) &&
2117                N1.getNode()->hasOneUse()) {
2118       Sh = N1; Y = N0;
2119     }
2120 
2121     if (Sh.getNode()) {
2122       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2123                                 Sh.getOperand(0), Y);
2124       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2125                          Mul, Sh.getOperand(1));
2126     }
2127   }
2128 
2129   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2130   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2131       N0.getOpcode() == ISD::ADD &&
2132       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2133       isMulAddWithConstProfitable(N, N0, N1))
2134       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2135                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2136                                      N0.getOperand(0), N1),
2137                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2138                                      N0.getOperand(1), N1));
2139 
2140   // reassociate mul
2141   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2142     return RMUL;
2143 
2144   return SDValue();
2145 }
2146 
2147 /// Return true if divmod libcall is available.
2148 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2149                                      const TargetLowering &TLI) {
2150   RTLIB::Libcall LC;
2151   EVT NodeType = Node->getValueType(0);
2152   if (!NodeType.isSimple())
2153     return false;
2154   switch (NodeType.getSimpleVT().SimpleTy) {
2155   default: return false; // No libcall for vector types.
2156   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2157   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2158   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2159   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2160   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2161   }
2162 
2163   return TLI.getLibcallName(LC) != nullptr;
2164 }
2165 
2166 /// Issue divrem if both quotient and remainder are needed.
2167 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2168   if (Node->use_empty())
2169     return SDValue(); // This is a dead node, leave it alone.
2170 
2171   unsigned Opcode = Node->getOpcode();
2172   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2173   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2174 
2175   // DivMod lib calls can still work on non-legal types if using lib-calls.
2176   EVT VT = Node->getValueType(0);
2177   if (VT.isVector() || !VT.isInteger())
2178     return SDValue();
2179 
2180   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2181     return SDValue();
2182 
2183   // If DIVREM is going to get expanded into a libcall,
2184   // but there is no libcall available, then don't combine.
2185   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2186       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2187     return SDValue();
2188 
2189   // If div is legal, it's better to do the normal expansion
2190   unsigned OtherOpcode = 0;
2191   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2192     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2193     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2194       return SDValue();
2195   } else {
2196     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2197     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2198       return SDValue();
2199   }
2200 
2201   SDValue Op0 = Node->getOperand(0);
2202   SDValue Op1 = Node->getOperand(1);
2203   SDValue combined;
2204   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2205          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2206     SDNode *User = *UI;
2207     if (User == Node || User->use_empty())
2208       continue;
2209     // Convert the other matching node(s), too;
2210     // otherwise, the DIVREM may get target-legalized into something
2211     // target-specific that we won't be able to recognize.
2212     unsigned UserOpc = User->getOpcode();
2213     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2214         User->getOperand(0) == Op0 &&
2215         User->getOperand(1) == Op1) {
2216       if (!combined) {
2217         if (UserOpc == OtherOpcode) {
2218           SDVTList VTs = DAG.getVTList(VT, VT);
2219           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2220         } else if (UserOpc == DivRemOpc) {
2221           combined = SDValue(User, 0);
2222         } else {
2223           assert(UserOpc == Opcode);
2224           continue;
2225         }
2226       }
2227       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2228         CombineTo(User, combined);
2229       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2230         CombineTo(User, combined.getValue(1));
2231     }
2232   }
2233   return combined;
2234 }
2235 
2236 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2237   SDValue N0 = N->getOperand(0);
2238   SDValue N1 = N->getOperand(1);
2239   EVT VT = N->getValueType(0);
2240 
2241   // fold vector ops
2242   if (VT.isVector())
2243     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2244       return FoldedVOp;
2245 
2246   SDLoc DL(N);
2247 
2248   // fold (sdiv c1, c2) -> c1/c2
2249   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2250   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2251   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2252     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2253   // fold (sdiv X, 1) -> X
2254   if (N1C && N1C->isOne())
2255     return N0;
2256   // fold (sdiv X, -1) -> 0-X
2257   if (N1C && N1C->isAllOnesValue())
2258     return DAG.getNode(ISD::SUB, DL, VT,
2259                        DAG.getConstant(0, DL, VT), N0);
2260 
2261   // If we know the sign bits of both operands are zero, strength reduce to a
2262   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2263   if (!VT.isVector()) {
2264     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2265       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2266   }
2267 
2268   // fold (sdiv X, pow2) -> simple ops after legalize
2269   // FIXME: We check for the exact bit here because the generic lowering gives
2270   // better results in that case. The target-specific lowering should learn how
2271   // to handle exact sdivs efficiently.
2272   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2273       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2274       (N1C->getAPIntValue().isPowerOf2() ||
2275        (-N1C->getAPIntValue()).isPowerOf2())) {
2276     // Target-specific implementation of sdiv x, pow2.
2277     if (SDValue Res = BuildSDIVPow2(N))
2278       return Res;
2279 
2280     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2281 
2282     // Splat the sign bit into the register
2283     SDValue SGN =
2284         DAG.getNode(ISD::SRA, DL, VT, N0,
2285                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2286                                     getShiftAmountTy(N0.getValueType())));
2287     AddToWorklist(SGN.getNode());
2288 
2289     // Add (N0 < 0) ? abs2 - 1 : 0;
2290     SDValue SRL =
2291         DAG.getNode(ISD::SRL, DL, VT, SGN,
2292                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2293                                     getShiftAmountTy(SGN.getValueType())));
2294     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2295     AddToWorklist(SRL.getNode());
2296     AddToWorklist(ADD.getNode());    // Divide by pow2
2297     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2298                   DAG.getConstant(lg2, DL,
2299                                   getShiftAmountTy(ADD.getValueType())));
2300 
2301     // If we're dividing by a positive value, we're done.  Otherwise, we must
2302     // negate the result.
2303     if (N1C->getAPIntValue().isNonNegative())
2304       return SRA;
2305 
2306     AddToWorklist(SRA.getNode());
2307     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2308   }
2309 
2310   // If integer divide is expensive and we satisfy the requirements, emit an
2311   // alternate sequence.  Targets may check function attributes for size/speed
2312   // trade-offs.
2313   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2314   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2315     if (SDValue Op = BuildSDIV(N))
2316       return Op;
2317 
2318   // sdiv, srem -> sdivrem
2319   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2320   // Otherwise, we break the simplification logic in visitREM().
2321   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2322     if (SDValue DivRem = useDivRem(N))
2323         return DivRem;
2324 
2325   // undef / X -> 0
2326   if (N0.isUndef())
2327     return DAG.getConstant(0, DL, VT);
2328   // X / undef -> undef
2329   if (N1.isUndef())
2330     return N1;
2331 
2332   return SDValue();
2333 }
2334 
2335 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2336   SDValue N0 = N->getOperand(0);
2337   SDValue N1 = N->getOperand(1);
2338   EVT VT = N->getValueType(0);
2339 
2340   // fold vector ops
2341   if (VT.isVector())
2342     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2343       return FoldedVOp;
2344 
2345   SDLoc DL(N);
2346 
2347   // fold (udiv c1, c2) -> c1/c2
2348   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2349   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2350   if (N0C && N1C)
2351     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2352                                                     N0C, N1C))
2353       return Folded;
2354   // fold (udiv x, (1 << c)) -> x >>u c
2355   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2356     return DAG.getNode(ISD::SRL, DL, VT, N0,
2357                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2358                                        getShiftAmountTy(N0.getValueType())));
2359 
2360   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2361   if (N1.getOpcode() == ISD::SHL) {
2362     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2363       if (SHC->getAPIntValue().isPowerOf2()) {
2364         EVT ADDVT = N1.getOperand(1).getValueType();
2365         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2366                                   N1.getOperand(1),
2367                                   DAG.getConstant(SHC->getAPIntValue()
2368                                                                   .logBase2(),
2369                                                   DL, ADDVT));
2370         AddToWorklist(Add.getNode());
2371         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2372       }
2373     }
2374   }
2375 
2376   // fold (udiv x, c) -> alternate
2377   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2378   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2379     if (SDValue Op = BuildUDIV(N))
2380       return Op;
2381 
2382   // sdiv, srem -> sdivrem
2383   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2384   // Otherwise, we break the simplification logic in visitREM().
2385   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2386     if (SDValue DivRem = useDivRem(N))
2387         return DivRem;
2388 
2389   // undef / X -> 0
2390   if (N0.isUndef())
2391     return DAG.getConstant(0, DL, VT);
2392   // X / undef -> undef
2393   if (N1.isUndef())
2394     return N1;
2395 
2396   return SDValue();
2397 }
2398 
2399 // handles ISD::SREM and ISD::UREM
2400 SDValue DAGCombiner::visitREM(SDNode *N) {
2401   unsigned Opcode = N->getOpcode();
2402   SDValue N0 = N->getOperand(0);
2403   SDValue N1 = N->getOperand(1);
2404   EVT VT = N->getValueType(0);
2405   bool isSigned = (Opcode == ISD::SREM);
2406   SDLoc DL(N);
2407 
2408   // fold (rem c1, c2) -> c1%c2
2409   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2410   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2411   if (N0C && N1C)
2412     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2413       return Folded;
2414 
2415   if (isSigned) {
2416     // If we know the sign bits of both operands are zero, strength reduce to a
2417     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2418     if (!VT.isVector()) {
2419       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2420         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2421     }
2422   } else {
2423     // fold (urem x, pow2) -> (and x, pow2-1)
2424     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2425         N1C->getAPIntValue().isPowerOf2()) {
2426       return DAG.getNode(ISD::AND, DL, VT, N0,
2427                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2428     }
2429     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2430     if (N1.getOpcode() == ISD::SHL) {
2431       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2432         if (SHC->getAPIntValue().isPowerOf2()) {
2433           SDValue Add =
2434             DAG.getNode(ISD::ADD, DL, VT, N1,
2435                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2436                                  VT));
2437           AddToWorklist(Add.getNode());
2438           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2439         }
2440       }
2441     }
2442   }
2443 
2444   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2445 
2446   // If X/C can be simplified by the division-by-constant logic, lower
2447   // X%C to the equivalent of X-X/C*C.
2448   // To avoid mangling nodes, this simplification requires that the combine()
2449   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2450   // against this by skipping the simplification if isIntDivCheap().  When
2451   // div is not cheap, combine will not return a DIVREM.  Regardless,
2452   // checking cheapness here makes sense since the simplification results in
2453   // fatter code.
2454   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2455     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2456     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2457     AddToWorklist(Div.getNode());
2458     SDValue OptimizedDiv = combine(Div.getNode());
2459     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2460       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2461              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2462       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2463       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2464       AddToWorklist(Mul.getNode());
2465       return Sub;
2466     }
2467   }
2468 
2469   // sdiv, srem -> sdivrem
2470   if (SDValue DivRem = useDivRem(N))
2471     return DivRem.getValue(1);
2472 
2473   // undef % X -> 0
2474   if (N0.isUndef())
2475     return DAG.getConstant(0, DL, VT);
2476   // X % undef -> undef
2477   if (N1.isUndef())
2478     return N1;
2479 
2480   return SDValue();
2481 }
2482 
2483 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2484   SDValue N0 = N->getOperand(0);
2485   SDValue N1 = N->getOperand(1);
2486   EVT VT = N->getValueType(0);
2487   SDLoc DL(N);
2488 
2489   // fold (mulhs x, 0) -> 0
2490   if (isNullConstant(N1))
2491     return N1;
2492   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2493   if (isOneConstant(N1)) {
2494     SDLoc DL(N);
2495     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2496                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2497                                        DL,
2498                                        getShiftAmountTy(N0.getValueType())));
2499   }
2500   // fold (mulhs x, undef) -> 0
2501   if (N0.isUndef() || N1.isUndef())
2502     return DAG.getConstant(0, SDLoc(N), VT);
2503 
2504   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2505   // plus a shift.
2506   if (VT.isSimple() && !VT.isVector()) {
2507     MVT Simple = VT.getSimpleVT();
2508     unsigned SimpleSize = Simple.getSizeInBits();
2509     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2510     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2511       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2512       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2513       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2514       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2515             DAG.getConstant(SimpleSize, DL,
2516                             getShiftAmountTy(N1.getValueType())));
2517       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2518     }
2519   }
2520 
2521   return SDValue();
2522 }
2523 
2524 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2525   SDValue N0 = N->getOperand(0);
2526   SDValue N1 = N->getOperand(1);
2527   EVT VT = N->getValueType(0);
2528   SDLoc DL(N);
2529 
2530   // fold (mulhu x, 0) -> 0
2531   if (isNullConstant(N1))
2532     return N1;
2533   // fold (mulhu x, 1) -> 0
2534   if (isOneConstant(N1))
2535     return DAG.getConstant(0, DL, N0.getValueType());
2536   // fold (mulhu x, undef) -> 0
2537   if (N0.isUndef() || N1.isUndef())
2538     return DAG.getConstant(0, DL, VT);
2539 
2540   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2541   // plus a shift.
2542   if (VT.isSimple() && !VT.isVector()) {
2543     MVT Simple = VT.getSimpleVT();
2544     unsigned SimpleSize = Simple.getSizeInBits();
2545     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2546     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2547       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2548       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2549       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2550       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2551             DAG.getConstant(SimpleSize, DL,
2552                             getShiftAmountTy(N1.getValueType())));
2553       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2554     }
2555   }
2556 
2557   return SDValue();
2558 }
2559 
2560 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2561 /// give the opcodes for the two computations that are being performed. Return
2562 /// true if a simplification was made.
2563 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2564                                                 unsigned HiOp) {
2565   // If the high half is not needed, just compute the low half.
2566   bool HiExists = N->hasAnyUseOfValue(1);
2567   if (!HiExists &&
2568       (!LegalOperations ||
2569        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2570     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2571     return CombineTo(N, Res, Res);
2572   }
2573 
2574   // If the low half is not needed, just compute the high half.
2575   bool LoExists = N->hasAnyUseOfValue(0);
2576   if (!LoExists &&
2577       (!LegalOperations ||
2578        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2579     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2580     return CombineTo(N, Res, Res);
2581   }
2582 
2583   // If both halves are used, return as it is.
2584   if (LoExists && HiExists)
2585     return SDValue();
2586 
2587   // If the two computed results can be simplified separately, separate them.
2588   if (LoExists) {
2589     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2590     AddToWorklist(Lo.getNode());
2591     SDValue LoOpt = combine(Lo.getNode());
2592     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2593         (!LegalOperations ||
2594          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2595       return CombineTo(N, LoOpt, LoOpt);
2596   }
2597 
2598   if (HiExists) {
2599     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2600     AddToWorklist(Hi.getNode());
2601     SDValue HiOpt = combine(Hi.getNode());
2602     if (HiOpt.getNode() && HiOpt != Hi &&
2603         (!LegalOperations ||
2604          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2605       return CombineTo(N, HiOpt, HiOpt);
2606   }
2607 
2608   return SDValue();
2609 }
2610 
2611 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2612   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2613     return Res;
2614 
2615   EVT VT = N->getValueType(0);
2616   SDLoc DL(N);
2617 
2618   // If the type is twice as wide is legal, transform the mulhu to a wider
2619   // multiply plus a shift.
2620   if (VT.isSimple() && !VT.isVector()) {
2621     MVT Simple = VT.getSimpleVT();
2622     unsigned SimpleSize = Simple.getSizeInBits();
2623     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2624     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2625       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2626       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2627       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2628       // Compute the high part as N1.
2629       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2630             DAG.getConstant(SimpleSize, DL,
2631                             getShiftAmountTy(Lo.getValueType())));
2632       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2633       // Compute the low part as N0.
2634       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2635       return CombineTo(N, Lo, Hi);
2636     }
2637   }
2638 
2639   return SDValue();
2640 }
2641 
2642 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2643   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2644     return Res;
2645 
2646   EVT VT = N->getValueType(0);
2647   SDLoc DL(N);
2648 
2649   // If the type is twice as wide is legal, transform the mulhu to a wider
2650   // multiply plus a shift.
2651   if (VT.isSimple() && !VT.isVector()) {
2652     MVT Simple = VT.getSimpleVT();
2653     unsigned SimpleSize = Simple.getSizeInBits();
2654     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2655     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2656       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2657       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2658       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2659       // Compute the high part as N1.
2660       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2661             DAG.getConstant(SimpleSize, DL,
2662                             getShiftAmountTy(Lo.getValueType())));
2663       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2664       // Compute the low part as N0.
2665       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2666       return CombineTo(N, Lo, Hi);
2667     }
2668   }
2669 
2670   return SDValue();
2671 }
2672 
2673 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2674   // (smulo x, 2) -> (saddo x, x)
2675   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2676     if (C2->getAPIntValue() == 2)
2677       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2678                          N->getOperand(0), N->getOperand(0));
2679 
2680   return SDValue();
2681 }
2682 
2683 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2684   // (umulo x, 2) -> (uaddo x, x)
2685   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2686     if (C2->getAPIntValue() == 2)
2687       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2688                          N->getOperand(0), N->getOperand(0));
2689 
2690   return SDValue();
2691 }
2692 
2693 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2694   SDValue N0 = N->getOperand(0);
2695   SDValue N1 = N->getOperand(1);
2696   EVT VT = N0.getValueType();
2697 
2698   // fold vector ops
2699   if (VT.isVector())
2700     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2701       return FoldedVOp;
2702 
2703   // fold (add c1, c2) -> c1+c2
2704   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2705   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2706   if (N0C && N1C)
2707     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2708 
2709   // canonicalize constant to RHS
2710   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2711      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2712     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2713 
2714   return SDValue();
2715 }
2716 
2717 /// If this is a binary operator with two operands of the same opcode, try to
2718 /// simplify it.
2719 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2720   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2721   EVT VT = N0.getValueType();
2722   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2723 
2724   // Bail early if none of these transforms apply.
2725   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2726 
2727   // For each of OP in AND/OR/XOR:
2728   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2729   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2730   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2731   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2732   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2733   //
2734   // do not sink logical op inside of a vector extend, since it may combine
2735   // into a vsetcc.
2736   EVT Op0VT = N0.getOperand(0).getValueType();
2737   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2738        N0.getOpcode() == ISD::SIGN_EXTEND ||
2739        N0.getOpcode() == ISD::BSWAP ||
2740        // Avoid infinite looping with PromoteIntBinOp.
2741        (N0.getOpcode() == ISD::ANY_EXTEND &&
2742         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2743        (N0.getOpcode() == ISD::TRUNCATE &&
2744         (!TLI.isZExtFree(VT, Op0VT) ||
2745          !TLI.isTruncateFree(Op0VT, VT)) &&
2746         TLI.isTypeLegal(Op0VT))) &&
2747       !VT.isVector() &&
2748       Op0VT == N1.getOperand(0).getValueType() &&
2749       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2750     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2751                                  N0.getOperand(0).getValueType(),
2752                                  N0.getOperand(0), N1.getOperand(0));
2753     AddToWorklist(ORNode.getNode());
2754     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2755   }
2756 
2757   // For each of OP in SHL/SRL/SRA/AND...
2758   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2759   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2760   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2761   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2762        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2763       N0.getOperand(1) == N1.getOperand(1)) {
2764     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2765                                  N0.getOperand(0).getValueType(),
2766                                  N0.getOperand(0), N1.getOperand(0));
2767     AddToWorklist(ORNode.getNode());
2768     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2769                        ORNode, N0.getOperand(1));
2770   }
2771 
2772   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2773   // Only perform this optimization up until type legalization, before
2774   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2775   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2776   // we don't want to undo this promotion.
2777   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2778   // on scalars.
2779   if ((N0.getOpcode() == ISD::BITCAST ||
2780        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2781        Level <= AfterLegalizeTypes) {
2782     SDValue In0 = N0.getOperand(0);
2783     SDValue In1 = N1.getOperand(0);
2784     EVT In0Ty = In0.getValueType();
2785     EVT In1Ty = In1.getValueType();
2786     SDLoc DL(N);
2787     // If both incoming values are integers, and the original types are the
2788     // same.
2789     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2790       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2791       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2792       AddToWorklist(Op.getNode());
2793       return BC;
2794     }
2795   }
2796 
2797   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2798   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2799   // If both shuffles use the same mask, and both shuffle within a single
2800   // vector, then it is worthwhile to move the swizzle after the operation.
2801   // The type-legalizer generates this pattern when loading illegal
2802   // vector types from memory. In many cases this allows additional shuffle
2803   // optimizations.
2804   // There are other cases where moving the shuffle after the xor/and/or
2805   // is profitable even if shuffles don't perform a swizzle.
2806   // If both shuffles use the same mask, and both shuffles have the same first
2807   // or second operand, then it might still be profitable to move the shuffle
2808   // after the xor/and/or operation.
2809   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2810     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2811     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2812 
2813     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2814            "Inputs to shuffles are not the same type");
2815 
2816     // Check that both shuffles use the same mask. The masks are known to be of
2817     // the same length because the result vector type is the same.
2818     // Check also that shuffles have only one use to avoid introducing extra
2819     // instructions.
2820     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2821         SVN0->getMask().equals(SVN1->getMask())) {
2822       SDValue ShOp = N0->getOperand(1);
2823 
2824       // Don't try to fold this node if it requires introducing a
2825       // build vector of all zeros that might be illegal at this stage.
2826       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2827         if (!LegalTypes)
2828           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2829         else
2830           ShOp = SDValue();
2831       }
2832 
2833       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2834       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2835       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2836       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2837         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2838                                       N0->getOperand(0), N1->getOperand(0));
2839         AddToWorklist(NewNode.getNode());
2840         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2841                                     &SVN0->getMask()[0]);
2842       }
2843 
2844       // Don't try to fold this node if it requires introducing a
2845       // build vector of all zeros that might be illegal at this stage.
2846       ShOp = N0->getOperand(0);
2847       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2848         if (!LegalTypes)
2849           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2850         else
2851           ShOp = SDValue();
2852       }
2853 
2854       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2855       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2856       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2857       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2858         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2859                                       N0->getOperand(1), N1->getOperand(1));
2860         AddToWorklist(NewNode.getNode());
2861         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2862                                     &SVN0->getMask()[0]);
2863       }
2864     }
2865   }
2866 
2867   return SDValue();
2868 }
2869 
2870 /// This contains all DAGCombine rules which reduce two values combined by
2871 /// an And operation to a single value. This makes them reusable in the context
2872 /// of visitSELECT(). Rules involving constants are not included as
2873 /// visitSELECT() already handles those cases.
2874 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2875                                   SDNode *LocReference) {
2876   EVT VT = N1.getValueType();
2877 
2878   // fold (and x, undef) -> 0
2879   if (N0.isUndef() || N1.isUndef())
2880     return DAG.getConstant(0, SDLoc(LocReference), VT);
2881   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2882   SDValue LL, LR, RL, RR, CC0, CC1;
2883   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2884     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2885     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2886 
2887     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2888         LL.getValueType().isInteger()) {
2889       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2890       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2891         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2892                                      LR.getValueType(), LL, RL);
2893         AddToWorklist(ORNode.getNode());
2894         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2895       }
2896       if (isAllOnesConstant(LR)) {
2897         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2898         if (Op1 == ISD::SETEQ) {
2899           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2900                                         LR.getValueType(), LL, RL);
2901           AddToWorklist(ANDNode.getNode());
2902           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2903         }
2904         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2905         if (Op1 == ISD::SETGT) {
2906           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2907                                        LR.getValueType(), LL, RL);
2908           AddToWorklist(ORNode.getNode());
2909           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2910         }
2911       }
2912     }
2913     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2914     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2915         Op0 == Op1 && LL.getValueType().isInteger() &&
2916       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2917                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2918       SDLoc DL(N0);
2919       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2920                                     LL, DAG.getConstant(1, DL,
2921                                                         LL.getValueType()));
2922       AddToWorklist(ADDNode.getNode());
2923       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2924                           DAG.getConstant(2, DL, LL.getValueType()),
2925                           ISD::SETUGE);
2926     }
2927     // canonicalize equivalent to ll == rl
2928     if (LL == RR && LR == RL) {
2929       Op1 = ISD::getSetCCSwappedOperands(Op1);
2930       std::swap(RL, RR);
2931     }
2932     if (LL == RL && LR == RR) {
2933       bool isInteger = LL.getValueType().isInteger();
2934       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2935       if (Result != ISD::SETCC_INVALID &&
2936           (!LegalOperations ||
2937            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2938             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2939         EVT CCVT = getSetCCResultType(LL.getValueType());
2940         if (N0.getValueType() == CCVT ||
2941             (!LegalOperations && N0.getValueType() == MVT::i1))
2942           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2943                               LL, LR, Result);
2944       }
2945     }
2946   }
2947 
2948   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2949       VT.getSizeInBits() <= 64) {
2950     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2951       APInt ADDC = ADDI->getAPIntValue();
2952       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2954         // immediate for an add, but it is legal if its top c2 bits are set,
2955         // transform the ADD so the immediate doesn't need to be materialized
2956         // in a register.
2957         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2958           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2959                                              SRLI->getZExtValue());
2960           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2961             ADDC |= Mask;
2962             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2963               SDLoc DL(N0);
2964               SDValue NewAdd =
2965                 DAG.getNode(ISD::ADD, DL, VT,
2966                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2967               CombineTo(N0.getNode(), NewAdd);
2968               // Return N so it doesn't get rechecked!
2969               return SDValue(LocReference, 0);
2970             }
2971           }
2972         }
2973       }
2974     }
2975   }
2976 
2977   // Reduce bit extract of low half of an integer to the narrower type.
2978   // (and (srl i64:x, K), KMask) ->
2979   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
2980   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2981     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
2982       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2983         unsigned Size = VT.getSizeInBits();
2984         const APInt &AndMask = CAnd->getAPIntValue();
2985         unsigned ShiftBits = CShift->getZExtValue();
2986         unsigned MaskBits = AndMask.countTrailingOnes();
2987         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
2988 
2989         if (APIntOps::isMask(AndMask) &&
2990             // Required bits must not span the two halves of the integer and
2991             // must fit in the half size type.
2992             (ShiftBits + MaskBits <= Size / 2) &&
2993             TLI.isNarrowingProfitable(VT, HalfVT) &&
2994             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
2995             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2996             TLI.isTruncateFree(VT, HalfVT) &&
2997             TLI.isZExtFree(HalfVT, VT)) {
2998           // The isNarrowingProfitable is to avoid regressions on PPC and
2999           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3000           // on downstream users of this. Those patterns could probably be
3001           // extended to handle extensions mixed in.
3002 
3003           SDValue SL(N0);
3004           assert(ShiftBits != 0 && MaskBits <= Size);
3005 
3006           // Extracting the highest bit of the low half.
3007           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3008           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3009                                       N0.getOperand(0));
3010 
3011           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3012           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3013           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3014           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3015           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3016         }
3017       }
3018     }
3019   }
3020 
3021   return SDValue();
3022 }
3023 
3024 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3025                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3026                                    bool &NarrowLoad) {
3027   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3028 
3029   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3030     return false;
3031 
3032   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3033   LoadedVT = LoadN->getMemoryVT();
3034 
3035   if (ExtVT == LoadedVT &&
3036       (!LegalOperations ||
3037        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3038     // ZEXTLOAD will match without needing to change the size of the value being
3039     // loaded.
3040     NarrowLoad = false;
3041     return true;
3042   }
3043 
3044   // Do not change the width of a volatile load.
3045   if (LoadN->isVolatile())
3046     return false;
3047 
3048   // Do not generate loads of non-round integer types since these can
3049   // be expensive (and would be wrong if the type is not byte sized).
3050   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3051     return false;
3052 
3053   if (LegalOperations &&
3054       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3055     return false;
3056 
3057   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3058     return false;
3059 
3060   NarrowLoad = true;
3061   return true;
3062 }
3063 
3064 SDValue DAGCombiner::visitAND(SDNode *N) {
3065   SDValue N0 = N->getOperand(0);
3066   SDValue N1 = N->getOperand(1);
3067   EVT VT = N1.getValueType();
3068 
3069   // fold vector ops
3070   if (VT.isVector()) {
3071     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3072       return FoldedVOp;
3073 
3074     // fold (and x, 0) -> 0, vector edition
3075     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3076       // do not return N0, because undef node may exist in N0
3077       return DAG.getConstant(
3078           APInt::getNullValue(
3079               N0.getValueType().getScalarType().getSizeInBits()),
3080           SDLoc(N), N0.getValueType());
3081     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3082       // do not return N1, because undef node may exist in N1
3083       return DAG.getConstant(
3084           APInt::getNullValue(
3085               N1.getValueType().getScalarType().getSizeInBits()),
3086           SDLoc(N), N1.getValueType());
3087 
3088     // fold (and x, -1) -> x, vector edition
3089     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3090       return N1;
3091     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3092       return N0;
3093   }
3094 
3095   // fold (and c1, c2) -> c1&c2
3096   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3097   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3098   if (N0C && N1C && !N1C->isOpaque())
3099     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3100   // canonicalize constant to RHS
3101   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3102      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3103     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3104   // fold (and x, -1) -> x
3105   if (isAllOnesConstant(N1))
3106     return N0;
3107   // if (and x, c) is known to be zero, return 0
3108   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3109   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3110                                    APInt::getAllOnesValue(BitWidth)))
3111     return DAG.getConstant(0, SDLoc(N), VT);
3112   // reassociate and
3113   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3114     return RAND;
3115   // fold (and (or x, C), D) -> D if (C & D) == D
3116   if (N1C && N0.getOpcode() == ISD::OR)
3117     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3118       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3119         return N1;
3120   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3121   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3122     SDValue N0Op0 = N0.getOperand(0);
3123     APInt Mask = ~N1C->getAPIntValue();
3124     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3125     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3126       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3127                                  N0.getValueType(), N0Op0);
3128 
3129       // Replace uses of the AND with uses of the Zero extend node.
3130       CombineTo(N, Zext);
3131 
3132       // We actually want to replace all uses of the any_extend with the
3133       // zero_extend, to avoid duplicating things.  This will later cause this
3134       // AND to be folded.
3135       CombineTo(N0.getNode(), Zext);
3136       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3137     }
3138   }
3139   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3140   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3141   // already be zero by virtue of the width of the base type of the load.
3142   //
3143   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3144   // more cases.
3145   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3146        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3147        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3148        N0.getOperand(0).getResNo() == 0) ||
3149       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3150     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3151                                          N0 : N0.getOperand(0) );
3152 
3153     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3154     // This can be a pure constant or a vector splat, in which case we treat the
3155     // vector as a scalar and use the splat value.
3156     APInt Constant = APInt::getNullValue(1);
3157     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3158       Constant = C->getAPIntValue();
3159     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3160       APInt SplatValue, SplatUndef;
3161       unsigned SplatBitSize;
3162       bool HasAnyUndefs;
3163       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3164                                              SplatBitSize, HasAnyUndefs);
3165       if (IsSplat) {
3166         // Undef bits can contribute to a possible optimisation if set, so
3167         // set them.
3168         SplatValue |= SplatUndef;
3169 
3170         // The splat value may be something like "0x00FFFFFF", which means 0 for
3171         // the first vector value and FF for the rest, repeating. We need a mask
3172         // that will apply equally to all members of the vector, so AND all the
3173         // lanes of the constant together.
3174         EVT VT = Vector->getValueType(0);
3175         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3176 
3177         // If the splat value has been compressed to a bitlength lower
3178         // than the size of the vector lane, we need to re-expand it to
3179         // the lane size.
3180         if (BitWidth > SplatBitSize)
3181           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3182                SplatBitSize < BitWidth;
3183                SplatBitSize = SplatBitSize * 2)
3184             SplatValue |= SplatValue.shl(SplatBitSize);
3185 
3186         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3187         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3188         if (SplatBitSize % BitWidth == 0) {
3189           Constant = APInt::getAllOnesValue(BitWidth);
3190           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3191             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3192         }
3193       }
3194     }
3195 
3196     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3197     // actually legal and isn't going to get expanded, else this is a false
3198     // optimisation.
3199     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3200                                                     Load->getValueType(0),
3201                                                     Load->getMemoryVT());
3202 
3203     // Resize the constant to the same size as the original memory access before
3204     // extension. If it is still the AllOnesValue then this AND is completely
3205     // unneeded.
3206     Constant =
3207       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3208 
3209     bool B;
3210     switch (Load->getExtensionType()) {
3211     default: B = false; break;
3212     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3213     case ISD::ZEXTLOAD:
3214     case ISD::NON_EXTLOAD: B = true; break;
3215     }
3216 
3217     if (B && Constant.isAllOnesValue()) {
3218       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3219       // preserve semantics once we get rid of the AND.
3220       SDValue NewLoad(Load, 0);
3221       if (Load->getExtensionType() == ISD::EXTLOAD) {
3222         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3223                               Load->getValueType(0), SDLoc(Load),
3224                               Load->getChain(), Load->getBasePtr(),
3225                               Load->getOffset(), Load->getMemoryVT(),
3226                               Load->getMemOperand());
3227         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3228         if (Load->getNumValues() == 3) {
3229           // PRE/POST_INC loads have 3 values.
3230           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3231                            NewLoad.getValue(2) };
3232           CombineTo(Load, To, 3, true);
3233         } else {
3234           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3235         }
3236       }
3237 
3238       // Fold the AND away, taking care not to fold to the old load node if we
3239       // replaced it.
3240       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3241 
3242       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3243     }
3244   }
3245 
3246   // fold (and (load x), 255) -> (zextload x, i8)
3247   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3248   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3249   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3250               (N0.getOpcode() == ISD::ANY_EXTEND &&
3251                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3252     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3253     LoadSDNode *LN0 = HasAnyExt
3254       ? cast<LoadSDNode>(N0.getOperand(0))
3255       : cast<LoadSDNode>(N0);
3256     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3257         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3258       auto NarrowLoad = false;
3259       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3260       EVT ExtVT, LoadedVT;
3261       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3262                            NarrowLoad)) {
3263         if (!NarrowLoad) {
3264           SDValue NewLoad =
3265             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3266                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3267                            LN0->getMemOperand());
3268           AddToWorklist(N);
3269           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3270           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3271         } else {
3272           EVT PtrType = LN0->getOperand(1).getValueType();
3273 
3274           unsigned Alignment = LN0->getAlignment();
3275           SDValue NewPtr = LN0->getBasePtr();
3276 
3277           // For big endian targets, we need to add an offset to the pointer
3278           // to load the correct bytes.  For little endian systems, we merely
3279           // need to read fewer bytes from the same pointer.
3280           if (DAG.getDataLayout().isBigEndian()) {
3281             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3282             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3283             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3284             SDLoc DL(LN0);
3285             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3286                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3287             Alignment = MinAlign(Alignment, PtrOff);
3288           }
3289 
3290           AddToWorklist(NewPtr.getNode());
3291 
3292           SDValue Load =
3293             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3294                            LN0->getChain(), NewPtr,
3295                            LN0->getPointerInfo(),
3296                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3297                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3298           AddToWorklist(N);
3299           CombineTo(LN0, Load, Load.getValue(1));
3300           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3301         }
3302       }
3303     }
3304   }
3305 
3306   if (SDValue Combined = visitANDLike(N0, N1, N))
3307     return Combined;
3308 
3309   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3310   if (N0.getOpcode() == N1.getOpcode())
3311     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3312       return Tmp;
3313 
3314   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3315   // fold (and (sra)) -> (and (srl)) when possible.
3316   if (!VT.isVector() &&
3317       SimplifyDemandedBits(SDValue(N, 0)))
3318     return SDValue(N, 0);
3319 
3320   // fold (zext_inreg (extload x)) -> (zextload x)
3321   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3322     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3323     EVT MemVT = LN0->getMemoryVT();
3324     // If we zero all the possible extended bits, then we can turn this into
3325     // a zextload if we are running before legalize or the operation is legal.
3326     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3327     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3328                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3329         ((!LegalOperations && !LN0->isVolatile()) ||
3330          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3331       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3332                                        LN0->getChain(), LN0->getBasePtr(),
3333                                        MemVT, LN0->getMemOperand());
3334       AddToWorklist(N);
3335       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3336       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3337     }
3338   }
3339   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3340   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3341       N0.hasOneUse()) {
3342     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3343     EVT MemVT = LN0->getMemoryVT();
3344     // If we zero all the possible extended bits, then we can turn this into
3345     // a zextload if we are running before legalize or the operation is legal.
3346     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3347     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3348                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3349         ((!LegalOperations && !LN0->isVolatile()) ||
3350          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3351       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3352                                        LN0->getChain(), LN0->getBasePtr(),
3353                                        MemVT, LN0->getMemOperand());
3354       AddToWorklist(N);
3355       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3356       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3357     }
3358   }
3359   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3360   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3361     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3362                                            N0.getOperand(1), false))
3363       return BSwap;
3364   }
3365 
3366   return SDValue();
3367 }
3368 
3369 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3370 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3371                                         bool DemandHighBits) {
3372   if (!LegalOperations)
3373     return SDValue();
3374 
3375   EVT VT = N->getValueType(0);
3376   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3377     return SDValue();
3378   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3379     return SDValue();
3380 
3381   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3382   bool LookPassAnd0 = false;
3383   bool LookPassAnd1 = false;
3384   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3385       std::swap(N0, N1);
3386   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3387       std::swap(N0, N1);
3388   if (N0.getOpcode() == ISD::AND) {
3389     if (!N0.getNode()->hasOneUse())
3390       return SDValue();
3391     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3392     if (!N01C || N01C->getZExtValue() != 0xFF00)
3393       return SDValue();
3394     N0 = N0.getOperand(0);
3395     LookPassAnd0 = true;
3396   }
3397 
3398   if (N1.getOpcode() == ISD::AND) {
3399     if (!N1.getNode()->hasOneUse())
3400       return SDValue();
3401     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3402     if (!N11C || N11C->getZExtValue() != 0xFF)
3403       return SDValue();
3404     N1 = N1.getOperand(0);
3405     LookPassAnd1 = true;
3406   }
3407 
3408   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3409     std::swap(N0, N1);
3410   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3411     return SDValue();
3412   if (!N0.getNode()->hasOneUse() ||
3413       !N1.getNode()->hasOneUse())
3414     return SDValue();
3415 
3416   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3417   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3418   if (!N01C || !N11C)
3419     return SDValue();
3420   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3421     return SDValue();
3422 
3423   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3424   SDValue N00 = N0->getOperand(0);
3425   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3426     if (!N00.getNode()->hasOneUse())
3427       return SDValue();
3428     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3429     if (!N001C || N001C->getZExtValue() != 0xFF)
3430       return SDValue();
3431     N00 = N00.getOperand(0);
3432     LookPassAnd0 = true;
3433   }
3434 
3435   SDValue N10 = N1->getOperand(0);
3436   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3437     if (!N10.getNode()->hasOneUse())
3438       return SDValue();
3439     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3440     if (!N101C || N101C->getZExtValue() != 0xFF00)
3441       return SDValue();
3442     N10 = N10.getOperand(0);
3443     LookPassAnd1 = true;
3444   }
3445 
3446   if (N00 != N10)
3447     return SDValue();
3448 
3449   // Make sure everything beyond the low halfword gets set to zero since the SRL
3450   // 16 will clear the top bits.
3451   unsigned OpSizeInBits = VT.getSizeInBits();
3452   if (DemandHighBits && OpSizeInBits > 16) {
3453     // If the left-shift isn't masked out then the only way this is a bswap is
3454     // if all bits beyond the low 8 are 0. In that case the entire pattern
3455     // reduces to a left shift anyway: leave it for other parts of the combiner.
3456     if (!LookPassAnd0)
3457       return SDValue();
3458 
3459     // However, if the right shift isn't masked out then it might be because
3460     // it's not needed. See if we can spot that too.
3461     if (!LookPassAnd1 &&
3462         !DAG.MaskedValueIsZero(
3463             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3464       return SDValue();
3465   }
3466 
3467   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3468   if (OpSizeInBits > 16) {
3469     SDLoc DL(N);
3470     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3471                       DAG.getConstant(OpSizeInBits - 16, DL,
3472                                       getShiftAmountTy(VT)));
3473   }
3474   return Res;
3475 }
3476 
3477 /// Return true if the specified node is an element that makes up a 32-bit
3478 /// packed halfword byteswap.
3479 /// ((x & 0x000000ff) << 8) |
3480 /// ((x & 0x0000ff00) >> 8) |
3481 /// ((x & 0x00ff0000) << 8) |
3482 /// ((x & 0xff000000) >> 8)
3483 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3484   if (!N.getNode()->hasOneUse())
3485     return false;
3486 
3487   unsigned Opc = N.getOpcode();
3488   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3489     return false;
3490 
3491   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3492   if (!N1C)
3493     return false;
3494 
3495   unsigned Num;
3496   switch (N1C->getZExtValue()) {
3497   default:
3498     return false;
3499   case 0xFF:       Num = 0; break;
3500   case 0xFF00:     Num = 1; break;
3501   case 0xFF0000:   Num = 2; break;
3502   case 0xFF000000: Num = 3; break;
3503   }
3504 
3505   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3506   SDValue N0 = N.getOperand(0);
3507   if (Opc == ISD::AND) {
3508     if (Num == 0 || Num == 2) {
3509       // (x >> 8) & 0xff
3510       // (x >> 8) & 0xff0000
3511       if (N0.getOpcode() != ISD::SRL)
3512         return false;
3513       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3514       if (!C || C->getZExtValue() != 8)
3515         return false;
3516     } else {
3517       // (x << 8) & 0xff00
3518       // (x << 8) & 0xff000000
3519       if (N0.getOpcode() != ISD::SHL)
3520         return false;
3521       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3522       if (!C || C->getZExtValue() != 8)
3523         return false;
3524     }
3525   } else if (Opc == ISD::SHL) {
3526     // (x & 0xff) << 8
3527     // (x & 0xff0000) << 8
3528     if (Num != 0 && Num != 2)
3529       return false;
3530     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3531     if (!C || C->getZExtValue() != 8)
3532       return false;
3533   } else { // Opc == ISD::SRL
3534     // (x & 0xff00) >> 8
3535     // (x & 0xff000000) >> 8
3536     if (Num != 1 && Num != 3)
3537       return false;
3538     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3539     if (!C || C->getZExtValue() != 8)
3540       return false;
3541   }
3542 
3543   if (Parts[Num])
3544     return false;
3545 
3546   Parts[Num] = N0.getOperand(0).getNode();
3547   return true;
3548 }
3549 
3550 /// Match a 32-bit packed halfword bswap. That is
3551 /// ((x & 0x000000ff) << 8) |
3552 /// ((x & 0x0000ff00) >> 8) |
3553 /// ((x & 0x00ff0000) << 8) |
3554 /// ((x & 0xff000000) >> 8)
3555 /// => (rotl (bswap x), 16)
3556 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3557   if (!LegalOperations)
3558     return SDValue();
3559 
3560   EVT VT = N->getValueType(0);
3561   if (VT != MVT::i32)
3562     return SDValue();
3563   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3564     return SDValue();
3565 
3566   // Look for either
3567   // (or (or (and), (and)), (or (and), (and)))
3568   // (or (or (or (and), (and)), (and)), (and))
3569   if (N0.getOpcode() != ISD::OR)
3570     return SDValue();
3571   SDValue N00 = N0.getOperand(0);
3572   SDValue N01 = N0.getOperand(1);
3573   SDNode *Parts[4] = {};
3574 
3575   if (N1.getOpcode() == ISD::OR &&
3576       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3577     // (or (or (and), (and)), (or (and), (and)))
3578     SDValue N000 = N00.getOperand(0);
3579     if (!isBSwapHWordElement(N000, Parts))
3580       return SDValue();
3581 
3582     SDValue N001 = N00.getOperand(1);
3583     if (!isBSwapHWordElement(N001, Parts))
3584       return SDValue();
3585     SDValue N010 = N01.getOperand(0);
3586     if (!isBSwapHWordElement(N010, Parts))
3587       return SDValue();
3588     SDValue N011 = N01.getOperand(1);
3589     if (!isBSwapHWordElement(N011, Parts))
3590       return SDValue();
3591   } else {
3592     // (or (or (or (and), (and)), (and)), (and))
3593     if (!isBSwapHWordElement(N1, Parts))
3594       return SDValue();
3595     if (!isBSwapHWordElement(N01, Parts))
3596       return SDValue();
3597     if (N00.getOpcode() != ISD::OR)
3598       return SDValue();
3599     SDValue N000 = N00.getOperand(0);
3600     if (!isBSwapHWordElement(N000, Parts))
3601       return SDValue();
3602     SDValue N001 = N00.getOperand(1);
3603     if (!isBSwapHWordElement(N001, Parts))
3604       return SDValue();
3605   }
3606 
3607   // Make sure the parts are all coming from the same node.
3608   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3609     return SDValue();
3610 
3611   SDLoc DL(N);
3612   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3613                               SDValue(Parts[0], 0));
3614 
3615   // Result of the bswap should be rotated by 16. If it's not legal, then
3616   // do  (x << 16) | (x >> 16).
3617   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3618   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3619     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3620   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3621     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3622   return DAG.getNode(ISD::OR, DL, VT,
3623                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3624                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3625 }
3626 
3627 /// This contains all DAGCombine rules which reduce two values combined by
3628 /// an Or operation to a single value \see visitANDLike().
3629 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3630   EVT VT = N1.getValueType();
3631   // fold (or x, undef) -> -1
3632   if (!LegalOperations &&
3633       (N0.isUndef() || N1.isUndef())) {
3634     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3635     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3636                            SDLoc(LocReference), VT);
3637   }
3638   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3639   SDValue LL, LR, RL, RR, CC0, CC1;
3640   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3641     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3642     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3643 
3644     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3645       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3646       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3647       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3648         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3649                                      LR.getValueType(), LL, RL);
3650         AddToWorklist(ORNode.getNode());
3651         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3652       }
3653       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3654       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3655       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3656         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3657                                       LR.getValueType(), LL, RL);
3658         AddToWorklist(ANDNode.getNode());
3659         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3660       }
3661     }
3662     // canonicalize equivalent to ll == rl
3663     if (LL == RR && LR == RL) {
3664       Op1 = ISD::getSetCCSwappedOperands(Op1);
3665       std::swap(RL, RR);
3666     }
3667     if (LL == RL && LR == RR) {
3668       bool isInteger = LL.getValueType().isInteger();
3669       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3670       if (Result != ISD::SETCC_INVALID &&
3671           (!LegalOperations ||
3672            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3673             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3674         EVT CCVT = getSetCCResultType(LL.getValueType());
3675         if (N0.getValueType() == CCVT ||
3676             (!LegalOperations && N0.getValueType() == MVT::i1))
3677           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3678                               LL, LR, Result);
3679       }
3680     }
3681   }
3682 
3683   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3684   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3685       // Don't increase # computations.
3686       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3687     // We can only do this xform if we know that bits from X that are set in C2
3688     // but not in C1 are already zero.  Likewise for Y.
3689     if (const ConstantSDNode *N0O1C =
3690         getAsNonOpaqueConstant(N0.getOperand(1))) {
3691       if (const ConstantSDNode *N1O1C =
3692           getAsNonOpaqueConstant(N1.getOperand(1))) {
3693         // We can only do this xform if we know that bits from X that are set in
3694         // C2 but not in C1 are already zero.  Likewise for Y.
3695         const APInt &LHSMask = N0O1C->getAPIntValue();
3696         const APInt &RHSMask = N1O1C->getAPIntValue();
3697 
3698         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3699             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3700           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3701                                   N0.getOperand(0), N1.getOperand(0));
3702           SDLoc DL(LocReference);
3703           return DAG.getNode(ISD::AND, DL, VT, X,
3704                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3705         }
3706       }
3707     }
3708   }
3709 
3710   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3711   if (N0.getOpcode() == ISD::AND &&
3712       N1.getOpcode() == ISD::AND &&
3713       N0.getOperand(0) == N1.getOperand(0) &&
3714       // Don't increase # computations.
3715       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3716     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3717                             N0.getOperand(1), N1.getOperand(1));
3718     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3719   }
3720 
3721   return SDValue();
3722 }
3723 
3724 SDValue DAGCombiner::visitOR(SDNode *N) {
3725   SDValue N0 = N->getOperand(0);
3726   SDValue N1 = N->getOperand(1);
3727   EVT VT = N1.getValueType();
3728 
3729   // fold vector ops
3730   if (VT.isVector()) {
3731     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3732       return FoldedVOp;
3733 
3734     // fold (or x, 0) -> x, vector edition
3735     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3736       return N1;
3737     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3738       return N0;
3739 
3740     // fold (or x, -1) -> -1, vector edition
3741     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3742       // do not return N0, because undef node may exist in N0
3743       return DAG.getConstant(
3744           APInt::getAllOnesValue(
3745               N0.getValueType().getScalarType().getSizeInBits()),
3746           SDLoc(N), N0.getValueType());
3747     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3748       // do not return N1, because undef node may exist in N1
3749       return DAG.getConstant(
3750           APInt::getAllOnesValue(
3751               N1.getValueType().getScalarType().getSizeInBits()),
3752           SDLoc(N), N1.getValueType());
3753 
3754     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3755     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3756     // Do this only if the resulting shuffle is legal.
3757     if (isa<ShuffleVectorSDNode>(N0) &&
3758         isa<ShuffleVectorSDNode>(N1) &&
3759         // Avoid folding a node with illegal type.
3760         TLI.isTypeLegal(VT) &&
3761         N0->getOperand(1) == N1->getOperand(1) &&
3762         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3763       bool CanFold = true;
3764       unsigned NumElts = VT.getVectorNumElements();
3765       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3766       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3767       // We construct two shuffle masks:
3768       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3769       // and N1 as the second operand.
3770       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3771       // and N0 as the second operand.
3772       // We do this because OR is commutable and therefore there might be
3773       // two ways to fold this node into a shuffle.
3774       SmallVector<int,4> Mask1;
3775       SmallVector<int,4> Mask2;
3776 
3777       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3778         int M0 = SV0->getMaskElt(i);
3779         int M1 = SV1->getMaskElt(i);
3780 
3781         // Both shuffle indexes are undef. Propagate Undef.
3782         if (M0 < 0 && M1 < 0) {
3783           Mask1.push_back(M0);
3784           Mask2.push_back(M0);
3785           continue;
3786         }
3787 
3788         if (M0 < 0 || M1 < 0 ||
3789             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3790             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3791           CanFold = false;
3792           break;
3793         }
3794 
3795         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3796         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3797       }
3798 
3799       if (CanFold) {
3800         // Fold this sequence only if the resulting shuffle is 'legal'.
3801         if (TLI.isShuffleMaskLegal(Mask1, VT))
3802           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3803                                       N1->getOperand(0), &Mask1[0]);
3804         if (TLI.isShuffleMaskLegal(Mask2, VT))
3805           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3806                                       N0->getOperand(0), &Mask2[0]);
3807       }
3808     }
3809   }
3810 
3811   // fold (or c1, c2) -> c1|c2
3812   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3813   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3814   if (N0C && N1C && !N1C->isOpaque())
3815     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3816   // canonicalize constant to RHS
3817   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3818      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3819     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3820   // fold (or x, 0) -> x
3821   if (isNullConstant(N1))
3822     return N0;
3823   // fold (or x, -1) -> -1
3824   if (isAllOnesConstant(N1))
3825     return N1;
3826   // fold (or x, c) -> c iff (x & ~c) == 0
3827   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3828     return N1;
3829 
3830   if (SDValue Combined = visitORLike(N0, N1, N))
3831     return Combined;
3832 
3833   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3834   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3835     return BSwap;
3836   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3837     return BSwap;
3838 
3839   // reassociate or
3840   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3841     return ROR;
3842   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3843   // iff (c1 & c2) == 0.
3844   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3845              isa<ConstantSDNode>(N0.getOperand(1))) {
3846     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3847     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3848       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3849                                                    N1C, C1))
3850         return DAG.getNode(
3851             ISD::AND, SDLoc(N), VT,
3852             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3853       return SDValue();
3854     }
3855   }
3856   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3857   if (N0.getOpcode() == N1.getOpcode())
3858     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3859       return Tmp;
3860 
3861   // See if this is some rotate idiom.
3862   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3863     return SDValue(Rot, 0);
3864 
3865   // Simplify the operands using demanded-bits information.
3866   if (!VT.isVector() &&
3867       SimplifyDemandedBits(SDValue(N, 0)))
3868     return SDValue(N, 0);
3869 
3870   return SDValue();
3871 }
3872 
3873 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3874 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3875   if (Op.getOpcode() == ISD::AND) {
3876     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3877       Mask = Op.getOperand(1);
3878       Op = Op.getOperand(0);
3879     } else {
3880       return false;
3881     }
3882   }
3883 
3884   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3885     Shift = Op;
3886     return true;
3887   }
3888 
3889   return false;
3890 }
3891 
3892 // Return true if we can prove that, whenever Neg and Pos are both in the
3893 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3894 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3895 //
3896 //     (or (shift1 X, Neg), (shift2 X, Pos))
3897 //
3898 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3899 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3900 // to consider shift amounts with defined behavior.
3901 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3902   // If EltSize is a power of 2 then:
3903   //
3904   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3905   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3906   //
3907   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3908   // for the stronger condition:
3909   //
3910   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3911   //
3912   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3913   // we can just replace Neg with Neg' for the rest of the function.
3914   //
3915   // In other cases we check for the even stronger condition:
3916   //
3917   //     Neg == EltSize - Pos                                    [B]
3918   //
3919   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3920   // behavior if Pos == 0 (and consequently Neg == EltSize).
3921   //
3922   // We could actually use [A] whenever EltSize is a power of 2, but the
3923   // only extra cases that it would match are those uninteresting ones
3924   // where Neg and Pos are never in range at the same time.  E.g. for
3925   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3926   // as well as (sub 32, Pos), but:
3927   //
3928   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3929   //
3930   // always invokes undefined behavior for 32-bit X.
3931   //
3932   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3933   unsigned MaskLoBits = 0;
3934   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3935     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3936       if (NegC->getAPIntValue() == EltSize - 1) {
3937         Neg = Neg.getOperand(0);
3938         MaskLoBits = Log2_64(EltSize);
3939       }
3940     }
3941   }
3942 
3943   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3944   if (Neg.getOpcode() != ISD::SUB)
3945     return false;
3946   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3947   if (!NegC)
3948     return false;
3949   SDValue NegOp1 = Neg.getOperand(1);
3950 
3951   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3952   // Pos'.  The truncation is redundant for the purpose of the equality.
3953   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3954     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3955       if (PosC->getAPIntValue() == EltSize - 1)
3956         Pos = Pos.getOperand(0);
3957 
3958   // The condition we need is now:
3959   //
3960   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3961   //
3962   // If NegOp1 == Pos then we need:
3963   //
3964   //              EltSize & Mask == NegC & Mask
3965   //
3966   // (because "x & Mask" is a truncation and distributes through subtraction).
3967   APInt Width;
3968   if (Pos == NegOp1)
3969     Width = NegC->getAPIntValue();
3970 
3971   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3972   // Then the condition we want to prove becomes:
3973   //
3974   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3975   //
3976   // which, again because "x & Mask" is a truncation, becomes:
3977   //
3978   //                NegC & Mask == (EltSize - PosC) & Mask
3979   //             EltSize & Mask == (NegC + PosC) & Mask
3980   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3981     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3982       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3983     else
3984       return false;
3985   } else
3986     return false;
3987 
3988   // Now we just need to check that EltSize & Mask == Width & Mask.
3989   if (MaskLoBits)
3990     // EltSize & Mask is 0 since Mask is EltSize - 1.
3991     return Width.getLoBits(MaskLoBits) == 0;
3992   return Width == EltSize;
3993 }
3994 
3995 // A subroutine of MatchRotate used once we have found an OR of two opposite
3996 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3997 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3998 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3999 // Neg with outer conversions stripped away.
4000 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4001                                        SDValue Neg, SDValue InnerPos,
4002                                        SDValue InnerNeg, unsigned PosOpcode,
4003                                        unsigned NegOpcode, SDLoc DL) {
4004   // fold (or (shl x, (*ext y)),
4005   //          (srl x, (*ext (sub 32, y)))) ->
4006   //   (rotl x, y) or (rotr x, (sub 32, y))
4007   //
4008   // fold (or (shl x, (*ext (sub 32, y))),
4009   //          (srl x, (*ext y))) ->
4010   //   (rotr x, y) or (rotl x, (sub 32, y))
4011   EVT VT = Shifted.getValueType();
4012   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4013     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4014     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4015                        HasPos ? Pos : Neg).getNode();
4016   }
4017 
4018   return nullptr;
4019 }
4020 
4021 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4022 // idioms for rotate, and if the target supports rotation instructions, generate
4023 // a rot[lr].
4024 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
4025   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4026   EVT VT = LHS.getValueType();
4027   if (!TLI.isTypeLegal(VT)) return nullptr;
4028 
4029   // The target must have at least one rotate flavor.
4030   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4031   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4032   if (!HasROTL && !HasROTR) return nullptr;
4033 
4034   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4035   SDValue LHSShift;   // The shift.
4036   SDValue LHSMask;    // AND value if any.
4037   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4038     return nullptr; // Not part of a rotate.
4039 
4040   SDValue RHSShift;   // The shift.
4041   SDValue RHSMask;    // AND value if any.
4042   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4043     return nullptr; // Not part of a rotate.
4044 
4045   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4046     return nullptr;   // Not shifting the same value.
4047 
4048   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4049     return nullptr;   // Shifts must disagree.
4050 
4051   // Canonicalize shl to left side in a shl/srl pair.
4052   if (RHSShift.getOpcode() == ISD::SHL) {
4053     std::swap(LHS, RHS);
4054     std::swap(LHSShift, RHSShift);
4055     std::swap(LHSMask, RHSMask);
4056   }
4057 
4058   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4059   SDValue LHSShiftArg = LHSShift.getOperand(0);
4060   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4061   SDValue RHSShiftArg = RHSShift.getOperand(0);
4062   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4063 
4064   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4065   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4066   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4067     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4068     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4069     if ((LShVal + RShVal) != EltSizeInBits)
4070       return nullptr;
4071 
4072     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4073                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4074 
4075     // If there is an AND of either shifted operand, apply it to the result.
4076     if (LHSMask.getNode() || RHSMask.getNode()) {
4077       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4078       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4079 
4080       if (LHSMask.getNode()) {
4081         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4082         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4083                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4084                                        DAG.getConstant(RHSBits, DL, VT)));
4085       }
4086       if (RHSMask.getNode()) {
4087         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4088         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4089                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4090                                        DAG.getConstant(LHSBits, DL, VT)));
4091       }
4092 
4093       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4094     }
4095 
4096     return Rot.getNode();
4097   }
4098 
4099   // If there is a mask here, and we have a variable shift, we can't be sure
4100   // that we're masking out the right stuff.
4101   if (LHSMask.getNode() || RHSMask.getNode())
4102     return nullptr;
4103 
4104   // If the shift amount is sign/zext/any-extended just peel it off.
4105   SDValue LExtOp0 = LHSShiftAmt;
4106   SDValue RExtOp0 = RHSShiftAmt;
4107   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4108        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4109        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4110        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4111       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4112        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4113        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4114        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4115     LExtOp0 = LHSShiftAmt.getOperand(0);
4116     RExtOp0 = RHSShiftAmt.getOperand(0);
4117   }
4118 
4119   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4120                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4121   if (TryL)
4122     return TryL;
4123 
4124   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4125                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4126   if (TryR)
4127     return TryR;
4128 
4129   return nullptr;
4130 }
4131 
4132 SDValue DAGCombiner::visitXOR(SDNode *N) {
4133   SDValue N0 = N->getOperand(0);
4134   SDValue N1 = N->getOperand(1);
4135   EVT VT = N0.getValueType();
4136 
4137   // fold vector ops
4138   if (VT.isVector()) {
4139     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4140       return FoldedVOp;
4141 
4142     // fold (xor x, 0) -> x, vector edition
4143     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4144       return N1;
4145     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4146       return N0;
4147   }
4148 
4149   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4150   if (N0.isUndef() && N1.isUndef())
4151     return DAG.getConstant(0, SDLoc(N), VT);
4152   // fold (xor x, undef) -> undef
4153   if (N0.isUndef())
4154     return N0;
4155   if (N1.isUndef())
4156     return N1;
4157   // fold (xor c1, c2) -> c1^c2
4158   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4159   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4160   if (N0C && N1C)
4161     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4162   // canonicalize constant to RHS
4163   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4164      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4165     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4166   // fold (xor x, 0) -> x
4167   if (isNullConstant(N1))
4168     return N0;
4169   // reassociate xor
4170   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4171     return RXOR;
4172 
4173   // fold !(x cc y) -> (x !cc y)
4174   SDValue LHS, RHS, CC;
4175   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4176     bool isInt = LHS.getValueType().isInteger();
4177     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4178                                                isInt);
4179 
4180     if (!LegalOperations ||
4181         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4182       switch (N0.getOpcode()) {
4183       default:
4184         llvm_unreachable("Unhandled SetCC Equivalent!");
4185       case ISD::SETCC:
4186         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4187       case ISD::SELECT_CC:
4188         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4189                                N0.getOperand(3), NotCC);
4190       }
4191     }
4192   }
4193 
4194   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4195   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4196       N0.getNode()->hasOneUse() &&
4197       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4198     SDValue V = N0.getOperand(0);
4199     SDLoc DL(N0);
4200     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4201                     DAG.getConstant(1, DL, V.getValueType()));
4202     AddToWorklist(V.getNode());
4203     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4204   }
4205 
4206   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4207   if (isOneConstant(N1) && VT == MVT::i1 &&
4208       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4209     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4210     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4211       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4212       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4213       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4214       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4215       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4216     }
4217   }
4218   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4219   if (isAllOnesConstant(N1) &&
4220       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4221     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4222     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4223       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4224       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4225       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4226       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4227       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4228     }
4229   }
4230   // fold (xor (and x, y), y) -> (and (not x), y)
4231   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4232       N0->getOperand(1) == N1) {
4233     SDValue X = N0->getOperand(0);
4234     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4235     AddToWorklist(NotX.getNode());
4236     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4237   }
4238   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4239   if (N1C && N0.getOpcode() == ISD::XOR) {
4240     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4241       SDLoc DL(N);
4242       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4243                          DAG.getConstant(N1C->getAPIntValue() ^
4244                                          N00C->getAPIntValue(), DL, VT));
4245     }
4246     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4247       SDLoc DL(N);
4248       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4249                          DAG.getConstant(N1C->getAPIntValue() ^
4250                                          N01C->getAPIntValue(), DL, VT));
4251     }
4252   }
4253   // fold (xor x, x) -> 0
4254   if (N0 == N1)
4255     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4256 
4257   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4258   // Here is a concrete example of this equivalence:
4259   // i16   x ==  14
4260   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4261   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4262   //
4263   // =>
4264   //
4265   // i16     ~1      == 0b1111111111111110
4266   // i16 rol(~1, 14) == 0b1011111111111111
4267   //
4268   // Some additional tips to help conceptualize this transform:
4269   // - Try to see the operation as placing a single zero in a value of all ones.
4270   // - There exists no value for x which would allow the result to contain zero.
4271   // - Values of x larger than the bitwidth are undefined and do not require a
4272   //   consistent result.
4273   // - Pushing the zero left requires shifting one bits in from the right.
4274   // A rotate left of ~1 is a nice way of achieving the desired result.
4275   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4276       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4277     SDLoc DL(N);
4278     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4279                        N0.getOperand(1));
4280   }
4281 
4282   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4283   if (N0.getOpcode() == N1.getOpcode())
4284     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4285       return Tmp;
4286 
4287   // Simplify the expression using non-local knowledge.
4288   if (!VT.isVector() &&
4289       SimplifyDemandedBits(SDValue(N, 0)))
4290     return SDValue(N, 0);
4291 
4292   return SDValue();
4293 }
4294 
4295 /// Handle transforms common to the three shifts, when the shift amount is a
4296 /// constant.
4297 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4298   SDNode *LHS = N->getOperand(0).getNode();
4299   if (!LHS->hasOneUse()) return SDValue();
4300 
4301   // We want to pull some binops through shifts, so that we have (and (shift))
4302   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4303   // thing happens with address calculations, so it's important to canonicalize
4304   // it.
4305   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4306 
4307   switch (LHS->getOpcode()) {
4308   default: return SDValue();
4309   case ISD::OR:
4310   case ISD::XOR:
4311     HighBitSet = false; // We can only transform sra if the high bit is clear.
4312     break;
4313   case ISD::AND:
4314     HighBitSet = true;  // We can only transform sra if the high bit is set.
4315     break;
4316   case ISD::ADD:
4317     if (N->getOpcode() != ISD::SHL)
4318       return SDValue(); // only shl(add) not sr[al](add).
4319     HighBitSet = false; // We can only transform sra if the high bit is clear.
4320     break;
4321   }
4322 
4323   // We require the RHS of the binop to be a constant and not opaque as well.
4324   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4325   if (!BinOpCst) return SDValue();
4326 
4327   // FIXME: disable this unless the input to the binop is a shift by a constant.
4328   // If it is not a shift, it pessimizes some common cases like:
4329   //
4330   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4331   //    int bar(int *X, int i) { return X[i & 255]; }
4332   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4333   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4334        BinOpLHSVal->getOpcode() != ISD::SRA &&
4335        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4336       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4337     return SDValue();
4338 
4339   EVT VT = N->getValueType(0);
4340 
4341   // If this is a signed shift right, and the high bit is modified by the
4342   // logical operation, do not perform the transformation. The highBitSet
4343   // boolean indicates the value of the high bit of the constant which would
4344   // cause it to be modified for this operation.
4345   if (N->getOpcode() == ISD::SRA) {
4346     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4347     if (BinOpRHSSignSet != HighBitSet)
4348       return SDValue();
4349   }
4350 
4351   if (!TLI.isDesirableToCommuteWithShift(LHS))
4352     return SDValue();
4353 
4354   // Fold the constants, shifting the binop RHS by the shift amount.
4355   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4356                                N->getValueType(0),
4357                                LHS->getOperand(1), N->getOperand(1));
4358   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4359 
4360   // Create the new shift.
4361   SDValue NewShift = DAG.getNode(N->getOpcode(),
4362                                  SDLoc(LHS->getOperand(0)),
4363                                  VT, LHS->getOperand(0), N->getOperand(1));
4364 
4365   // Create the new binop.
4366   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4367 }
4368 
4369 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4370   assert(N->getOpcode() == ISD::TRUNCATE);
4371   assert(N->getOperand(0).getOpcode() == ISD::AND);
4372 
4373   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4374   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4375     SDValue N01 = N->getOperand(0).getOperand(1);
4376 
4377     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4378       if (!N01C->isOpaque()) {
4379         EVT TruncVT = N->getValueType(0);
4380         SDValue N00 = N->getOperand(0).getOperand(0);
4381         APInt TruncC = N01C->getAPIntValue();
4382         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4383         SDLoc DL(N);
4384 
4385         return DAG.getNode(ISD::AND, DL, TruncVT,
4386                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4387                            DAG.getConstant(TruncC, DL, TruncVT));
4388       }
4389     }
4390   }
4391 
4392   return SDValue();
4393 }
4394 
4395 SDValue DAGCombiner::visitRotate(SDNode *N) {
4396   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4397   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4398       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4399     if (SDValue NewOp1 =
4400             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4401       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4402                          N->getOperand(0), NewOp1);
4403   }
4404   return SDValue();
4405 }
4406 
4407 SDValue DAGCombiner::visitSHL(SDNode *N) {
4408   SDValue N0 = N->getOperand(0);
4409   SDValue N1 = N->getOperand(1);
4410   EVT VT = N0.getValueType();
4411   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4412 
4413   // fold vector ops
4414   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4415   if (VT.isVector()) {
4416     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4417       return FoldedVOp;
4418 
4419     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4420     // If setcc produces all-one true value then:
4421     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4422     if (N1CV && N1CV->isConstant()) {
4423       if (N0.getOpcode() == ISD::AND) {
4424         SDValue N00 = N0->getOperand(0);
4425         SDValue N01 = N0->getOperand(1);
4426         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4427 
4428         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4429             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4430                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4431           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4432                                                      N01CV, N1CV))
4433             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4434         }
4435       } else {
4436         N1C = isConstOrConstSplat(N1);
4437       }
4438     }
4439   }
4440 
4441   // fold (shl c1, c2) -> c1<<c2
4442   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4443   if (N0C && N1C && !N1C->isOpaque())
4444     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4445   // fold (shl 0, x) -> 0
4446   if (isNullConstant(N0))
4447     return N0;
4448   // fold (shl x, c >= size(x)) -> undef
4449   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4450     return DAG.getUNDEF(VT);
4451   // fold (shl x, 0) -> x
4452   if (N1C && N1C->isNullValue())
4453     return N0;
4454   // fold (shl undef, x) -> 0
4455   if (N0.isUndef())
4456     return DAG.getConstant(0, SDLoc(N), VT);
4457   // if (shl x, c) is known to be zero, return 0
4458   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4459                             APInt::getAllOnesValue(OpSizeInBits)))
4460     return DAG.getConstant(0, SDLoc(N), VT);
4461   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4462   if (N1.getOpcode() == ISD::TRUNCATE &&
4463       N1.getOperand(0).getOpcode() == ISD::AND) {
4464     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4465       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4466   }
4467 
4468   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4469     return SDValue(N, 0);
4470 
4471   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4472   if (N1C && N0.getOpcode() == ISD::SHL) {
4473     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4474       uint64_t c1 = N0C1->getZExtValue();
4475       uint64_t c2 = N1C->getZExtValue();
4476       SDLoc DL(N);
4477       if (c1 + c2 >= OpSizeInBits)
4478         return DAG.getConstant(0, DL, VT);
4479       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4480                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4481     }
4482   }
4483 
4484   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4485   // For this to be valid, the second form must not preserve any of the bits
4486   // that are shifted out by the inner shift in the first form.  This means
4487   // the outer shift size must be >= the number of bits added by the ext.
4488   // As a corollary, we don't care what kind of ext it is.
4489   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4490               N0.getOpcode() == ISD::ANY_EXTEND ||
4491               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4492       N0.getOperand(0).getOpcode() == ISD::SHL) {
4493     SDValue N0Op0 = N0.getOperand(0);
4494     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4495       uint64_t c1 = N0Op0C1->getZExtValue();
4496       uint64_t c2 = N1C->getZExtValue();
4497       EVT InnerShiftVT = N0Op0.getValueType();
4498       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4499       if (c2 >= OpSizeInBits - InnerShiftSize) {
4500         SDLoc DL(N0);
4501         if (c1 + c2 >= OpSizeInBits)
4502           return DAG.getConstant(0, DL, VT);
4503         return DAG.getNode(ISD::SHL, DL, VT,
4504                            DAG.getNode(N0.getOpcode(), DL, VT,
4505                                        N0Op0->getOperand(0)),
4506                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4507       }
4508     }
4509   }
4510 
4511   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4512   // Only fold this if the inner zext has no other uses to avoid increasing
4513   // the total number of instructions.
4514   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4515       N0.getOperand(0).getOpcode() == ISD::SRL) {
4516     SDValue N0Op0 = N0.getOperand(0);
4517     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4518       uint64_t c1 = N0Op0C1->getZExtValue();
4519       if (c1 < VT.getScalarSizeInBits()) {
4520         uint64_t c2 = N1C->getZExtValue();
4521         if (c1 == c2) {
4522           SDValue NewOp0 = N0.getOperand(0);
4523           EVT CountVT = NewOp0.getOperand(1).getValueType();
4524           SDLoc DL(N);
4525           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4526                                        NewOp0,
4527                                        DAG.getConstant(c2, DL, CountVT));
4528           AddToWorklist(NewSHL.getNode());
4529           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4530         }
4531       }
4532     }
4533   }
4534 
4535   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4536   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4537   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4538       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4539     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4540       uint64_t C1 = N0C1->getZExtValue();
4541       uint64_t C2 = N1C->getZExtValue();
4542       SDLoc DL(N);
4543       if (C1 <= C2)
4544         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4545                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4546       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4547                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4548     }
4549   }
4550 
4551   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4552   //                               (and (srl x, (sub c1, c2), MASK)
4553   // Only fold this if the inner shift has no other uses -- if it does, folding
4554   // this will increase the total number of instructions.
4555   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4556     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4557       uint64_t c1 = N0C1->getZExtValue();
4558       if (c1 < OpSizeInBits) {
4559         uint64_t c2 = N1C->getZExtValue();
4560         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4561         SDValue Shift;
4562         if (c2 > c1) {
4563           Mask = Mask.shl(c2 - c1);
4564           SDLoc DL(N);
4565           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4566                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4567         } else {
4568           Mask = Mask.lshr(c1 - c2);
4569           SDLoc DL(N);
4570           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4571                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4572         }
4573         SDLoc DL(N0);
4574         return DAG.getNode(ISD::AND, DL, VT, Shift,
4575                            DAG.getConstant(Mask, DL, VT));
4576       }
4577     }
4578   }
4579   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4580   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4581     unsigned BitSize = VT.getScalarSizeInBits();
4582     SDLoc DL(N);
4583     SDValue HiBitsMask =
4584       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4585                                             BitSize - N1C->getZExtValue()),
4586                       DL, VT);
4587     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4588                        HiBitsMask);
4589   }
4590 
4591   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4592   // Variant of version done on multiply, except mul by a power of 2 is turned
4593   // into a shift.
4594   APInt Val;
4595   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4596       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4597        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4598     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4599     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4600     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4601   }
4602 
4603   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4604   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4605     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4606       if (SDValue Folded =
4607               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4608         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4609     }
4610   }
4611 
4612   if (N1C && !N1C->isOpaque())
4613     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4614       return NewSHL;
4615 
4616   return SDValue();
4617 }
4618 
4619 SDValue DAGCombiner::visitSRA(SDNode *N) {
4620   SDValue N0 = N->getOperand(0);
4621   SDValue N1 = N->getOperand(1);
4622   EVT VT = N0.getValueType();
4623   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4624 
4625   // fold vector ops
4626   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4627   if (VT.isVector()) {
4628     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4629       return FoldedVOp;
4630 
4631     N1C = isConstOrConstSplat(N1);
4632   }
4633 
4634   // fold (sra c1, c2) -> (sra c1, c2)
4635   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4636   if (N0C && N1C && !N1C->isOpaque())
4637     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4638   // fold (sra 0, x) -> 0
4639   if (isNullConstant(N0))
4640     return N0;
4641   // fold (sra -1, x) -> -1
4642   if (isAllOnesConstant(N0))
4643     return N0;
4644   // fold (sra x, (setge c, size(x))) -> undef
4645   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4646     return DAG.getUNDEF(VT);
4647   // fold (sra x, 0) -> x
4648   if (N1C && N1C->isNullValue())
4649     return N0;
4650   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4651   // sext_inreg.
4652   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4653     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4654     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4655     if (VT.isVector())
4656       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4657                                ExtVT, VT.getVectorNumElements());
4658     if ((!LegalOperations ||
4659          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4660       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4661                          N0.getOperand(0), DAG.getValueType(ExtVT));
4662   }
4663 
4664   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4665   if (N1C && N0.getOpcode() == ISD::SRA) {
4666     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4667       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4668       if (Sum >= OpSizeInBits)
4669         Sum = OpSizeInBits - 1;
4670       SDLoc DL(N);
4671       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4672                          DAG.getConstant(Sum, DL, N1.getValueType()));
4673     }
4674   }
4675 
4676   // fold (sra (shl X, m), (sub result_size, n))
4677   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4678   // result_size - n != m.
4679   // If truncate is free for the target sext(shl) is likely to result in better
4680   // code.
4681   if (N0.getOpcode() == ISD::SHL && N1C) {
4682     // Get the two constanst of the shifts, CN0 = m, CN = n.
4683     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4684     if (N01C) {
4685       LLVMContext &Ctx = *DAG.getContext();
4686       // Determine what the truncate's result bitsize and type would be.
4687       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4688 
4689       if (VT.isVector())
4690         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4691 
4692       // Determine the residual right-shift amount.
4693       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4694 
4695       // If the shift is not a no-op (in which case this should be just a sign
4696       // extend already), the truncated to type is legal, sign_extend is legal
4697       // on that type, and the truncate to that type is both legal and free,
4698       // perform the transform.
4699       if ((ShiftAmt > 0) &&
4700           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4701           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4702           TLI.isTruncateFree(VT, TruncVT)) {
4703 
4704         SDLoc DL(N);
4705         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4706             getShiftAmountTy(N0.getOperand(0).getValueType()));
4707         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4708                                     N0.getOperand(0), Amt);
4709         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4710                                     Shift);
4711         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4712                            N->getValueType(0), Trunc);
4713       }
4714     }
4715   }
4716 
4717   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4718   if (N1.getOpcode() == ISD::TRUNCATE &&
4719       N1.getOperand(0).getOpcode() == ISD::AND) {
4720     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4721       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4722   }
4723 
4724   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4725   //      if c1 is equal to the number of bits the trunc removes
4726   if (N0.getOpcode() == ISD::TRUNCATE &&
4727       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4728        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4729       N0.getOperand(0).hasOneUse() &&
4730       N0.getOperand(0).getOperand(1).hasOneUse() &&
4731       N1C) {
4732     SDValue N0Op0 = N0.getOperand(0);
4733     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4734       unsigned LargeShiftVal = LargeShift->getZExtValue();
4735       EVT LargeVT = N0Op0.getValueType();
4736 
4737       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4738         SDLoc DL(N);
4739         SDValue Amt =
4740           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4741                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4742         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4743                                   N0Op0.getOperand(0), Amt);
4744         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4745       }
4746     }
4747   }
4748 
4749   // Simplify, based on bits shifted out of the LHS.
4750   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4751     return SDValue(N, 0);
4752 
4753 
4754   // If the sign bit is known to be zero, switch this to a SRL.
4755   if (DAG.SignBitIsZero(N0))
4756     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4757 
4758   if (N1C && !N1C->isOpaque())
4759     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4760       return NewSRA;
4761 
4762   return SDValue();
4763 }
4764 
4765 SDValue DAGCombiner::visitSRL(SDNode *N) {
4766   SDValue N0 = N->getOperand(0);
4767   SDValue N1 = N->getOperand(1);
4768   EVT VT = N0.getValueType();
4769   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4770 
4771   // fold vector ops
4772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4773   if (VT.isVector()) {
4774     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4775       return FoldedVOp;
4776 
4777     N1C = isConstOrConstSplat(N1);
4778   }
4779 
4780   // fold (srl c1, c2) -> c1 >>u c2
4781   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4782   if (N0C && N1C && !N1C->isOpaque())
4783     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4784   // fold (srl 0, x) -> 0
4785   if (isNullConstant(N0))
4786     return N0;
4787   // fold (srl x, c >= size(x)) -> undef
4788   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4789     return DAG.getUNDEF(VT);
4790   // fold (srl x, 0) -> x
4791   if (N1C && N1C->isNullValue())
4792     return N0;
4793   // if (srl x, c) is known to be zero, return 0
4794   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4795                                    APInt::getAllOnesValue(OpSizeInBits)))
4796     return DAG.getConstant(0, SDLoc(N), VT);
4797 
4798   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4799   if (N1C && N0.getOpcode() == ISD::SRL) {
4800     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4801       uint64_t c1 = N01C->getZExtValue();
4802       uint64_t c2 = N1C->getZExtValue();
4803       SDLoc DL(N);
4804       if (c1 + c2 >= OpSizeInBits)
4805         return DAG.getConstant(0, DL, VT);
4806       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4807                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4808     }
4809   }
4810 
4811   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4812   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4813       N0.getOperand(0).getOpcode() == ISD::SRL &&
4814       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4815     uint64_t c1 =
4816       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4817     uint64_t c2 = N1C->getZExtValue();
4818     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4819     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4820     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4821     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4822     if (c1 + OpSizeInBits == InnerShiftSize) {
4823       SDLoc DL(N0);
4824       if (c1 + c2 >= InnerShiftSize)
4825         return DAG.getConstant(0, DL, VT);
4826       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4827                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4828                                      N0.getOperand(0)->getOperand(0),
4829                                      DAG.getConstant(c1 + c2, DL,
4830                                                      ShiftCountVT)));
4831     }
4832   }
4833 
4834   // fold (srl (shl x, c), c) -> (and x, cst2)
4835   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4836     unsigned BitSize = N0.getScalarValueSizeInBits();
4837     if (BitSize <= 64) {
4838       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4839       SDLoc DL(N);
4840       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4841                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4842     }
4843   }
4844 
4845   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4846   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4847     // Shifting in all undef bits?
4848     EVT SmallVT = N0.getOperand(0).getValueType();
4849     unsigned BitSize = SmallVT.getScalarSizeInBits();
4850     if (N1C->getZExtValue() >= BitSize)
4851       return DAG.getUNDEF(VT);
4852 
4853     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4854       uint64_t ShiftAmt = N1C->getZExtValue();
4855       SDLoc DL0(N0);
4856       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4857                                        N0.getOperand(0),
4858                           DAG.getConstant(ShiftAmt, DL0,
4859                                           getShiftAmountTy(SmallVT)));
4860       AddToWorklist(SmallShift.getNode());
4861       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4862       SDLoc DL(N);
4863       return DAG.getNode(ISD::AND, DL, VT,
4864                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4865                          DAG.getConstant(Mask, DL, VT));
4866     }
4867   }
4868 
4869   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4870   // bit, which is unmodified by sra.
4871   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4872     if (N0.getOpcode() == ISD::SRA)
4873       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4874   }
4875 
4876   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4877   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4878       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4879     APInt KnownZero, KnownOne;
4880     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4881 
4882     // If any of the input bits are KnownOne, then the input couldn't be all
4883     // zeros, thus the result of the srl will always be zero.
4884     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4885 
4886     // If all of the bits input the to ctlz node are known to be zero, then
4887     // the result of the ctlz is "32" and the result of the shift is one.
4888     APInt UnknownBits = ~KnownZero;
4889     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4890 
4891     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4892     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4893       // Okay, we know that only that the single bit specified by UnknownBits
4894       // could be set on input to the CTLZ node. If this bit is set, the SRL
4895       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4896       // to an SRL/XOR pair, which is likely to simplify more.
4897       unsigned ShAmt = UnknownBits.countTrailingZeros();
4898       SDValue Op = N0.getOperand(0);
4899 
4900       if (ShAmt) {
4901         SDLoc DL(N0);
4902         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4903                   DAG.getConstant(ShAmt, DL,
4904                                   getShiftAmountTy(Op.getValueType())));
4905         AddToWorklist(Op.getNode());
4906       }
4907 
4908       SDLoc DL(N);
4909       return DAG.getNode(ISD::XOR, DL, VT,
4910                          Op, DAG.getConstant(1, DL, VT));
4911     }
4912   }
4913 
4914   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4915   if (N1.getOpcode() == ISD::TRUNCATE &&
4916       N1.getOperand(0).getOpcode() == ISD::AND) {
4917     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4918       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4919   }
4920 
4921   // fold operands of srl based on knowledge that the low bits are not
4922   // demanded.
4923   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4924     return SDValue(N, 0);
4925 
4926   if (N1C && !N1C->isOpaque())
4927     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4928       return NewSRL;
4929 
4930   // Attempt to convert a srl of a load into a narrower zero-extending load.
4931   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4932     return NarrowLoad;
4933 
4934   // Here is a common situation. We want to optimize:
4935   //
4936   //   %a = ...
4937   //   %b = and i32 %a, 2
4938   //   %c = srl i32 %b, 1
4939   //   brcond i32 %c ...
4940   //
4941   // into
4942   //
4943   //   %a = ...
4944   //   %b = and %a, 2
4945   //   %c = setcc eq %b, 0
4946   //   brcond %c ...
4947   //
4948   // However when after the source operand of SRL is optimized into AND, the SRL
4949   // itself may not be optimized further. Look for it and add the BRCOND into
4950   // the worklist.
4951   if (N->hasOneUse()) {
4952     SDNode *Use = *N->use_begin();
4953     if (Use->getOpcode() == ISD::BRCOND)
4954       AddToWorklist(Use);
4955     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4956       // Also look pass the truncate.
4957       Use = *Use->use_begin();
4958       if (Use->getOpcode() == ISD::BRCOND)
4959         AddToWorklist(Use);
4960     }
4961   }
4962 
4963   return SDValue();
4964 }
4965 
4966 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4967   SDValue N0 = N->getOperand(0);
4968   EVT VT = N->getValueType(0);
4969 
4970   // fold (bswap c1) -> c2
4971   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4972     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4973   // fold (bswap (bswap x)) -> x
4974   if (N0.getOpcode() == ISD::BSWAP)
4975     return N0->getOperand(0);
4976   return SDValue();
4977 }
4978 
4979 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4980   SDValue N0 = N->getOperand(0);
4981   EVT VT = N->getValueType(0);
4982 
4983   // fold (ctlz c1) -> c2
4984   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4985     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4986   return SDValue();
4987 }
4988 
4989 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4990   SDValue N0 = N->getOperand(0);
4991   EVT VT = N->getValueType(0);
4992 
4993   // fold (ctlz_zero_undef c1) -> c2
4994   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4995     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4996   return SDValue();
4997 }
4998 
4999 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5000   SDValue N0 = N->getOperand(0);
5001   EVT VT = N->getValueType(0);
5002 
5003   // fold (cttz c1) -> c2
5004   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5005     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5006   return SDValue();
5007 }
5008 
5009 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5010   SDValue N0 = N->getOperand(0);
5011   EVT VT = N->getValueType(0);
5012 
5013   // fold (cttz_zero_undef c1) -> c2
5014   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5015     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5016   return SDValue();
5017 }
5018 
5019 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5020   SDValue N0 = N->getOperand(0);
5021   EVT VT = N->getValueType(0);
5022 
5023   // fold (ctpop c1) -> c2
5024   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5025     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5026   return SDValue();
5027 }
5028 
5029 
5030 /// \brief Generate Min/Max node
5031 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5032                                    SDValue True, SDValue False,
5033                                    ISD::CondCode CC, const TargetLowering &TLI,
5034                                    SelectionDAG &DAG) {
5035   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5036     return SDValue();
5037 
5038   switch (CC) {
5039   case ISD::SETOLT:
5040   case ISD::SETOLE:
5041   case ISD::SETLT:
5042   case ISD::SETLE:
5043   case ISD::SETULT:
5044   case ISD::SETULE: {
5045     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5046     if (TLI.isOperationLegal(Opcode, VT))
5047       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5048     return SDValue();
5049   }
5050   case ISD::SETOGT:
5051   case ISD::SETOGE:
5052   case ISD::SETGT:
5053   case ISD::SETGE:
5054   case ISD::SETUGT:
5055   case ISD::SETUGE: {
5056     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5057     if (TLI.isOperationLegal(Opcode, VT))
5058       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5059     return SDValue();
5060   }
5061   default:
5062     return SDValue();
5063   }
5064 }
5065 
5066 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5067   SDValue N0 = N->getOperand(0);
5068   SDValue N1 = N->getOperand(1);
5069   SDValue N2 = N->getOperand(2);
5070   EVT VT = N->getValueType(0);
5071   EVT VT0 = N0.getValueType();
5072 
5073   // fold (select C, X, X) -> X
5074   if (N1 == N2)
5075     return N1;
5076   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5077     // fold (select true, X, Y) -> X
5078     // fold (select false, X, Y) -> Y
5079     return !N0C->isNullValue() ? N1 : N2;
5080   }
5081   // fold (select C, 1, X) -> (or C, X)
5082   if (VT == MVT::i1 && isOneConstant(N1))
5083     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5084   // fold (select C, 0, 1) -> (xor C, 1)
5085   // We can't do this reliably if integer based booleans have different contents
5086   // to floating point based booleans. This is because we can't tell whether we
5087   // have an integer-based boolean or a floating-point-based boolean unless we
5088   // can find the SETCC that produced it and inspect its operands. This is
5089   // fairly easy if C is the SETCC node, but it can potentially be
5090   // undiscoverable (or not reasonably discoverable). For example, it could be
5091   // in another basic block or it could require searching a complicated
5092   // expression.
5093   if (VT.isInteger() &&
5094       (VT0 == MVT::i1 || (VT0.isInteger() &&
5095                           TLI.getBooleanContents(false, false) ==
5096                               TLI.getBooleanContents(false, true) &&
5097                           TLI.getBooleanContents(false, false) ==
5098                               TargetLowering::ZeroOrOneBooleanContent)) &&
5099       isNullConstant(N1) && isOneConstant(N2)) {
5100     SDValue XORNode;
5101     if (VT == VT0) {
5102       SDLoc DL(N);
5103       return DAG.getNode(ISD::XOR, DL, VT0,
5104                          N0, DAG.getConstant(1, DL, VT0));
5105     }
5106     SDLoc DL0(N0);
5107     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5108                           N0, DAG.getConstant(1, DL0, VT0));
5109     AddToWorklist(XORNode.getNode());
5110     if (VT.bitsGT(VT0))
5111       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5112     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5113   }
5114   // fold (select C, 0, X) -> (and (not C), X)
5115   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5116     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5117     AddToWorklist(NOTNode.getNode());
5118     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5119   }
5120   // fold (select C, X, 1) -> (or (not C), X)
5121   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5122     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5123     AddToWorklist(NOTNode.getNode());
5124     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5125   }
5126   // fold (select C, X, 0) -> (and C, X)
5127   if (VT == MVT::i1 && isNullConstant(N2))
5128     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5129   // fold (select X, X, Y) -> (or X, Y)
5130   // fold (select X, 1, Y) -> (or X, Y)
5131   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5132     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5133   // fold (select X, Y, X) -> (and X, Y)
5134   // fold (select X, Y, 0) -> (and X, Y)
5135   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5136     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5137 
5138   // If we can fold this based on the true/false value, do so.
5139   if (SimplifySelectOps(N, N1, N2))
5140     return SDValue(N, 0);  // Don't revisit N.
5141 
5142   if (VT0 == MVT::i1) {
5143     // The code in this block deals with the following 2 equivalences:
5144     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5145     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5146     // The target can specify its prefered form with the
5147     // shouldNormalizeToSelectSequence() callback. However we always transform
5148     // to the right anyway if we find the inner select exists in the DAG anyway
5149     // and we always transform to the left side if we know that we can further
5150     // optimize the combination of the conditions.
5151     bool normalizeToSequence
5152       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5153     // select (and Cond0, Cond1), X, Y
5154     //   -> select Cond0, (select Cond1, X, Y), Y
5155     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5156       SDValue Cond0 = N0->getOperand(0);
5157       SDValue Cond1 = N0->getOperand(1);
5158       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5159                                         N1.getValueType(), Cond1, N1, N2);
5160       if (normalizeToSequence || !InnerSelect.use_empty())
5161         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5162                            InnerSelect, N2);
5163     }
5164     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5165     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5166       SDValue Cond0 = N0->getOperand(0);
5167       SDValue Cond1 = N0->getOperand(1);
5168       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5169                                         N1.getValueType(), Cond1, N1, N2);
5170       if (normalizeToSequence || !InnerSelect.use_empty())
5171         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5172                            InnerSelect);
5173     }
5174 
5175     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5176     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5177       SDValue N1_0 = N1->getOperand(0);
5178       SDValue N1_1 = N1->getOperand(1);
5179       SDValue N1_2 = N1->getOperand(2);
5180       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5181         // Create the actual and node if we can generate good code for it.
5182         if (!normalizeToSequence) {
5183           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5184                                     N0, N1_0);
5185           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5186                              N1_1, N2);
5187         }
5188         // Otherwise see if we can optimize the "and" to a better pattern.
5189         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5190           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5191                              N1_1, N2);
5192       }
5193     }
5194     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5195     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5196       SDValue N2_0 = N2->getOperand(0);
5197       SDValue N2_1 = N2->getOperand(1);
5198       SDValue N2_2 = N2->getOperand(2);
5199       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5200         // Create the actual or node if we can generate good code for it.
5201         if (!normalizeToSequence) {
5202           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5203                                    N0, N2_0);
5204           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5205                              N1, N2_2);
5206         }
5207         // Otherwise see if we can optimize to a better pattern.
5208         if (SDValue Combined = visitORLike(N0, N2_0, N))
5209           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5210                              N1, N2_2);
5211       }
5212     }
5213   }
5214 
5215   // fold selects based on a setcc into other things, such as min/max/abs
5216   if (N0.getOpcode() == ISD::SETCC) {
5217     // select x, y (fcmp lt x, y) -> fminnum x, y
5218     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5219     //
5220     // This is OK if we don't care about what happens if either operand is a
5221     // NaN.
5222     //
5223 
5224     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5225     // no signed zeros as well as no nans.
5226     const TargetOptions &Options = DAG.getTarget().Options;
5227     if (Options.UnsafeFPMath &&
5228         VT.isFloatingPoint() && N0.hasOneUse() &&
5229         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5230       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5231 
5232       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5233                                                 N0.getOperand(1), N1, N2, CC,
5234                                                 TLI, DAG))
5235         return FMinMax;
5236     }
5237 
5238     if ((!LegalOperations &&
5239          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5240         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5241       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5242                          N0.getOperand(0), N0.getOperand(1),
5243                          N1, N2, N0.getOperand(2));
5244     return SimplifySelect(SDLoc(N), N0, N1, N2);
5245   }
5246 
5247   return SDValue();
5248 }
5249 
5250 static
5251 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5252   SDLoc DL(N);
5253   EVT LoVT, HiVT;
5254   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5255 
5256   // Split the inputs.
5257   SDValue Lo, Hi, LL, LH, RL, RH;
5258   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5259   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5260 
5261   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5262   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5263 
5264   return std::make_pair(Lo, Hi);
5265 }
5266 
5267 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5268 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5269 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5270   SDLoc dl(N);
5271   SDValue Cond = N->getOperand(0);
5272   SDValue LHS = N->getOperand(1);
5273   SDValue RHS = N->getOperand(2);
5274   EVT VT = N->getValueType(0);
5275   int NumElems = VT.getVectorNumElements();
5276   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5277          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5278          Cond.getOpcode() == ISD::BUILD_VECTOR);
5279 
5280   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5281   // binary ones here.
5282   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5283     return SDValue();
5284 
5285   // We're sure we have an even number of elements due to the
5286   // concat_vectors we have as arguments to vselect.
5287   // Skip BV elements until we find one that's not an UNDEF
5288   // After we find an UNDEF element, keep looping until we get to half the
5289   // length of the BV and see if all the non-undef nodes are the same.
5290   ConstantSDNode *BottomHalf = nullptr;
5291   for (int i = 0; i < NumElems / 2; ++i) {
5292     if (Cond->getOperand(i)->isUndef())
5293       continue;
5294 
5295     if (BottomHalf == nullptr)
5296       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5297     else if (Cond->getOperand(i).getNode() != BottomHalf)
5298       return SDValue();
5299   }
5300 
5301   // Do the same for the second half of the BuildVector
5302   ConstantSDNode *TopHalf = nullptr;
5303   for (int i = NumElems / 2; i < NumElems; ++i) {
5304     if (Cond->getOperand(i)->isUndef())
5305       continue;
5306 
5307     if (TopHalf == nullptr)
5308       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5309     else if (Cond->getOperand(i).getNode() != TopHalf)
5310       return SDValue();
5311   }
5312 
5313   assert(TopHalf && BottomHalf &&
5314          "One half of the selector was all UNDEFs and the other was all the "
5315          "same value. This should have been addressed before this function.");
5316   return DAG.getNode(
5317       ISD::CONCAT_VECTORS, dl, VT,
5318       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5319       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5320 }
5321 
5322 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5323 
5324   if (Level >= AfterLegalizeTypes)
5325     return SDValue();
5326 
5327   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5328   SDValue Mask = MSC->getMask();
5329   SDValue Data  = MSC->getValue();
5330   SDLoc DL(N);
5331 
5332   // If the MSCATTER data type requires splitting and the mask is provided by a
5333   // SETCC, then split both nodes and its operands before legalization. This
5334   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5335   // and enables future optimizations (e.g. min/max pattern matching on X86).
5336   if (Mask.getOpcode() != ISD::SETCC)
5337     return SDValue();
5338 
5339   // Check if any splitting is required.
5340   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5341       TargetLowering::TypeSplitVector)
5342     return SDValue();
5343   SDValue MaskLo, MaskHi, Lo, Hi;
5344   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5345 
5346   EVT LoVT, HiVT;
5347   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5348 
5349   SDValue Chain = MSC->getChain();
5350 
5351   EVT MemoryVT = MSC->getMemoryVT();
5352   unsigned Alignment = MSC->getOriginalAlignment();
5353 
5354   EVT LoMemVT, HiMemVT;
5355   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5356 
5357   SDValue DataLo, DataHi;
5358   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5359 
5360   SDValue BasePtr = MSC->getBasePtr();
5361   SDValue IndexLo, IndexHi;
5362   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5363 
5364   MachineMemOperand *MMO = DAG.getMachineFunction().
5365     getMachineMemOperand(MSC->getPointerInfo(),
5366                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5367                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5368 
5369   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5370   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5371                             DL, OpsLo, MMO);
5372 
5373   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5374   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5375                             DL, OpsHi, MMO);
5376 
5377   AddToWorklist(Lo.getNode());
5378   AddToWorklist(Hi.getNode());
5379 
5380   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5381 }
5382 
5383 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5384 
5385   if (Level >= AfterLegalizeTypes)
5386     return SDValue();
5387 
5388   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5389   SDValue Mask = MST->getMask();
5390   SDValue Data  = MST->getValue();
5391   SDLoc DL(N);
5392 
5393   // If the MSTORE data type requires splitting and the mask is provided by a
5394   // SETCC, then split both nodes and its operands before legalization. This
5395   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5396   // and enables future optimizations (e.g. min/max pattern matching on X86).
5397   if (Mask.getOpcode() == ISD::SETCC) {
5398 
5399     // Check if any splitting is required.
5400     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5401         TargetLowering::TypeSplitVector)
5402       return SDValue();
5403 
5404     SDValue MaskLo, MaskHi, Lo, Hi;
5405     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5406 
5407     EVT LoVT, HiVT;
5408     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5409 
5410     SDValue Chain = MST->getChain();
5411     SDValue Ptr   = MST->getBasePtr();
5412 
5413     EVT MemoryVT = MST->getMemoryVT();
5414     unsigned Alignment = MST->getOriginalAlignment();
5415 
5416     // if Alignment is equal to the vector size,
5417     // take the half of it for the second part
5418     unsigned SecondHalfAlignment =
5419       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5420          Alignment/2 : Alignment;
5421 
5422     EVT LoMemVT, HiMemVT;
5423     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5424 
5425     SDValue DataLo, DataHi;
5426     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5427 
5428     MachineMemOperand *MMO = DAG.getMachineFunction().
5429       getMachineMemOperand(MST->getPointerInfo(),
5430                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5431                            Alignment, MST->getAAInfo(), MST->getRanges());
5432 
5433     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5434                             MST->isTruncatingStore());
5435 
5436     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5437     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5438                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5439 
5440     MMO = DAG.getMachineFunction().
5441       getMachineMemOperand(MST->getPointerInfo(),
5442                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5443                            SecondHalfAlignment, MST->getAAInfo(),
5444                            MST->getRanges());
5445 
5446     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5447                             MST->isTruncatingStore());
5448 
5449     AddToWorklist(Lo.getNode());
5450     AddToWorklist(Hi.getNode());
5451 
5452     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5453   }
5454   return SDValue();
5455 }
5456 
5457 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5458 
5459   if (Level >= AfterLegalizeTypes)
5460     return SDValue();
5461 
5462   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5463   SDValue Mask = MGT->getMask();
5464   SDLoc DL(N);
5465 
5466   // If the MGATHER result requires splitting and the mask is provided by a
5467   // SETCC, then split both nodes and its operands before legalization. This
5468   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5469   // and enables future optimizations (e.g. min/max pattern matching on X86).
5470 
5471   if (Mask.getOpcode() != ISD::SETCC)
5472     return SDValue();
5473 
5474   EVT VT = N->getValueType(0);
5475 
5476   // Check if any splitting is required.
5477   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5478       TargetLowering::TypeSplitVector)
5479     return SDValue();
5480 
5481   SDValue MaskLo, MaskHi, Lo, Hi;
5482   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5483 
5484   SDValue Src0 = MGT->getValue();
5485   SDValue Src0Lo, Src0Hi;
5486   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5487 
5488   EVT LoVT, HiVT;
5489   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5490 
5491   SDValue Chain = MGT->getChain();
5492   EVT MemoryVT = MGT->getMemoryVT();
5493   unsigned Alignment = MGT->getOriginalAlignment();
5494 
5495   EVT LoMemVT, HiMemVT;
5496   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5497 
5498   SDValue BasePtr = MGT->getBasePtr();
5499   SDValue Index = MGT->getIndex();
5500   SDValue IndexLo, IndexHi;
5501   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5502 
5503   MachineMemOperand *MMO = DAG.getMachineFunction().
5504     getMachineMemOperand(MGT->getPointerInfo(),
5505                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5506                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5507 
5508   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5509   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5510                             MMO);
5511 
5512   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5513   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5514                             MMO);
5515 
5516   AddToWorklist(Lo.getNode());
5517   AddToWorklist(Hi.getNode());
5518 
5519   // Build a factor node to remember that this load is independent of the
5520   // other one.
5521   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5522                       Hi.getValue(1));
5523 
5524   // Legalized the chain result - switch anything that used the old chain to
5525   // use the new one.
5526   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5527 
5528   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5529 
5530   SDValue RetOps[] = { GatherRes, Chain };
5531   return DAG.getMergeValues(RetOps, DL);
5532 }
5533 
5534 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5535 
5536   if (Level >= AfterLegalizeTypes)
5537     return SDValue();
5538 
5539   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5540   SDValue Mask = MLD->getMask();
5541   SDLoc DL(N);
5542 
5543   // If the MLOAD result requires splitting and the mask is provided by a
5544   // SETCC, then split both nodes and its operands before legalization. This
5545   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5546   // and enables future optimizations (e.g. min/max pattern matching on X86).
5547 
5548   if (Mask.getOpcode() == ISD::SETCC) {
5549     EVT VT = N->getValueType(0);
5550 
5551     // Check if any splitting is required.
5552     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5553         TargetLowering::TypeSplitVector)
5554       return SDValue();
5555 
5556     SDValue MaskLo, MaskHi, Lo, Hi;
5557     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5558 
5559     SDValue Src0 = MLD->getSrc0();
5560     SDValue Src0Lo, Src0Hi;
5561     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5562 
5563     EVT LoVT, HiVT;
5564     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5565 
5566     SDValue Chain = MLD->getChain();
5567     SDValue Ptr   = MLD->getBasePtr();
5568     EVT MemoryVT = MLD->getMemoryVT();
5569     unsigned Alignment = MLD->getOriginalAlignment();
5570 
5571     // if Alignment is equal to the vector size,
5572     // take the half of it for the second part
5573     unsigned SecondHalfAlignment =
5574       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5575          Alignment/2 : Alignment;
5576 
5577     EVT LoMemVT, HiMemVT;
5578     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5579 
5580     MachineMemOperand *MMO = DAG.getMachineFunction().
5581     getMachineMemOperand(MLD->getPointerInfo(),
5582                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5583                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5584 
5585     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5586                            ISD::NON_EXTLOAD);
5587 
5588     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5589     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5590                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5591 
5592     MMO = DAG.getMachineFunction().
5593     getMachineMemOperand(MLD->getPointerInfo(),
5594                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5595                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5596 
5597     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5598                            ISD::NON_EXTLOAD);
5599 
5600     AddToWorklist(Lo.getNode());
5601     AddToWorklist(Hi.getNode());
5602 
5603     // Build a factor node to remember that this load is independent of the
5604     // other one.
5605     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5606                         Hi.getValue(1));
5607 
5608     // Legalized the chain result - switch anything that used the old chain to
5609     // use the new one.
5610     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5611 
5612     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5613 
5614     SDValue RetOps[] = { LoadRes, Chain };
5615     return DAG.getMergeValues(RetOps, DL);
5616   }
5617   return SDValue();
5618 }
5619 
5620 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5621   SDValue N0 = N->getOperand(0);
5622   SDValue N1 = N->getOperand(1);
5623   SDValue N2 = N->getOperand(2);
5624   SDLoc DL(N);
5625 
5626   // Canonicalize integer abs.
5627   // vselect (setg[te] X,  0),  X, -X ->
5628   // vselect (setgt    X, -1),  X, -X ->
5629   // vselect (setl[te] X,  0), -X,  X ->
5630   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5631   if (N0.getOpcode() == ISD::SETCC) {
5632     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5633     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5634     bool isAbs = false;
5635     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5636 
5637     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5638          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5639         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5640       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5641     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5642              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5643       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5644 
5645     if (isAbs) {
5646       EVT VT = LHS.getValueType();
5647       SDValue Shift = DAG.getNode(
5648           ISD::SRA, DL, VT, LHS,
5649           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5650       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5651       AddToWorklist(Shift.getNode());
5652       AddToWorklist(Add.getNode());
5653       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5654     }
5655   }
5656 
5657   if (SimplifySelectOps(N, N1, N2))
5658     return SDValue(N, 0);  // Don't revisit N.
5659 
5660   // If the VSELECT result requires splitting and the mask is provided by a
5661   // SETCC, then split both nodes and its operands before legalization. This
5662   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5663   // and enables future optimizations (e.g. min/max pattern matching on X86).
5664   if (N0.getOpcode() == ISD::SETCC) {
5665     EVT VT = N->getValueType(0);
5666 
5667     // Check if any splitting is required.
5668     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5669         TargetLowering::TypeSplitVector)
5670       return SDValue();
5671 
5672     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5673     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5674     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5675     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5676 
5677     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5678     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5679 
5680     // Add the new VSELECT nodes to the work list in case they need to be split
5681     // again.
5682     AddToWorklist(Lo.getNode());
5683     AddToWorklist(Hi.getNode());
5684 
5685     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5686   }
5687 
5688   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5689   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5690     return N1;
5691   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5692   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5693     return N2;
5694 
5695   // The ConvertSelectToConcatVector function is assuming both the above
5696   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5697   // and addressed.
5698   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5699       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5700       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5701     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5702       return CV;
5703   }
5704 
5705   return SDValue();
5706 }
5707 
5708 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5709   SDValue N0 = N->getOperand(0);
5710   SDValue N1 = N->getOperand(1);
5711   SDValue N2 = N->getOperand(2);
5712   SDValue N3 = N->getOperand(3);
5713   SDValue N4 = N->getOperand(4);
5714   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5715 
5716   // fold select_cc lhs, rhs, x, x, cc -> x
5717   if (N2 == N3)
5718     return N2;
5719 
5720   // Determine if the condition we're dealing with is constant
5721   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5722                                   CC, SDLoc(N), false)) {
5723     AddToWorklist(SCC.getNode());
5724 
5725     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5726       if (!SCCC->isNullValue())
5727         return N2;    // cond always true -> true val
5728       else
5729         return N3;    // cond always false -> false val
5730     } else if (SCC->isUndef()) {
5731       // When the condition is UNDEF, just return the first operand. This is
5732       // coherent the DAG creation, no setcc node is created in this case
5733       return N2;
5734     } else if (SCC.getOpcode() == ISD::SETCC) {
5735       // Fold to a simpler select_cc
5736       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5737                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5738                          SCC.getOperand(2));
5739     }
5740   }
5741 
5742   // If we can fold this based on the true/false value, do so.
5743   if (SimplifySelectOps(N, N2, N3))
5744     return SDValue(N, 0);  // Don't revisit N.
5745 
5746   // fold select_cc into other things, such as min/max/abs
5747   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5748 }
5749 
5750 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5751   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5752                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5753                        SDLoc(N));
5754 }
5755 
5756 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5757   SDValue LHS = N->getOperand(0);
5758   SDValue RHS = N->getOperand(1);
5759   SDValue Carry = N->getOperand(2);
5760   SDValue Cond = N->getOperand(3);
5761 
5762   // If Carry is false, fold to a regular SETCC.
5763   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5764     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5765 
5766   return SDValue();
5767 }
5768 
5769 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5770 /// a build_vector of constants.
5771 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5772 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5773 /// Vector extends are not folded if operations are legal; this is to
5774 /// avoid introducing illegal build_vector dag nodes.
5775 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5776                                          SelectionDAG &DAG, bool LegalTypes,
5777                                          bool LegalOperations) {
5778   unsigned Opcode = N->getOpcode();
5779   SDValue N0 = N->getOperand(0);
5780   EVT VT = N->getValueType(0);
5781 
5782   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5783          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5784          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5785          && "Expected EXTEND dag node in input!");
5786 
5787   // fold (sext c1) -> c1
5788   // fold (zext c1) -> c1
5789   // fold (aext c1) -> c1
5790   if (isa<ConstantSDNode>(N0))
5791     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5792 
5793   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5794   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5795   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5796   EVT SVT = VT.getScalarType();
5797   if (!(VT.isVector() &&
5798       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5799       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5800     return nullptr;
5801 
5802   // We can fold this node into a build_vector.
5803   unsigned VTBits = SVT.getSizeInBits();
5804   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5805   SmallVector<SDValue, 8> Elts;
5806   unsigned NumElts = VT.getVectorNumElements();
5807   SDLoc DL(N);
5808 
5809   for (unsigned i=0; i != NumElts; ++i) {
5810     SDValue Op = N0->getOperand(i);
5811     if (Op->isUndef()) {
5812       Elts.push_back(DAG.getUNDEF(SVT));
5813       continue;
5814     }
5815 
5816     SDLoc DL(Op);
5817     // Get the constant value and if needed trunc it to the size of the type.
5818     // Nodes like build_vector might have constants wider than the scalar type.
5819     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5820     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5821       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5822     else
5823       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5824   }
5825 
5826   return DAG.getBuildVector(VT, DL, Elts).getNode();
5827 }
5828 
5829 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5830 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5831 // transformation. Returns true if extension are possible and the above
5832 // mentioned transformation is profitable.
5833 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5834                                     unsigned ExtOpc,
5835                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5836                                     const TargetLowering &TLI) {
5837   bool HasCopyToRegUses = false;
5838   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5839   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5840                             UE = N0.getNode()->use_end();
5841        UI != UE; ++UI) {
5842     SDNode *User = *UI;
5843     if (User == N)
5844       continue;
5845     if (UI.getUse().getResNo() != N0.getResNo())
5846       continue;
5847     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5848     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5849       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5850       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5851         // Sign bits will be lost after a zext.
5852         return false;
5853       bool Add = false;
5854       for (unsigned i = 0; i != 2; ++i) {
5855         SDValue UseOp = User->getOperand(i);
5856         if (UseOp == N0)
5857           continue;
5858         if (!isa<ConstantSDNode>(UseOp))
5859           return false;
5860         Add = true;
5861       }
5862       if (Add)
5863         ExtendNodes.push_back(User);
5864       continue;
5865     }
5866     // If truncates aren't free and there are users we can't
5867     // extend, it isn't worthwhile.
5868     if (!isTruncFree)
5869       return false;
5870     // Remember if this value is live-out.
5871     if (User->getOpcode() == ISD::CopyToReg)
5872       HasCopyToRegUses = true;
5873   }
5874 
5875   if (HasCopyToRegUses) {
5876     bool BothLiveOut = false;
5877     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5878          UI != UE; ++UI) {
5879       SDUse &Use = UI.getUse();
5880       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5881         BothLiveOut = true;
5882         break;
5883       }
5884     }
5885     if (BothLiveOut)
5886       // Both unextended and extended values are live out. There had better be
5887       // a good reason for the transformation.
5888       return ExtendNodes.size();
5889   }
5890   return true;
5891 }
5892 
5893 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5894                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5895                                   ISD::NodeType ExtType) {
5896   // Extend SetCC uses if necessary.
5897   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5898     SDNode *SetCC = SetCCs[i];
5899     SmallVector<SDValue, 4> Ops;
5900 
5901     for (unsigned j = 0; j != 2; ++j) {
5902       SDValue SOp = SetCC->getOperand(j);
5903       if (SOp == Trunc)
5904         Ops.push_back(ExtLoad);
5905       else
5906         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5907     }
5908 
5909     Ops.push_back(SetCC->getOperand(2));
5910     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5911   }
5912 }
5913 
5914 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5915 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5916   SDValue N0 = N->getOperand(0);
5917   EVT DstVT = N->getValueType(0);
5918   EVT SrcVT = N0.getValueType();
5919 
5920   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5921           N->getOpcode() == ISD::ZERO_EXTEND) &&
5922          "Unexpected node type (not an extend)!");
5923 
5924   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5925   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5926   //   (v8i32 (sext (v8i16 (load x))))
5927   // into:
5928   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5929   //                          (v4i32 (sextload (x + 16)))))
5930   // Where uses of the original load, i.e.:
5931   //   (v8i16 (load x))
5932   // are replaced with:
5933   //   (v8i16 (truncate
5934   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5935   //                            (v4i32 (sextload (x + 16)))))))
5936   //
5937   // This combine is only applicable to illegal, but splittable, vectors.
5938   // All legal types, and illegal non-vector types, are handled elsewhere.
5939   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5940   //
5941   if (N0->getOpcode() != ISD::LOAD)
5942     return SDValue();
5943 
5944   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5945 
5946   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5947       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5948       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5949     return SDValue();
5950 
5951   SmallVector<SDNode *, 4> SetCCs;
5952   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5953     return SDValue();
5954 
5955   ISD::LoadExtType ExtType =
5956       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5957 
5958   // Try to split the vector types to get down to legal types.
5959   EVT SplitSrcVT = SrcVT;
5960   EVT SplitDstVT = DstVT;
5961   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5962          SplitSrcVT.getVectorNumElements() > 1) {
5963     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5964     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5965   }
5966 
5967   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5968     return SDValue();
5969 
5970   SDLoc DL(N);
5971   const unsigned NumSplits =
5972       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5973   const unsigned Stride = SplitSrcVT.getStoreSize();
5974   SmallVector<SDValue, 4> Loads;
5975   SmallVector<SDValue, 4> Chains;
5976 
5977   SDValue BasePtr = LN0->getBasePtr();
5978   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5979     const unsigned Offset = Idx * Stride;
5980     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5981 
5982     SDValue SplitLoad = DAG.getExtLoad(
5983         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5984         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5985         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5986         Align, LN0->getAAInfo());
5987 
5988     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5989                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5990 
5991     Loads.push_back(SplitLoad.getValue(0));
5992     Chains.push_back(SplitLoad.getValue(1));
5993   }
5994 
5995   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5996   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5997 
5998   CombineTo(N, NewValue);
5999 
6000   // Replace uses of the original load (before extension)
6001   // with a truncate of the concatenated sextloaded vectors.
6002   SDValue Trunc =
6003       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6004   CombineTo(N0.getNode(), Trunc, NewChain);
6005   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6006                   (ISD::NodeType)N->getOpcode());
6007   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6008 }
6009 
6010 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6011   SDValue N0 = N->getOperand(0);
6012   EVT VT = N->getValueType(0);
6013 
6014   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6015                                               LegalOperations))
6016     return SDValue(Res, 0);
6017 
6018   // fold (sext (sext x)) -> (sext x)
6019   // fold (sext (aext x)) -> (sext x)
6020   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6021     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6022                        N0.getOperand(0));
6023 
6024   if (N0.getOpcode() == ISD::TRUNCATE) {
6025     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6026     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6027     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6028       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6029       if (NarrowLoad.getNode() != N0.getNode()) {
6030         CombineTo(N0.getNode(), NarrowLoad);
6031         // CombineTo deleted the truncate, if needed, but not what's under it.
6032         AddToWorklist(oye);
6033       }
6034       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6035     }
6036 
6037     // See if the value being truncated is already sign extended.  If so, just
6038     // eliminate the trunc/sext pair.
6039     SDValue Op = N0.getOperand(0);
6040     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6041     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6042     unsigned DestBits = VT.getScalarType().getSizeInBits();
6043     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6044 
6045     if (OpBits == DestBits) {
6046       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6047       // bits, it is already ready.
6048       if (NumSignBits > DestBits-MidBits)
6049         return Op;
6050     } else if (OpBits < DestBits) {
6051       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6052       // bits, just sext from i32.
6053       if (NumSignBits > OpBits-MidBits)
6054         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6055     } else {
6056       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6057       // bits, just truncate to i32.
6058       if (NumSignBits > OpBits-MidBits)
6059         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6060     }
6061 
6062     // fold (sext (truncate x)) -> (sextinreg x).
6063     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6064                                                  N0.getValueType())) {
6065       if (OpBits < DestBits)
6066         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6067       else if (OpBits > DestBits)
6068         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6069       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6070                          DAG.getValueType(N0.getValueType()));
6071     }
6072   }
6073 
6074   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6075   // Only generate vector extloads when 1) they're legal, and 2) they are
6076   // deemed desirable by the target.
6077   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6078       ((!LegalOperations && !VT.isVector() &&
6079         !cast<LoadSDNode>(N0)->isVolatile()) ||
6080        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6081     bool DoXform = true;
6082     SmallVector<SDNode*, 4> SetCCs;
6083     if (!N0.hasOneUse())
6084       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6085     if (VT.isVector())
6086       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6087     if (DoXform) {
6088       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6089       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6090                                        LN0->getChain(),
6091                                        LN0->getBasePtr(), N0.getValueType(),
6092                                        LN0->getMemOperand());
6093       CombineTo(N, ExtLoad);
6094       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6095                                   N0.getValueType(), ExtLoad);
6096       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6097       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6098                       ISD::SIGN_EXTEND);
6099       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6100     }
6101   }
6102 
6103   // fold (sext (load x)) to multiple smaller sextloads.
6104   // Only on illegal but splittable vectors.
6105   if (SDValue ExtLoad = CombineExtLoad(N))
6106     return ExtLoad;
6107 
6108   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6109   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6110   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6111       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6112     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6113     EVT MemVT = LN0->getMemoryVT();
6114     if ((!LegalOperations && !LN0->isVolatile()) ||
6115         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6116       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6117                                        LN0->getChain(),
6118                                        LN0->getBasePtr(), MemVT,
6119                                        LN0->getMemOperand());
6120       CombineTo(N, ExtLoad);
6121       CombineTo(N0.getNode(),
6122                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6123                             N0.getValueType(), ExtLoad),
6124                 ExtLoad.getValue(1));
6125       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6126     }
6127   }
6128 
6129   // fold (sext (and/or/xor (load x), cst)) ->
6130   //      (and/or/xor (sextload x), (sext cst))
6131   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6132        N0.getOpcode() == ISD::XOR) &&
6133       isa<LoadSDNode>(N0.getOperand(0)) &&
6134       N0.getOperand(1).getOpcode() == ISD::Constant &&
6135       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6136       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6137     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6138     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6139       bool DoXform = true;
6140       SmallVector<SDNode*, 4> SetCCs;
6141       if (!N0.hasOneUse())
6142         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6143                                           SetCCs, TLI);
6144       if (DoXform) {
6145         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6146                                          LN0->getChain(), LN0->getBasePtr(),
6147                                          LN0->getMemoryVT(),
6148                                          LN0->getMemOperand());
6149         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6150         Mask = Mask.sext(VT.getSizeInBits());
6151         SDLoc DL(N);
6152         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6153                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6154         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6155                                     SDLoc(N0.getOperand(0)),
6156                                     N0.getOperand(0).getValueType(), ExtLoad);
6157         CombineTo(N, And);
6158         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6159         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6160                         ISD::SIGN_EXTEND);
6161         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6162       }
6163     }
6164   }
6165 
6166   if (N0.getOpcode() == ISD::SETCC) {
6167     EVT N0VT = N0.getOperand(0).getValueType();
6168     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6169     // Only do this before legalize for now.
6170     if (VT.isVector() && !LegalOperations &&
6171         TLI.getBooleanContents(N0VT) ==
6172             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6173       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6174       // of the same size as the compared operands. Only optimize sext(setcc())
6175       // if this is the case.
6176       EVT SVT = getSetCCResultType(N0VT);
6177 
6178       // We know that the # elements of the results is the same as the
6179       // # elements of the compare (and the # elements of the compare result
6180       // for that matter).  Check to see that they are the same size.  If so,
6181       // we know that the element size of the sext'd result matches the
6182       // element size of the compare operands.
6183       if (VT.getSizeInBits() == SVT.getSizeInBits())
6184         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6185                              N0.getOperand(1),
6186                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6187 
6188       // If the desired elements are smaller or larger than the source
6189       // elements we can use a matching integer vector type and then
6190       // truncate/sign extend
6191       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6192       if (SVT == MatchingVectorType) {
6193         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6194                                N0.getOperand(0), N0.getOperand(1),
6195                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6196         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6197       }
6198     }
6199 
6200     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6201     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6202     SDLoc DL(N);
6203     SDValue NegOne =
6204       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6205     if (SDValue SCC = SimplifySelectCC(
6206             DL, N0.getOperand(0), N0.getOperand(1), NegOne,
6207             DAG.getConstant(0, DL, VT),
6208             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6209       return SCC;
6210 
6211     if (!VT.isVector()) {
6212       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6213       if (!LegalOperations ||
6214           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6215         SDLoc DL(N);
6216         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6217         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6218                                      N0.getOperand(0), N0.getOperand(1), CC);
6219         return DAG.getSelect(DL, VT, SetCC,
6220                              NegOne, DAG.getConstant(0, DL, VT));
6221       }
6222     }
6223   }
6224 
6225   // fold (sext x) -> (zext x) if the sign bit is known zero.
6226   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6227       DAG.SignBitIsZero(N0))
6228     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6229 
6230   return SDValue();
6231 }
6232 
6233 // isTruncateOf - If N is a truncate of some other value, return true, record
6234 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6235 // This function computes KnownZero to avoid a duplicated call to
6236 // computeKnownBits in the caller.
6237 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6238                          APInt &KnownZero) {
6239   APInt KnownOne;
6240   if (N->getOpcode() == ISD::TRUNCATE) {
6241     Op = N->getOperand(0);
6242     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6243     return true;
6244   }
6245 
6246   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6247       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6248     return false;
6249 
6250   SDValue Op0 = N->getOperand(0);
6251   SDValue Op1 = N->getOperand(1);
6252   assert(Op0.getValueType() == Op1.getValueType());
6253 
6254   if (isNullConstant(Op0))
6255     Op = Op1;
6256   else if (isNullConstant(Op1))
6257     Op = Op0;
6258   else
6259     return false;
6260 
6261   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6262 
6263   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6264     return false;
6265 
6266   return true;
6267 }
6268 
6269 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6270   SDValue N0 = N->getOperand(0);
6271   EVT VT = N->getValueType(0);
6272 
6273   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6274                                               LegalOperations))
6275     return SDValue(Res, 0);
6276 
6277   // fold (zext (zext x)) -> (zext x)
6278   // fold (zext (aext x)) -> (zext x)
6279   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6280     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6281                        N0.getOperand(0));
6282 
6283   // fold (zext (truncate x)) -> (zext x) or
6284   //      (zext (truncate x)) -> (truncate x)
6285   // This is valid when the truncated bits of x are already zero.
6286   // FIXME: We should extend this to work for vectors too.
6287   SDValue Op;
6288   APInt KnownZero;
6289   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6290     APInt TruncatedBits =
6291       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6292       APInt(Op.getValueSizeInBits(), 0) :
6293       APInt::getBitsSet(Op.getValueSizeInBits(),
6294                         N0.getValueSizeInBits(),
6295                         std::min(Op.getValueSizeInBits(),
6296                                  VT.getSizeInBits()));
6297     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6298       if (VT.bitsGT(Op.getValueType()))
6299         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6300       if (VT.bitsLT(Op.getValueType()))
6301         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6302 
6303       return Op;
6304     }
6305   }
6306 
6307   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6308   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6309   if (N0.getOpcode() == ISD::TRUNCATE) {
6310     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6311       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6312       if (NarrowLoad.getNode() != N0.getNode()) {
6313         CombineTo(N0.getNode(), NarrowLoad);
6314         // CombineTo deleted the truncate, if needed, but not what's under it.
6315         AddToWorklist(oye);
6316       }
6317       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6318     }
6319   }
6320 
6321   // fold (zext (truncate x)) -> (and x, mask)
6322   if (N0.getOpcode() == ISD::TRUNCATE) {
6323     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6324     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6325     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6326       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6327       if (NarrowLoad.getNode() != N0.getNode()) {
6328         CombineTo(N0.getNode(), NarrowLoad);
6329         // CombineTo deleted the truncate, if needed, but not what's under it.
6330         AddToWorklist(oye);
6331       }
6332       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6333     }
6334 
6335     EVT SrcVT = N0.getOperand(0).getValueType();
6336     EVT MinVT = N0.getValueType();
6337 
6338     // Try to mask before the extension to avoid having to generate a larger mask,
6339     // possibly over several sub-vectors.
6340     if (SrcVT.bitsLT(VT)) {
6341       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6342                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6343         SDValue Op = N0.getOperand(0);
6344         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6345         AddToWorklist(Op.getNode());
6346         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6347       }
6348     }
6349 
6350     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6351       SDValue Op = N0.getOperand(0);
6352       if (SrcVT.bitsLT(VT)) {
6353         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6354         AddToWorklist(Op.getNode());
6355       } else if (SrcVT.bitsGT(VT)) {
6356         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6357         AddToWorklist(Op.getNode());
6358       }
6359       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6360     }
6361   }
6362 
6363   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6364   // if either of the casts is not free.
6365   if (N0.getOpcode() == ISD::AND &&
6366       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6367       N0.getOperand(1).getOpcode() == ISD::Constant &&
6368       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6369                            N0.getValueType()) ||
6370        !TLI.isZExtFree(N0.getValueType(), VT))) {
6371     SDValue X = N0.getOperand(0).getOperand(0);
6372     if (X.getValueType().bitsLT(VT)) {
6373       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6374     } else if (X.getValueType().bitsGT(VT)) {
6375       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6376     }
6377     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6378     Mask = Mask.zext(VT.getSizeInBits());
6379     SDLoc DL(N);
6380     return DAG.getNode(ISD::AND, DL, VT,
6381                        X, DAG.getConstant(Mask, DL, VT));
6382   }
6383 
6384   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6385   // Only generate vector extloads when 1) they're legal, and 2) they are
6386   // deemed desirable by the target.
6387   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6388       ((!LegalOperations && !VT.isVector() &&
6389         !cast<LoadSDNode>(N0)->isVolatile()) ||
6390        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6391     bool DoXform = true;
6392     SmallVector<SDNode*, 4> SetCCs;
6393     if (!N0.hasOneUse())
6394       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6395     if (VT.isVector())
6396       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6397     if (DoXform) {
6398       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6399       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6400                                        LN0->getChain(),
6401                                        LN0->getBasePtr(), N0.getValueType(),
6402                                        LN0->getMemOperand());
6403       CombineTo(N, ExtLoad);
6404       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6405                                   N0.getValueType(), ExtLoad);
6406       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6407 
6408       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6409                       ISD::ZERO_EXTEND);
6410       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6411     }
6412   }
6413 
6414   // fold (zext (load x)) to multiple smaller zextloads.
6415   // Only on illegal but splittable vectors.
6416   if (SDValue ExtLoad = CombineExtLoad(N))
6417     return ExtLoad;
6418 
6419   // fold (zext (and/or/xor (load x), cst)) ->
6420   //      (and/or/xor (zextload x), (zext cst))
6421   // Unless (and (load x) cst) will match as a zextload already and has
6422   // additional users.
6423   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6424        N0.getOpcode() == ISD::XOR) &&
6425       isa<LoadSDNode>(N0.getOperand(0)) &&
6426       N0.getOperand(1).getOpcode() == ISD::Constant &&
6427       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6428       (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) {
6429     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6430     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6431       bool DoXform = true;
6432       SmallVector<SDNode*, 4> SetCCs;
6433       if (!N0.hasOneUse()) {
6434         if (N0.getOpcode() == ISD::AND) {
6435           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6436           auto NarrowLoad = false;
6437           EVT LoadResultTy = AndC->getValueType(0);
6438           EVT ExtVT, LoadedVT;
6439           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6440                                NarrowLoad))
6441             DoXform = false;
6442         }
6443         if (DoXform)
6444           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6445                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6446       }
6447       if (DoXform) {
6448         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6449                                          LN0->getChain(), LN0->getBasePtr(),
6450                                          LN0->getMemoryVT(),
6451                                          LN0->getMemOperand());
6452         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6453         Mask = Mask.zext(VT.getSizeInBits());
6454         SDLoc DL(N);
6455         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6456                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6457         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6458                                     SDLoc(N0.getOperand(0)),
6459                                     N0.getOperand(0).getValueType(), ExtLoad);
6460         CombineTo(N, And);
6461         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6462         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6463                         ISD::ZERO_EXTEND);
6464         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6465       }
6466     }
6467   }
6468 
6469   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6470   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6471   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6472       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6473     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6474     EVT MemVT = LN0->getMemoryVT();
6475     if ((!LegalOperations && !LN0->isVolatile()) ||
6476         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6477       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6478                                        LN0->getChain(),
6479                                        LN0->getBasePtr(), MemVT,
6480                                        LN0->getMemOperand());
6481       CombineTo(N, ExtLoad);
6482       CombineTo(N0.getNode(),
6483                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6484                             ExtLoad),
6485                 ExtLoad.getValue(1));
6486       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6487     }
6488   }
6489 
6490   if (N0.getOpcode() == ISD::SETCC) {
6491     if (!LegalOperations && VT.isVector() &&
6492         N0.getValueType().getVectorElementType() == MVT::i1) {
6493       EVT N0VT = N0.getOperand(0).getValueType();
6494       if (getSetCCResultType(N0VT) == N0.getValueType())
6495         return SDValue();
6496 
6497       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6498       // Only do this before legalize for now.
6499       SDLoc DL(N);
6500       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6501       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6502         // We know that the # elements of the results is the same as the
6503         // # elements of the compare (and the # elements of the compare result
6504         // for that matter).  Check to see that they are the same size.  If so,
6505         // we know that the element size of the sext'd result matches the
6506         // element size of the compare operands.
6507         return DAG.getNode(ISD::AND, DL, VT,
6508                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6509                                          N0.getOperand(1),
6510                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6511                            VecOnes);
6512 
6513       // If the desired elements are smaller or larger than the source
6514       // elements we can use a matching integer vector type and then
6515       // truncate/sign extend
6516       EVT MatchingElementType =
6517         EVT::getIntegerVT(*DAG.getContext(),
6518                           N0VT.getScalarType().getSizeInBits());
6519       EVT MatchingVectorType =
6520         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6521                          N0VT.getVectorNumElements());
6522       SDValue VsetCC =
6523         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6524                       N0.getOperand(1),
6525                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6526       return DAG.getNode(ISD::AND, DL, VT,
6527                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6528                          VecOnes);
6529     }
6530 
6531     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6532     SDLoc DL(N);
6533     if (SDValue SCC = SimplifySelectCC(
6534             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6535             DAG.getConstant(0, DL, VT),
6536             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6537       return SCC;
6538   }
6539 
6540   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6541   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6542       isa<ConstantSDNode>(N0.getOperand(1)) &&
6543       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6544       N0.hasOneUse()) {
6545     SDValue ShAmt = N0.getOperand(1);
6546     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6547     if (N0.getOpcode() == ISD::SHL) {
6548       SDValue InnerZExt = N0.getOperand(0);
6549       // If the original shl may be shifting out bits, do not perform this
6550       // transformation.
6551       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6552         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6553       if (ShAmtVal > KnownZeroBits)
6554         return SDValue();
6555     }
6556 
6557     SDLoc DL(N);
6558 
6559     // Ensure that the shift amount is wide enough for the shifted value.
6560     if (VT.getSizeInBits() >= 256)
6561       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6562 
6563     return DAG.getNode(N0.getOpcode(), DL, VT,
6564                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6565                        ShAmt);
6566   }
6567 
6568   return SDValue();
6569 }
6570 
6571 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6572   SDValue N0 = N->getOperand(0);
6573   EVT VT = N->getValueType(0);
6574 
6575   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6576                                               LegalOperations))
6577     return SDValue(Res, 0);
6578 
6579   // fold (aext (aext x)) -> (aext x)
6580   // fold (aext (zext x)) -> (zext x)
6581   // fold (aext (sext x)) -> (sext x)
6582   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6583       N0.getOpcode() == ISD::ZERO_EXTEND ||
6584       N0.getOpcode() == ISD::SIGN_EXTEND)
6585     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6586 
6587   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6588   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6589   if (N0.getOpcode() == ISD::TRUNCATE) {
6590     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6591       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6592       if (NarrowLoad.getNode() != N0.getNode()) {
6593         CombineTo(N0.getNode(), NarrowLoad);
6594         // CombineTo deleted the truncate, if needed, but not what's under it.
6595         AddToWorklist(oye);
6596       }
6597       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6598     }
6599   }
6600 
6601   // fold (aext (truncate x))
6602   if (N0.getOpcode() == ISD::TRUNCATE) {
6603     SDValue TruncOp = N0.getOperand(0);
6604     if (TruncOp.getValueType() == VT)
6605       return TruncOp; // x iff x size == zext size.
6606     if (TruncOp.getValueType().bitsGT(VT))
6607       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6608     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6609   }
6610 
6611   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6612   // if the trunc is not free.
6613   if (N0.getOpcode() == ISD::AND &&
6614       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6615       N0.getOperand(1).getOpcode() == ISD::Constant &&
6616       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6617                           N0.getValueType())) {
6618     SDValue X = N0.getOperand(0).getOperand(0);
6619     if (X.getValueType().bitsLT(VT)) {
6620       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6621     } else if (X.getValueType().bitsGT(VT)) {
6622       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6623     }
6624     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6625     Mask = Mask.zext(VT.getSizeInBits());
6626     SDLoc DL(N);
6627     return DAG.getNode(ISD::AND, DL, VT,
6628                        X, DAG.getConstant(Mask, DL, VT));
6629   }
6630 
6631   // fold (aext (load x)) -> (aext (truncate (extload x)))
6632   // None of the supported targets knows how to perform load and any_ext
6633   // on vectors in one instruction.  We only perform this transformation on
6634   // scalars.
6635   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6636       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6637       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6638     bool DoXform = true;
6639     SmallVector<SDNode*, 4> SetCCs;
6640     if (!N0.hasOneUse())
6641       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6642     if (DoXform) {
6643       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6644       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6645                                        LN0->getChain(),
6646                                        LN0->getBasePtr(), N0.getValueType(),
6647                                        LN0->getMemOperand());
6648       CombineTo(N, ExtLoad);
6649       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6650                                   N0.getValueType(), ExtLoad);
6651       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6652       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6653                       ISD::ANY_EXTEND);
6654       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6655     }
6656   }
6657 
6658   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6659   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6660   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6661   if (N0.getOpcode() == ISD::LOAD &&
6662       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6663       N0.hasOneUse()) {
6664     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6665     ISD::LoadExtType ExtType = LN0->getExtensionType();
6666     EVT MemVT = LN0->getMemoryVT();
6667     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6668       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6669                                        VT, LN0->getChain(), LN0->getBasePtr(),
6670                                        MemVT, LN0->getMemOperand());
6671       CombineTo(N, ExtLoad);
6672       CombineTo(N0.getNode(),
6673                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6674                             N0.getValueType(), ExtLoad),
6675                 ExtLoad.getValue(1));
6676       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6677     }
6678   }
6679 
6680   if (N0.getOpcode() == ISD::SETCC) {
6681     // For vectors:
6682     // aext(setcc) -> vsetcc
6683     // aext(setcc) -> truncate(vsetcc)
6684     // aext(setcc) -> aext(vsetcc)
6685     // Only do this before legalize for now.
6686     if (VT.isVector() && !LegalOperations) {
6687       EVT N0VT = N0.getOperand(0).getValueType();
6688         // We know that the # elements of the results is the same as the
6689         // # elements of the compare (and the # elements of the compare result
6690         // for that matter).  Check to see that they are the same size.  If so,
6691         // we know that the element size of the sext'd result matches the
6692         // element size of the compare operands.
6693       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6694         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6695                              N0.getOperand(1),
6696                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6697       // If the desired elements are smaller or larger than the source
6698       // elements we can use a matching integer vector type and then
6699       // truncate/any extend
6700       else {
6701         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6702         SDValue VsetCC =
6703           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6704                         N0.getOperand(1),
6705                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6706         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6707       }
6708     }
6709 
6710     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6711     SDLoc DL(N);
6712     if (SDValue SCC = SimplifySelectCC(
6713             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6714             DAG.getConstant(0, DL, VT),
6715             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6716       return SCC;
6717   }
6718 
6719   return SDValue();
6720 }
6721 
6722 /// See if the specified operand can be simplified with the knowledge that only
6723 /// the bits specified by Mask are used.  If so, return the simpler operand,
6724 /// otherwise return a null SDValue.
6725 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6726   switch (V.getOpcode()) {
6727   default: break;
6728   case ISD::Constant: {
6729     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6730     assert(CV && "Const value should be ConstSDNode.");
6731     const APInt &CVal = CV->getAPIntValue();
6732     APInt NewVal = CVal & Mask;
6733     if (NewVal != CVal)
6734       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6735     break;
6736   }
6737   case ISD::OR:
6738   case ISD::XOR:
6739     // If the LHS or RHS don't contribute bits to the or, drop them.
6740     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6741       return V.getOperand(1);
6742     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6743       return V.getOperand(0);
6744     break;
6745   case ISD::SRL:
6746     // Only look at single-use SRLs.
6747     if (!V.getNode()->hasOneUse())
6748       break;
6749     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6750       // See if we can recursively simplify the LHS.
6751       unsigned Amt = RHSC->getZExtValue();
6752 
6753       // Watch out for shift count overflow though.
6754       if (Amt >= Mask.getBitWidth()) break;
6755       APInt NewMask = Mask << Amt;
6756       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6757         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6758                            SimplifyLHS, V.getOperand(1));
6759     }
6760   }
6761   return SDValue();
6762 }
6763 
6764 /// If the result of a wider load is shifted to right of N  bits and then
6765 /// truncated to a narrower type and where N is a multiple of number of bits of
6766 /// the narrower type, transform it to a narrower load from address + N / num of
6767 /// bits of new type. If the result is to be extended, also fold the extension
6768 /// to form a extending load.
6769 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6770   unsigned Opc = N->getOpcode();
6771 
6772   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6773   SDValue N0 = N->getOperand(0);
6774   EVT VT = N->getValueType(0);
6775   EVT ExtVT = VT;
6776 
6777   // This transformation isn't valid for vector loads.
6778   if (VT.isVector())
6779     return SDValue();
6780 
6781   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6782   // extended to VT.
6783   if (Opc == ISD::SIGN_EXTEND_INREG) {
6784     ExtType = ISD::SEXTLOAD;
6785     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6786   } else if (Opc == ISD::SRL) {
6787     // Another special-case: SRL is basically zero-extending a narrower value.
6788     ExtType = ISD::ZEXTLOAD;
6789     N0 = SDValue(N, 0);
6790     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6791     if (!N01) return SDValue();
6792     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6793                               VT.getSizeInBits() - N01->getZExtValue());
6794   }
6795   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6796     return SDValue();
6797 
6798   unsigned EVTBits = ExtVT.getSizeInBits();
6799 
6800   // Do not generate loads of non-round integer types since these can
6801   // be expensive (and would be wrong if the type is not byte sized).
6802   if (!ExtVT.isRound())
6803     return SDValue();
6804 
6805   unsigned ShAmt = 0;
6806   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6807     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6808       ShAmt = N01->getZExtValue();
6809       // Is the shift amount a multiple of size of VT?
6810       if ((ShAmt & (EVTBits-1)) == 0) {
6811         N0 = N0.getOperand(0);
6812         // Is the load width a multiple of size of VT?
6813         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6814           return SDValue();
6815       }
6816 
6817       // At this point, we must have a load or else we can't do the transform.
6818       if (!isa<LoadSDNode>(N0)) return SDValue();
6819 
6820       // Because a SRL must be assumed to *need* to zero-extend the high bits
6821       // (as opposed to anyext the high bits), we can't combine the zextload
6822       // lowering of SRL and an sextload.
6823       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6824         return SDValue();
6825 
6826       // If the shift amount is larger than the input type then we're not
6827       // accessing any of the loaded bytes.  If the load was a zextload/extload
6828       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6829       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6830         return SDValue();
6831     }
6832   }
6833 
6834   // If the load is shifted left (and the result isn't shifted back right),
6835   // we can fold the truncate through the shift.
6836   unsigned ShLeftAmt = 0;
6837   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6838       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6839     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6840       ShLeftAmt = N01->getZExtValue();
6841       N0 = N0.getOperand(0);
6842     }
6843   }
6844 
6845   // If we haven't found a load, we can't narrow it.  Don't transform one with
6846   // multiple uses, this would require adding a new load.
6847   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6848     return SDValue();
6849 
6850   // Don't change the width of a volatile load.
6851   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6852   if (LN0->isVolatile())
6853     return SDValue();
6854 
6855   // Verify that we are actually reducing a load width here.
6856   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6857     return SDValue();
6858 
6859   // For the transform to be legal, the load must produce only two values
6860   // (the value loaded and the chain).  Don't transform a pre-increment
6861   // load, for example, which produces an extra value.  Otherwise the
6862   // transformation is not equivalent, and the downstream logic to replace
6863   // uses gets things wrong.
6864   if (LN0->getNumValues() > 2)
6865     return SDValue();
6866 
6867   // If the load that we're shrinking is an extload and we're not just
6868   // discarding the extension we can't simply shrink the load. Bail.
6869   // TODO: It would be possible to merge the extensions in some cases.
6870   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6871       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6872     return SDValue();
6873 
6874   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6875     return SDValue();
6876 
6877   EVT PtrType = N0.getOperand(1).getValueType();
6878 
6879   if (PtrType == MVT::Untyped || PtrType.isExtended())
6880     // It's not possible to generate a constant of extended or untyped type.
6881     return SDValue();
6882 
6883   // For big endian targets, we need to adjust the offset to the pointer to
6884   // load the correct bytes.
6885   if (DAG.getDataLayout().isBigEndian()) {
6886     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6887     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6888     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6889   }
6890 
6891   uint64_t PtrOff = ShAmt / 8;
6892   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6893   SDLoc DL(LN0);
6894   // The original load itself didn't wrap, so an offset within it doesn't.
6895   SDNodeFlags Flags;
6896   Flags.setNoUnsignedWrap(true);
6897   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6898                                PtrType, LN0->getBasePtr(),
6899                                DAG.getConstant(PtrOff, DL, PtrType),
6900                                &Flags);
6901   AddToWorklist(NewPtr.getNode());
6902 
6903   SDValue Load;
6904   if (ExtType == ISD::NON_EXTLOAD)
6905     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6906                         LN0->getPointerInfo().getWithOffset(PtrOff),
6907                         LN0->isVolatile(), LN0->isNonTemporal(),
6908                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6909   else
6910     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6911                           LN0->getPointerInfo().getWithOffset(PtrOff),
6912                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6913                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6914 
6915   // Replace the old load's chain with the new load's chain.
6916   WorklistRemover DeadNodes(*this);
6917   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6918 
6919   // Shift the result left, if we've swallowed a left shift.
6920   SDValue Result = Load;
6921   if (ShLeftAmt != 0) {
6922     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6923     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6924       ShImmTy = VT;
6925     // If the shift amount is as large as the result size (but, presumably,
6926     // no larger than the source) then the useful bits of the result are
6927     // zero; we can't simply return the shortened shift, because the result
6928     // of that operation is undefined.
6929     SDLoc DL(N0);
6930     if (ShLeftAmt >= VT.getSizeInBits())
6931       Result = DAG.getConstant(0, DL, VT);
6932     else
6933       Result = DAG.getNode(ISD::SHL, DL, VT,
6934                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6935   }
6936 
6937   // Return the new loaded value.
6938   return Result;
6939 }
6940 
6941 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6942   SDValue N0 = N->getOperand(0);
6943   SDValue N1 = N->getOperand(1);
6944   EVT VT = N->getValueType(0);
6945   EVT EVT = cast<VTSDNode>(N1)->getVT();
6946   unsigned VTBits = VT.getScalarType().getSizeInBits();
6947   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6948 
6949   if (N0.isUndef())
6950     return DAG.getUNDEF(VT);
6951 
6952   // fold (sext_in_reg c1) -> c1
6953   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6954     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6955 
6956   // If the input is already sign extended, just drop the extension.
6957   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6958     return N0;
6959 
6960   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6961   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6962       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6963     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6964                        N0.getOperand(0), N1);
6965 
6966   // fold (sext_in_reg (sext x)) -> (sext x)
6967   // fold (sext_in_reg (aext x)) -> (sext x)
6968   // if x is small enough.
6969   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6970     SDValue N00 = N0.getOperand(0);
6971     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6972         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6973       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6974   }
6975 
6976   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6977   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6978     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6979 
6980   // fold operands of sext_in_reg based on knowledge that the top bits are not
6981   // demanded.
6982   if (SimplifyDemandedBits(SDValue(N, 0)))
6983     return SDValue(N, 0);
6984 
6985   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6986   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6987   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6988     return NarrowLoad;
6989 
6990   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6991   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6992   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6993   if (N0.getOpcode() == ISD::SRL) {
6994     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6995       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6996         // We can turn this into an SRA iff the input to the SRL is already sign
6997         // extended enough.
6998         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6999         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7000           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7001                              N0.getOperand(0), N0.getOperand(1));
7002       }
7003   }
7004 
7005   // fold (sext_inreg (extload x)) -> (sextload x)
7006   if (ISD::isEXTLoad(N0.getNode()) &&
7007       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7008       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7009       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7010        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7011     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7012     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7013                                      LN0->getChain(),
7014                                      LN0->getBasePtr(), EVT,
7015                                      LN0->getMemOperand());
7016     CombineTo(N, ExtLoad);
7017     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7018     AddToWorklist(ExtLoad.getNode());
7019     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7020   }
7021   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7022   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7023       N0.hasOneUse() &&
7024       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7025       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7026        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7027     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7028     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7029                                      LN0->getChain(),
7030                                      LN0->getBasePtr(), EVT,
7031                                      LN0->getMemOperand());
7032     CombineTo(N, ExtLoad);
7033     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7034     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7035   }
7036 
7037   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7038   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7039     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7040                                            N0.getOperand(1), false))
7041       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7042                          BSwap, N1);
7043   }
7044 
7045   return SDValue();
7046 }
7047 
7048 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7049   SDValue N0 = N->getOperand(0);
7050   EVT VT = N->getValueType(0);
7051 
7052   if (N0.isUndef())
7053     return DAG.getUNDEF(VT);
7054 
7055   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7056                                               LegalOperations))
7057     return SDValue(Res, 0);
7058 
7059   return SDValue();
7060 }
7061 
7062 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7063   SDValue N0 = N->getOperand(0);
7064   EVT VT = N->getValueType(0);
7065 
7066   if (N0.isUndef())
7067     return DAG.getUNDEF(VT);
7068 
7069   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7070                                               LegalOperations))
7071     return SDValue(Res, 0);
7072 
7073   return SDValue();
7074 }
7075 
7076 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7077   SDValue N0 = N->getOperand(0);
7078   EVT VT = N->getValueType(0);
7079   bool isLE = DAG.getDataLayout().isLittleEndian();
7080 
7081   // noop truncate
7082   if (N0.getValueType() == N->getValueType(0))
7083     return N0;
7084   // fold (truncate c1) -> c1
7085   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7086     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7087   // fold (truncate (truncate x)) -> (truncate x)
7088   if (N0.getOpcode() == ISD::TRUNCATE)
7089     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7090   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7091   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7092       N0.getOpcode() == ISD::SIGN_EXTEND ||
7093       N0.getOpcode() == ISD::ANY_EXTEND) {
7094     // if the source is smaller than the dest, we still need an extend.
7095     if (N0.getOperand(0).getValueType().bitsLT(VT))
7096       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7097     // if the source is larger than the dest, than we just need the truncate.
7098     if (N0.getOperand(0).getValueType().bitsGT(VT))
7099       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7100     // if the source and dest are the same type, we can drop both the extend
7101     // and the truncate.
7102     return N0.getOperand(0);
7103   }
7104 
7105   // Fold extract-and-trunc into a narrow extract. For example:
7106   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7107   //   i32 y = TRUNCATE(i64 x)
7108   //        -- becomes --
7109   //   v16i8 b = BITCAST (v2i64 val)
7110   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7111   //
7112   // Note: We only run this optimization after type legalization (which often
7113   // creates this pattern) and before operation legalization after which
7114   // we need to be more careful about the vector instructions that we generate.
7115   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7116       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7117 
7118     EVT VecTy = N0.getOperand(0).getValueType();
7119     EVT ExTy = N0.getValueType();
7120     EVT TrTy = N->getValueType(0);
7121 
7122     unsigned NumElem = VecTy.getVectorNumElements();
7123     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7124 
7125     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7126     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7127 
7128     SDValue EltNo = N0->getOperand(1);
7129     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7130       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7131       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7132       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7133 
7134       SDLoc DL(N);
7135       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7136                          DAG.getBitcast(NVT, N0.getOperand(0)),
7137                          DAG.getConstant(Index, DL, IndexTy));
7138     }
7139   }
7140 
7141   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7142   if (N0.getOpcode() == ISD::SELECT) {
7143     EVT SrcVT = N0.getValueType();
7144     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7145         TLI.isTruncateFree(SrcVT, VT)) {
7146       SDLoc SL(N0);
7147       SDValue Cond = N0.getOperand(0);
7148       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7149       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7150       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7151     }
7152   }
7153 
7154   // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2
7155   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7156       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7157       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7158     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7159       uint64_t Amt = CAmt->getZExtValue();
7160       unsigned Size = VT.getSizeInBits();
7161 
7162       if (Amt < Size / 2) {
7163         SDLoc SL(N);
7164         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7165 
7166         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7167         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7168                            DAG.getConstant(Amt, SL, AmtVT));
7169       }
7170     }
7171   }
7172 
7173   // Fold a series of buildvector, bitcast, and truncate if possible.
7174   // For example fold
7175   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7176   //   (2xi32 (buildvector x, y)).
7177   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7178       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7179       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7180       N0.getOperand(0).hasOneUse()) {
7181 
7182     SDValue BuildVect = N0.getOperand(0);
7183     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7184     EVT TruncVecEltTy = VT.getVectorElementType();
7185 
7186     // Check that the element types match.
7187     if (BuildVectEltTy == TruncVecEltTy) {
7188       // Now we only need to compute the offset of the truncated elements.
7189       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7190       unsigned TruncVecNumElts = VT.getVectorNumElements();
7191       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7192 
7193       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7194              "Invalid number of elements");
7195 
7196       SmallVector<SDValue, 8> Opnds;
7197       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7198         Opnds.push_back(BuildVect.getOperand(i));
7199 
7200       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7201     }
7202   }
7203 
7204   // See if we can simplify the input to this truncate through knowledge that
7205   // only the low bits are being used.
7206   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7207   // Currently we only perform this optimization on scalars because vectors
7208   // may have different active low bits.
7209   if (!VT.isVector()) {
7210     if (SDValue Shorter =
7211             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7212                                                      VT.getSizeInBits())))
7213       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7214   }
7215   // fold (truncate (load x)) -> (smaller load x)
7216   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7217   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7218     if (SDValue Reduced = ReduceLoadWidth(N))
7219       return Reduced;
7220 
7221     // Handle the case where the load remains an extending load even
7222     // after truncation.
7223     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7224       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7225       if (!LN0->isVolatile() &&
7226           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7227         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7228                                          VT, LN0->getChain(), LN0->getBasePtr(),
7229                                          LN0->getMemoryVT(),
7230                                          LN0->getMemOperand());
7231         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7232         return NewLoad;
7233       }
7234     }
7235   }
7236   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7237   // where ... are all 'undef'.
7238   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7239     SmallVector<EVT, 8> VTs;
7240     SDValue V;
7241     unsigned Idx = 0;
7242     unsigned NumDefs = 0;
7243 
7244     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7245       SDValue X = N0.getOperand(i);
7246       if (!X.isUndef()) {
7247         V = X;
7248         Idx = i;
7249         NumDefs++;
7250       }
7251       // Stop if more than one members are non-undef.
7252       if (NumDefs > 1)
7253         break;
7254       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7255                                      VT.getVectorElementType(),
7256                                      X.getValueType().getVectorNumElements()));
7257     }
7258 
7259     if (NumDefs == 0)
7260       return DAG.getUNDEF(VT);
7261 
7262     if (NumDefs == 1) {
7263       assert(V.getNode() && "The single defined operand is empty!");
7264       SmallVector<SDValue, 8> Opnds;
7265       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7266         if (i != Idx) {
7267           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7268           continue;
7269         }
7270         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7271         AddToWorklist(NV.getNode());
7272         Opnds.push_back(NV);
7273       }
7274       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7275     }
7276   }
7277 
7278   // Fold truncate of a bitcast of a vector to an extract of the low vector
7279   // element.
7280   //
7281   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7282   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7283     SDValue VecSrc = N0.getOperand(0);
7284     EVT SrcVT = VecSrc.getValueType();
7285     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7286         (!LegalOperations ||
7287          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7288       SDLoc SL(N);
7289 
7290       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7291       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7292                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7293     }
7294   }
7295 
7296   // Simplify the operands using demanded-bits information.
7297   if (!VT.isVector() &&
7298       SimplifyDemandedBits(SDValue(N, 0)))
7299     return SDValue(N, 0);
7300 
7301   return SDValue();
7302 }
7303 
7304 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7305   SDValue Elt = N->getOperand(i);
7306   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7307     return Elt.getNode();
7308   return Elt.getOperand(Elt.getResNo()).getNode();
7309 }
7310 
7311 /// build_pair (load, load) -> load
7312 /// if load locations are consecutive.
7313 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7314   assert(N->getOpcode() == ISD::BUILD_PAIR);
7315 
7316   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7317   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7318   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7319       LD1->getAddressSpace() != LD2->getAddressSpace())
7320     return SDValue();
7321   EVT LD1VT = LD1->getValueType(0);
7322   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7323   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7324       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7325     unsigned Align = LD1->getAlignment();
7326     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7327         VT.getTypeForEVT(*DAG.getContext()));
7328 
7329     if (NewAlign <= Align &&
7330         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7331       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7332                          LD1->getBasePtr(), LD1->getPointerInfo(),
7333                          false, false, false, Align);
7334   }
7335 
7336   return SDValue();
7337 }
7338 
7339 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7340   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7341   // and Lo parts; on big-endian machines it doesn't.
7342   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7343 }
7344 
7345 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7346   SDValue N0 = N->getOperand(0);
7347   EVT VT = N->getValueType(0);
7348 
7349   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7350   // Only do this before legalize, since afterward the target may be depending
7351   // on the bitconvert.
7352   // First check to see if this is all constant.
7353   if (!LegalTypes &&
7354       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7355       VT.isVector()) {
7356     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7357 
7358     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7359     assert(!DestEltVT.isVector() &&
7360            "Element type of vector ValueType must not be vector!");
7361     if (isSimple)
7362       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7363   }
7364 
7365   // If the input is a constant, let getNode fold it.
7366   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7367     // If we can't allow illegal operations, we need to check that this is just
7368     // a fp -> int or int -> conversion and that the resulting operation will
7369     // be legal.
7370     if (!LegalOperations ||
7371         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7372          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7373         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7374          TLI.isOperationLegal(ISD::Constant, VT)))
7375       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7376   }
7377 
7378   // (conv (conv x, t1), t2) -> (conv x, t2)
7379   if (N0.getOpcode() == ISD::BITCAST)
7380     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7381                        N0.getOperand(0));
7382 
7383   // fold (conv (load x)) -> (load (conv*)x)
7384   // If the resultant load doesn't need a higher alignment than the original!
7385   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7386       // Do not change the width of a volatile load.
7387       !cast<LoadSDNode>(N0)->isVolatile() &&
7388       // Do not remove the cast if the types differ in endian layout.
7389       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7390           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7391       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7392       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7393     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7394     unsigned OrigAlign = LN0->getAlignment();
7395 
7396     bool Fast = false;
7397     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7398                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7399         Fast) {
7400       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7401                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7402                                  LN0->isVolatile(), LN0->isNonTemporal(),
7403                                  LN0->isInvariant(), OrigAlign,
7404                                  LN0->getAAInfo());
7405       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7406       return Load;
7407     }
7408   }
7409 
7410   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7411   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7412   //
7413   // For ppc_fp128:
7414   // fold (bitcast (fneg x)) ->
7415   //     flipbit = signbit
7416   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7417   //
7418   // fold (bitcast (fabs x)) ->
7419   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7420   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7421   // This often reduces constant pool loads.
7422   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7423        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7424       N0.getNode()->hasOneUse() && VT.isInteger() &&
7425       !VT.isVector() && !N0.getValueType().isVector()) {
7426     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7427                                   N0.getOperand(0));
7428     AddToWorklist(NewConv.getNode());
7429 
7430     SDLoc DL(N);
7431     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7432       assert(VT.getSizeInBits() == 128);
7433       SDValue SignBit = DAG.getConstant(
7434           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7435       SDValue FlipBit;
7436       if (N0.getOpcode() == ISD::FNEG) {
7437         FlipBit = SignBit;
7438         AddToWorklist(FlipBit.getNode());
7439       } else {
7440         assert(N0.getOpcode() == ISD::FABS);
7441         SDValue Hi =
7442             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7443                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7444                                               SDLoc(NewConv)));
7445         AddToWorklist(Hi.getNode());
7446         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7447         AddToWorklist(FlipBit.getNode());
7448       }
7449       SDValue FlipBits =
7450           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7451       AddToWorklist(FlipBits.getNode());
7452       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7453     }
7454     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7455     if (N0.getOpcode() == ISD::FNEG)
7456       return DAG.getNode(ISD::XOR, DL, VT,
7457                          NewConv, DAG.getConstant(SignBit, DL, VT));
7458     assert(N0.getOpcode() == ISD::FABS);
7459     return DAG.getNode(ISD::AND, DL, VT,
7460                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7461   }
7462 
7463   // fold (bitconvert (fcopysign cst, x)) ->
7464   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7465   // Note that we don't handle (copysign x, cst) because this can always be
7466   // folded to an fneg or fabs.
7467   //
7468   // For ppc_fp128:
7469   // fold (bitcast (fcopysign cst, x)) ->
7470   //     flipbit = (and (extract_element
7471   //                     (xor (bitcast cst), (bitcast x)), 0),
7472   //                    signbit)
7473   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7474   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7475       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7476       VT.isInteger() && !VT.isVector()) {
7477     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7478     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7479     if (isTypeLegal(IntXVT)) {
7480       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7481                               IntXVT, N0.getOperand(1));
7482       AddToWorklist(X.getNode());
7483 
7484       // If X has a different width than the result/lhs, sext it or truncate it.
7485       unsigned VTWidth = VT.getSizeInBits();
7486       if (OrigXWidth < VTWidth) {
7487         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7488         AddToWorklist(X.getNode());
7489       } else if (OrigXWidth > VTWidth) {
7490         // To get the sign bit in the right place, we have to shift it right
7491         // before truncating.
7492         SDLoc DL(X);
7493         X = DAG.getNode(ISD::SRL, DL,
7494                         X.getValueType(), X,
7495                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7496                                         X.getValueType()));
7497         AddToWorklist(X.getNode());
7498         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7499         AddToWorklist(X.getNode());
7500       }
7501 
7502       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7503         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7504         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7505         AddToWorklist(Cst.getNode());
7506         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7507         AddToWorklist(X.getNode());
7508         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7509         AddToWorklist(XorResult.getNode());
7510         SDValue XorResult64 = DAG.getNode(
7511             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7512             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7513                                   SDLoc(XorResult)));
7514         AddToWorklist(XorResult64.getNode());
7515         SDValue FlipBit =
7516             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7517                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7518         AddToWorklist(FlipBit.getNode());
7519         SDValue FlipBits =
7520             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7521         AddToWorklist(FlipBits.getNode());
7522         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7523       }
7524       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7525       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7526                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7527       AddToWorklist(X.getNode());
7528 
7529       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7530                                 VT, N0.getOperand(0));
7531       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7532                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7533       AddToWorklist(Cst.getNode());
7534 
7535       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7536     }
7537   }
7538 
7539   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7540   if (N0.getOpcode() == ISD::BUILD_PAIR)
7541     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7542       return CombineLD;
7543 
7544   // Remove double bitcasts from shuffles - this is often a legacy of
7545   // XformToShuffleWithZero being used to combine bitmaskings (of
7546   // float vectors bitcast to integer vectors) into shuffles.
7547   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7548   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7549       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7550       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7551       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7552     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7553 
7554     // If operands are a bitcast, peek through if it casts the original VT.
7555     // If operands are a constant, just bitcast back to original VT.
7556     auto PeekThroughBitcast = [&](SDValue Op) {
7557       if (Op.getOpcode() == ISD::BITCAST &&
7558           Op.getOperand(0).getValueType() == VT)
7559         return SDValue(Op.getOperand(0));
7560       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7561           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7562         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7563       return SDValue();
7564     };
7565 
7566     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7567     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7568     if (!(SV0 && SV1))
7569       return SDValue();
7570 
7571     int MaskScale =
7572         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7573     SmallVector<int, 8> NewMask;
7574     for (int M : SVN->getMask())
7575       for (int i = 0; i != MaskScale; ++i)
7576         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7577 
7578     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7579     if (!LegalMask) {
7580       std::swap(SV0, SV1);
7581       ShuffleVectorSDNode::commuteMask(NewMask);
7582       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7583     }
7584 
7585     if (LegalMask)
7586       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7587   }
7588 
7589   return SDValue();
7590 }
7591 
7592 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7593   EVT VT = N->getValueType(0);
7594   return CombineConsecutiveLoads(N, VT);
7595 }
7596 
7597 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7598 /// operands. DstEltVT indicates the destination element value type.
7599 SDValue DAGCombiner::
7600 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7601   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7602 
7603   // If this is already the right type, we're done.
7604   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7605 
7606   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7607   unsigned DstBitSize = DstEltVT.getSizeInBits();
7608 
7609   // If this is a conversion of N elements of one type to N elements of another
7610   // type, convert each element.  This handles FP<->INT cases.
7611   if (SrcBitSize == DstBitSize) {
7612     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7613                               BV->getValueType(0).getVectorNumElements());
7614 
7615     // Due to the FP element handling below calling this routine recursively,
7616     // we can end up with a scalar-to-vector node here.
7617     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7618       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7619                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7620                                      DstEltVT, BV->getOperand(0)));
7621 
7622     SmallVector<SDValue, 8> Ops;
7623     for (SDValue Op : BV->op_values()) {
7624       // If the vector element type is not legal, the BUILD_VECTOR operands
7625       // are promoted and implicitly truncated.  Make that explicit here.
7626       if (Op.getValueType() != SrcEltVT)
7627         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7628       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7629                                 DstEltVT, Op));
7630       AddToWorklist(Ops.back().getNode());
7631     }
7632     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7633   }
7634 
7635   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7636   // handle annoying details of growing/shrinking FP values, we convert them to
7637   // int first.
7638   if (SrcEltVT.isFloatingPoint()) {
7639     // Convert the input float vector to a int vector where the elements are the
7640     // same sizes.
7641     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7642     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7643     SrcEltVT = IntVT;
7644   }
7645 
7646   // Now we know the input is an integer vector.  If the output is a FP type,
7647   // convert to integer first, then to FP of the right size.
7648   if (DstEltVT.isFloatingPoint()) {
7649     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7650     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7651 
7652     // Next, convert to FP elements of the same size.
7653     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7654   }
7655 
7656   SDLoc DL(BV);
7657 
7658   // Okay, we know the src/dst types are both integers of differing types.
7659   // Handling growing first.
7660   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7661   if (SrcBitSize < DstBitSize) {
7662     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7663 
7664     SmallVector<SDValue, 8> Ops;
7665     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7666          i += NumInputsPerOutput) {
7667       bool isLE = DAG.getDataLayout().isLittleEndian();
7668       APInt NewBits = APInt(DstBitSize, 0);
7669       bool EltIsUndef = true;
7670       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7671         // Shift the previously computed bits over.
7672         NewBits <<= SrcBitSize;
7673         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7674         if (Op.isUndef()) continue;
7675         EltIsUndef = false;
7676 
7677         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7678                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7679       }
7680 
7681       if (EltIsUndef)
7682         Ops.push_back(DAG.getUNDEF(DstEltVT));
7683       else
7684         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7685     }
7686 
7687     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7688     return DAG.getBuildVector(VT, DL, Ops);
7689   }
7690 
7691   // Finally, this must be the case where we are shrinking elements: each input
7692   // turns into multiple outputs.
7693   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7694   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7695                             NumOutputsPerInput*BV->getNumOperands());
7696   SmallVector<SDValue, 8> Ops;
7697 
7698   for (const SDValue &Op : BV->op_values()) {
7699     if (Op.isUndef()) {
7700       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7701       continue;
7702     }
7703 
7704     APInt OpVal = cast<ConstantSDNode>(Op)->
7705                   getAPIntValue().zextOrTrunc(SrcBitSize);
7706 
7707     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7708       APInt ThisVal = OpVal.trunc(DstBitSize);
7709       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7710       OpVal = OpVal.lshr(DstBitSize);
7711     }
7712 
7713     // For big endian targets, swap the order of the pieces of each element.
7714     if (DAG.getDataLayout().isBigEndian())
7715       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7716   }
7717 
7718   return DAG.getBuildVector(VT, DL, Ops);
7719 }
7720 
7721 /// Try to perform FMA combining on a given FADD node.
7722 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7723   SDValue N0 = N->getOperand(0);
7724   SDValue N1 = N->getOperand(1);
7725   EVT VT = N->getValueType(0);
7726   SDLoc SL(N);
7727 
7728   const TargetOptions &Options = DAG.getTarget().Options;
7729   bool AllowFusion =
7730       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7731 
7732   // Floating-point multiply-add with intermediate rounding.
7733   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7734 
7735   // Floating-point multiply-add without intermediate rounding.
7736   bool HasFMA =
7737       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7738       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7739 
7740   // No valid opcode, do not combine.
7741   if (!HasFMAD && !HasFMA)
7742     return SDValue();
7743 
7744   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7745   ;
7746   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7747     return SDValue();
7748 
7749   // Always prefer FMAD to FMA for precision.
7750   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7751   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7752   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7753 
7754   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7755   // prefer to fold the multiply with fewer uses.
7756   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7757       N1.getOpcode() == ISD::FMUL) {
7758     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7759       std::swap(N0, N1);
7760   }
7761 
7762   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7763   if (N0.getOpcode() == ISD::FMUL &&
7764       (Aggressive || N0->hasOneUse())) {
7765     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7766                        N0.getOperand(0), N0.getOperand(1), N1);
7767   }
7768 
7769   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7770   // Note: Commutes FADD operands.
7771   if (N1.getOpcode() == ISD::FMUL &&
7772       (Aggressive || N1->hasOneUse())) {
7773     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7774                        N1.getOperand(0), N1.getOperand(1), N0);
7775   }
7776 
7777   // Look through FP_EXTEND nodes to do more combining.
7778   if (AllowFusion && LookThroughFPExt) {
7779     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7780     if (N0.getOpcode() == ISD::FP_EXTEND) {
7781       SDValue N00 = N0.getOperand(0);
7782       if (N00.getOpcode() == ISD::FMUL)
7783         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7784                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7785                                        N00.getOperand(0)),
7786                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787                                        N00.getOperand(1)), N1);
7788     }
7789 
7790     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7791     // Note: Commutes FADD operands.
7792     if (N1.getOpcode() == ISD::FP_EXTEND) {
7793       SDValue N10 = N1.getOperand(0);
7794       if (N10.getOpcode() == ISD::FMUL)
7795         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7796                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7797                                        N10.getOperand(0)),
7798                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7799                                        N10.getOperand(1)), N0);
7800     }
7801   }
7802 
7803   // More folding opportunities when target permits.
7804   if ((AllowFusion || HasFMAD)  && Aggressive) {
7805     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7806     if (N0.getOpcode() == PreferredFusedOpcode &&
7807         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7808       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7809                          N0.getOperand(0), N0.getOperand(1),
7810                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7811                                      N0.getOperand(2).getOperand(0),
7812                                      N0.getOperand(2).getOperand(1),
7813                                      N1));
7814     }
7815 
7816     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7817     if (N1->getOpcode() == PreferredFusedOpcode &&
7818         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7819       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                          N1.getOperand(0), N1.getOperand(1),
7821                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7822                                      N1.getOperand(2).getOperand(0),
7823                                      N1.getOperand(2).getOperand(1),
7824                                      N0));
7825     }
7826 
7827     if (AllowFusion && LookThroughFPExt) {
7828       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7829       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7830       auto FoldFAddFMAFPExtFMul = [&] (
7831           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7832         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7833                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7834                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7835                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7836                                        Z));
7837       };
7838       if (N0.getOpcode() == PreferredFusedOpcode) {
7839         SDValue N02 = N0.getOperand(2);
7840         if (N02.getOpcode() == ISD::FP_EXTEND) {
7841           SDValue N020 = N02.getOperand(0);
7842           if (N020.getOpcode() == ISD::FMUL)
7843             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7844                                         N020.getOperand(0), N020.getOperand(1),
7845                                         N1);
7846         }
7847       }
7848 
7849       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7850       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7851       // FIXME: This turns two single-precision and one double-precision
7852       // operation into two double-precision operations, which might not be
7853       // interesting for all targets, especially GPUs.
7854       auto FoldFAddFPExtFMAFMul = [&] (
7855           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7856         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7857                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7858                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7859                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7860                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7861                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7862                                        Z));
7863       };
7864       if (N0.getOpcode() == ISD::FP_EXTEND) {
7865         SDValue N00 = N0.getOperand(0);
7866         if (N00.getOpcode() == PreferredFusedOpcode) {
7867           SDValue N002 = N00.getOperand(2);
7868           if (N002.getOpcode() == ISD::FMUL)
7869             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7870                                         N002.getOperand(0), N002.getOperand(1),
7871                                         N1);
7872         }
7873       }
7874 
7875       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7876       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7877       if (N1.getOpcode() == PreferredFusedOpcode) {
7878         SDValue N12 = N1.getOperand(2);
7879         if (N12.getOpcode() == ISD::FP_EXTEND) {
7880           SDValue N120 = N12.getOperand(0);
7881           if (N120.getOpcode() == ISD::FMUL)
7882             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7883                                         N120.getOperand(0), N120.getOperand(1),
7884                                         N0);
7885         }
7886       }
7887 
7888       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7889       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7890       // FIXME: This turns two single-precision and one double-precision
7891       // operation into two double-precision operations, which might not be
7892       // interesting for all targets, especially GPUs.
7893       if (N1.getOpcode() == ISD::FP_EXTEND) {
7894         SDValue N10 = N1.getOperand(0);
7895         if (N10.getOpcode() == PreferredFusedOpcode) {
7896           SDValue N102 = N10.getOperand(2);
7897           if (N102.getOpcode() == ISD::FMUL)
7898             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7899                                         N102.getOperand(0), N102.getOperand(1),
7900                                         N0);
7901         }
7902       }
7903     }
7904   }
7905 
7906   return SDValue();
7907 }
7908 
7909 /// Try to perform FMA combining on a given FSUB node.
7910 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7911   SDValue N0 = N->getOperand(0);
7912   SDValue N1 = N->getOperand(1);
7913   EVT VT = N->getValueType(0);
7914   SDLoc SL(N);
7915 
7916   const TargetOptions &Options = DAG.getTarget().Options;
7917   bool AllowFusion =
7918       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7919 
7920   // Floating-point multiply-add with intermediate rounding.
7921   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7922 
7923   // Floating-point multiply-add without intermediate rounding.
7924   bool HasFMA =
7925       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7926       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7927 
7928   // No valid opcode, do not combine.
7929   if (!HasFMAD && !HasFMA)
7930     return SDValue();
7931 
7932   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7933   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7934     return SDValue();
7935 
7936   // Always prefer FMAD to FMA for precision.
7937   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7938   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7939   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7940 
7941   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7942   if (N0.getOpcode() == ISD::FMUL &&
7943       (Aggressive || N0->hasOneUse())) {
7944     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7945                        N0.getOperand(0), N0.getOperand(1),
7946                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7947   }
7948 
7949   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7950   // Note: Commutes FSUB operands.
7951   if (N1.getOpcode() == ISD::FMUL &&
7952       (Aggressive || N1->hasOneUse()))
7953     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7954                        DAG.getNode(ISD::FNEG, SL, VT,
7955                                    N1.getOperand(0)),
7956                        N1.getOperand(1), N0);
7957 
7958   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7959   if (N0.getOpcode() == ISD::FNEG &&
7960       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7961       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7962     SDValue N00 = N0.getOperand(0).getOperand(0);
7963     SDValue N01 = N0.getOperand(0).getOperand(1);
7964     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7965                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7966                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7967   }
7968 
7969   // Look through FP_EXTEND nodes to do more combining.
7970   if (AllowFusion && LookThroughFPExt) {
7971     // fold (fsub (fpext (fmul x, y)), z)
7972     //   -> (fma (fpext x), (fpext y), (fneg z))
7973     if (N0.getOpcode() == ISD::FP_EXTEND) {
7974       SDValue N00 = N0.getOperand(0);
7975       if (N00.getOpcode() == ISD::FMUL)
7976         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7977                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7978                                        N00.getOperand(0)),
7979                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7980                                        N00.getOperand(1)),
7981                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7982     }
7983 
7984     // fold (fsub x, (fpext (fmul y, z)))
7985     //   -> (fma (fneg (fpext y)), (fpext z), x)
7986     // Note: Commutes FSUB operands.
7987     if (N1.getOpcode() == ISD::FP_EXTEND) {
7988       SDValue N10 = N1.getOperand(0);
7989       if (N10.getOpcode() == ISD::FMUL)
7990         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7991                            DAG.getNode(ISD::FNEG, SL, VT,
7992                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7993                                                    N10.getOperand(0))),
7994                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7995                                        N10.getOperand(1)),
7996                            N0);
7997     }
7998 
7999     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8000     //   -> (fneg (fma (fpext x), (fpext y), z))
8001     // Note: This could be removed with appropriate canonicalization of the
8002     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8003     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8004     // from implementing the canonicalization in visitFSUB.
8005     if (N0.getOpcode() == ISD::FP_EXTEND) {
8006       SDValue N00 = N0.getOperand(0);
8007       if (N00.getOpcode() == ISD::FNEG) {
8008         SDValue N000 = N00.getOperand(0);
8009         if (N000.getOpcode() == ISD::FMUL) {
8010           return DAG.getNode(ISD::FNEG, SL, VT,
8011                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8012                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8013                                                      N000.getOperand(0)),
8014                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8015                                                      N000.getOperand(1)),
8016                                          N1));
8017         }
8018       }
8019     }
8020 
8021     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8022     //   -> (fneg (fma (fpext x)), (fpext y), z)
8023     // Note: This could be removed with appropriate canonicalization of the
8024     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8025     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8026     // from implementing the canonicalization in visitFSUB.
8027     if (N0.getOpcode() == ISD::FNEG) {
8028       SDValue N00 = N0.getOperand(0);
8029       if (N00.getOpcode() == ISD::FP_EXTEND) {
8030         SDValue N000 = N00.getOperand(0);
8031         if (N000.getOpcode() == ISD::FMUL) {
8032           return DAG.getNode(ISD::FNEG, SL, VT,
8033                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8034                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8035                                                      N000.getOperand(0)),
8036                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8037                                                      N000.getOperand(1)),
8038                                          N1));
8039         }
8040       }
8041     }
8042 
8043   }
8044 
8045   // More folding opportunities when target permits.
8046   if ((AllowFusion || HasFMAD) && Aggressive) {
8047     // fold (fsub (fma x, y, (fmul u, v)), z)
8048     //   -> (fma x, y (fma u, v, (fneg z)))
8049     if (N0.getOpcode() == PreferredFusedOpcode &&
8050         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8051       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8052                          N0.getOperand(0), N0.getOperand(1),
8053                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8054                                      N0.getOperand(2).getOperand(0),
8055                                      N0.getOperand(2).getOperand(1),
8056                                      DAG.getNode(ISD::FNEG, SL, VT,
8057                                                  N1)));
8058     }
8059 
8060     // fold (fsub x, (fma y, z, (fmul u, v)))
8061     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8062     if (N1.getOpcode() == PreferredFusedOpcode &&
8063         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8064       SDValue N20 = N1.getOperand(2).getOperand(0);
8065       SDValue N21 = N1.getOperand(2).getOperand(1);
8066       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8067                          DAG.getNode(ISD::FNEG, SL, VT,
8068                                      N1.getOperand(0)),
8069                          N1.getOperand(1),
8070                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8071                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8072 
8073                                      N21, N0));
8074     }
8075 
8076     if (AllowFusion && LookThroughFPExt) {
8077       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8078       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8079       if (N0.getOpcode() == PreferredFusedOpcode) {
8080         SDValue N02 = N0.getOperand(2);
8081         if (N02.getOpcode() == ISD::FP_EXTEND) {
8082           SDValue N020 = N02.getOperand(0);
8083           if (N020.getOpcode() == ISD::FMUL)
8084             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8085                                N0.getOperand(0), N0.getOperand(1),
8086                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8087                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8088                                                        N020.getOperand(0)),
8089                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8090                                                        N020.getOperand(1)),
8091                                            DAG.getNode(ISD::FNEG, SL, VT,
8092                                                        N1)));
8093         }
8094       }
8095 
8096       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8097       //   -> (fma (fpext x), (fpext y),
8098       //           (fma (fpext u), (fpext v), (fneg z)))
8099       // FIXME: This turns two single-precision and one double-precision
8100       // operation into two double-precision operations, which might not be
8101       // interesting for all targets, especially GPUs.
8102       if (N0.getOpcode() == ISD::FP_EXTEND) {
8103         SDValue N00 = N0.getOperand(0);
8104         if (N00.getOpcode() == PreferredFusedOpcode) {
8105           SDValue N002 = N00.getOperand(2);
8106           if (N002.getOpcode() == ISD::FMUL)
8107             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8108                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8109                                            N00.getOperand(0)),
8110                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8111                                            N00.getOperand(1)),
8112                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8113                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8114                                                        N002.getOperand(0)),
8115                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8116                                                        N002.getOperand(1)),
8117                                            DAG.getNode(ISD::FNEG, SL, VT,
8118                                                        N1)));
8119         }
8120       }
8121 
8122       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8123       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8124       if (N1.getOpcode() == PreferredFusedOpcode &&
8125         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8126         SDValue N120 = N1.getOperand(2).getOperand(0);
8127         if (N120.getOpcode() == ISD::FMUL) {
8128           SDValue N1200 = N120.getOperand(0);
8129           SDValue N1201 = N120.getOperand(1);
8130           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8131                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8132                              N1.getOperand(1),
8133                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8134                                          DAG.getNode(ISD::FNEG, SL, VT,
8135                                              DAG.getNode(ISD::FP_EXTEND, SL,
8136                                                          VT, N1200)),
8137                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8138                                                      N1201),
8139                                          N0));
8140         }
8141       }
8142 
8143       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8144       //   -> (fma (fneg (fpext y)), (fpext z),
8145       //           (fma (fneg (fpext u)), (fpext v), x))
8146       // FIXME: This turns two single-precision and one double-precision
8147       // operation into two double-precision operations, which might not be
8148       // interesting for all targets, especially GPUs.
8149       if (N1.getOpcode() == ISD::FP_EXTEND &&
8150         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8151         SDValue N100 = N1.getOperand(0).getOperand(0);
8152         SDValue N101 = N1.getOperand(0).getOperand(1);
8153         SDValue N102 = N1.getOperand(0).getOperand(2);
8154         if (N102.getOpcode() == ISD::FMUL) {
8155           SDValue N1020 = N102.getOperand(0);
8156           SDValue N1021 = N102.getOperand(1);
8157           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8158                              DAG.getNode(ISD::FNEG, SL, VT,
8159                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8160                                                      N100)),
8161                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8162                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8163                                          DAG.getNode(ISD::FNEG, SL, VT,
8164                                              DAG.getNode(ISD::FP_EXTEND, SL,
8165                                                          VT, N1020)),
8166                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8167                                                      N1021),
8168                                          N0));
8169         }
8170       }
8171     }
8172   }
8173 
8174   return SDValue();
8175 }
8176 
8177 /// Try to perform FMA combining on a given FMUL node.
8178 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8179   SDValue N0 = N->getOperand(0);
8180   SDValue N1 = N->getOperand(1);
8181   EVT VT = N->getValueType(0);
8182   SDLoc SL(N);
8183 
8184   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8185 
8186   const TargetOptions &Options = DAG.getTarget().Options;
8187   bool AllowFusion =
8188       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8189 
8190   // Floating-point multiply-add with intermediate rounding.
8191   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8192 
8193   // Floating-point multiply-add without intermediate rounding.
8194   bool HasFMA =
8195       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8196       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8197 
8198   // No valid opcode, do not combine.
8199   if (!HasFMAD && !HasFMA)
8200     return SDValue();
8201 
8202   // Always prefer FMAD to FMA for precision.
8203   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8204   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8205 
8206   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8207   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8208   auto FuseFADD = [&](SDValue X, SDValue Y) {
8209     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8210       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8211       if (XC1 && XC1->isExactlyValue(+1.0))
8212         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8213       if (XC1 && XC1->isExactlyValue(-1.0))
8214         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8215                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8216     }
8217     return SDValue();
8218   };
8219 
8220   if (SDValue FMA = FuseFADD(N0, N1))
8221     return FMA;
8222   if (SDValue FMA = FuseFADD(N1, N0))
8223     return FMA;
8224 
8225   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8226   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8227   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8228   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8229   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8230     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8231       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8232       if (XC0 && XC0->isExactlyValue(+1.0))
8233         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8234                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8235                            Y);
8236       if (XC0 && XC0->isExactlyValue(-1.0))
8237         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8238                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8239                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8240 
8241       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8242       if (XC1 && XC1->isExactlyValue(+1.0))
8243         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8244                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8245       if (XC1 && XC1->isExactlyValue(-1.0))
8246         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8247     }
8248     return SDValue();
8249   };
8250 
8251   if (SDValue FMA = FuseFSUB(N0, N1))
8252     return FMA;
8253   if (SDValue FMA = FuseFSUB(N1, N0))
8254     return FMA;
8255 
8256   return SDValue();
8257 }
8258 
8259 SDValue DAGCombiner::visitFADD(SDNode *N) {
8260   SDValue N0 = N->getOperand(0);
8261   SDValue N1 = N->getOperand(1);
8262   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8263   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8264   EVT VT = N->getValueType(0);
8265   SDLoc DL(N);
8266   const TargetOptions &Options = DAG.getTarget().Options;
8267   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8268 
8269   // fold vector ops
8270   if (VT.isVector())
8271     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8272       return FoldedVOp;
8273 
8274   // fold (fadd c1, c2) -> c1 + c2
8275   if (N0CFP && N1CFP)
8276     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8277 
8278   // canonicalize constant to RHS
8279   if (N0CFP && !N1CFP)
8280     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8281 
8282   // fold (fadd A, (fneg B)) -> (fsub A, B)
8283   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8284       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8285     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8286                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8287 
8288   // fold (fadd (fneg A), B) -> (fsub B, A)
8289   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8290       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8291     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8292                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8293 
8294   // If 'unsafe math' is enabled, fold lots of things.
8295   if (Options.UnsafeFPMath) {
8296     // No FP constant should be created after legalization as Instruction
8297     // Selection pass has a hard time dealing with FP constants.
8298     bool AllowNewConst = (Level < AfterLegalizeDAG);
8299 
8300     // fold (fadd A, 0) -> A
8301     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8302       if (N1C->isZero())
8303         return N0;
8304 
8305     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8306     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8307         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8308       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8309                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8310                                      Flags),
8311                          Flags);
8312 
8313     // If allowed, fold (fadd (fneg x), x) -> 0.0
8314     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8315       return DAG.getConstantFP(0.0, DL, VT);
8316 
8317     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8318     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8319       return DAG.getConstantFP(0.0, DL, VT);
8320 
8321     // We can fold chains of FADD's of the same value into multiplications.
8322     // This transform is not safe in general because we are reducing the number
8323     // of rounding steps.
8324     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8325       if (N0.getOpcode() == ISD::FMUL) {
8326         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8327         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8328 
8329         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8330         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8331           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8332                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8333           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8334         }
8335 
8336         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8337         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8338             N1.getOperand(0) == N1.getOperand(1) &&
8339             N0.getOperand(0) == N1.getOperand(0)) {
8340           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8341                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8342           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8343         }
8344       }
8345 
8346       if (N1.getOpcode() == ISD::FMUL) {
8347         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8348         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8349 
8350         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8351         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8352           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8353                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8354           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8355         }
8356 
8357         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8358         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8359             N0.getOperand(0) == N0.getOperand(1) &&
8360             N1.getOperand(0) == N0.getOperand(0)) {
8361           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8362                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8363           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8364         }
8365       }
8366 
8367       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8368         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8369         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8370         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8371             (N0.getOperand(0) == N1)) {
8372           return DAG.getNode(ISD::FMUL, DL, VT,
8373                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8374         }
8375       }
8376 
8377       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8378         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8379         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8380         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8381             N1.getOperand(0) == N0) {
8382           return DAG.getNode(ISD::FMUL, DL, VT,
8383                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8384         }
8385       }
8386 
8387       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8388       if (AllowNewConst &&
8389           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8390           N0.getOperand(0) == N0.getOperand(1) &&
8391           N1.getOperand(0) == N1.getOperand(1) &&
8392           N0.getOperand(0) == N1.getOperand(0)) {
8393         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8394                            DAG.getConstantFP(4.0, DL, VT), Flags);
8395       }
8396     }
8397   } // enable-unsafe-fp-math
8398 
8399   // FADD -> FMA combines:
8400   if (SDValue Fused = visitFADDForFMACombine(N)) {
8401     AddToWorklist(Fused.getNode());
8402     return Fused;
8403   }
8404   return SDValue();
8405 }
8406 
8407 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8408   SDValue N0 = N->getOperand(0);
8409   SDValue N1 = N->getOperand(1);
8410   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8411   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8412   EVT VT = N->getValueType(0);
8413   SDLoc dl(N);
8414   const TargetOptions &Options = DAG.getTarget().Options;
8415   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8416 
8417   // fold vector ops
8418   if (VT.isVector())
8419     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8420       return FoldedVOp;
8421 
8422   // fold (fsub c1, c2) -> c1-c2
8423   if (N0CFP && N1CFP)
8424     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8425 
8426   // fold (fsub A, (fneg B)) -> (fadd A, B)
8427   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8428     return DAG.getNode(ISD::FADD, dl, VT, N0,
8429                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8430 
8431   // If 'unsafe math' is enabled, fold lots of things.
8432   if (Options.UnsafeFPMath) {
8433     // (fsub A, 0) -> A
8434     if (N1CFP && N1CFP->isZero())
8435       return N0;
8436 
8437     // (fsub 0, B) -> -B
8438     if (N0CFP && N0CFP->isZero()) {
8439       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8440         return GetNegatedExpression(N1, DAG, LegalOperations);
8441       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8442         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8443     }
8444 
8445     // (fsub x, x) -> 0.0
8446     if (N0 == N1)
8447       return DAG.getConstantFP(0.0f, dl, VT);
8448 
8449     // (fsub x, (fadd x, y)) -> (fneg y)
8450     // (fsub x, (fadd y, x)) -> (fneg y)
8451     if (N1.getOpcode() == ISD::FADD) {
8452       SDValue N10 = N1->getOperand(0);
8453       SDValue N11 = N1->getOperand(1);
8454 
8455       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8456         return GetNegatedExpression(N11, DAG, LegalOperations);
8457 
8458       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8459         return GetNegatedExpression(N10, DAG, LegalOperations);
8460     }
8461   }
8462 
8463   // FSUB -> FMA combines:
8464   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8465     AddToWorklist(Fused.getNode());
8466     return Fused;
8467   }
8468 
8469   return SDValue();
8470 }
8471 
8472 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8473   SDValue N0 = N->getOperand(0);
8474   SDValue N1 = N->getOperand(1);
8475   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8476   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8477   EVT VT = N->getValueType(0);
8478   SDLoc DL(N);
8479   const TargetOptions &Options = DAG.getTarget().Options;
8480   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8481 
8482   // fold vector ops
8483   if (VT.isVector()) {
8484     // This just handles C1 * C2 for vectors. Other vector folds are below.
8485     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8486       return FoldedVOp;
8487   }
8488 
8489   // fold (fmul c1, c2) -> c1*c2
8490   if (N0CFP && N1CFP)
8491     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8492 
8493   // canonicalize constant to RHS
8494   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8495      !isConstantFPBuildVectorOrConstantFP(N1))
8496     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8497 
8498   // fold (fmul A, 1.0) -> A
8499   if (N1CFP && N1CFP->isExactlyValue(1.0))
8500     return N0;
8501 
8502   if (Options.UnsafeFPMath) {
8503     // fold (fmul A, 0) -> 0
8504     if (N1CFP && N1CFP->isZero())
8505       return N1;
8506 
8507     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8508     if (N0.getOpcode() == ISD::FMUL) {
8509       // Fold scalars or any vector constants (not just splats).
8510       // This fold is done in general by InstCombine, but extra fmul insts
8511       // may have been generated during lowering.
8512       SDValue N00 = N0.getOperand(0);
8513       SDValue N01 = N0.getOperand(1);
8514       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8515       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8516       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8517 
8518       // Check 1: Make sure that the first operand of the inner multiply is NOT
8519       // a constant. Otherwise, we may induce infinite looping.
8520       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8521         // Check 2: Make sure that the second operand of the inner multiply and
8522         // the second operand of the outer multiply are constants.
8523         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8524             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8525           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8526           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8527         }
8528       }
8529     }
8530 
8531     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8532     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8533     // during an early run of DAGCombiner can prevent folding with fmuls
8534     // inserted during lowering.
8535     if (N0.getOpcode() == ISD::FADD &&
8536         (N0.getOperand(0) == N0.getOperand(1)) &&
8537         N0.hasOneUse()) {
8538       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8539       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8540       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8541     }
8542   }
8543 
8544   // fold (fmul X, 2.0) -> (fadd X, X)
8545   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8546     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8547 
8548   // fold (fmul X, -1.0) -> (fneg X)
8549   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8550     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8551       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8552 
8553   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8554   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8555     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8556       // Both can be negated for free, check to see if at least one is cheaper
8557       // negated.
8558       if (LHSNeg == 2 || RHSNeg == 2)
8559         return DAG.getNode(ISD::FMUL, DL, VT,
8560                            GetNegatedExpression(N0, DAG, LegalOperations),
8561                            GetNegatedExpression(N1, DAG, LegalOperations),
8562                            Flags);
8563     }
8564   }
8565 
8566   // FMUL -> FMA combines:
8567   if (SDValue Fused = visitFMULForFMACombine(N)) {
8568     AddToWorklist(Fused.getNode());
8569     return Fused;
8570   }
8571 
8572   return SDValue();
8573 }
8574 
8575 SDValue DAGCombiner::visitFMA(SDNode *N) {
8576   SDValue N0 = N->getOperand(0);
8577   SDValue N1 = N->getOperand(1);
8578   SDValue N2 = N->getOperand(2);
8579   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8580   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8581   EVT VT = N->getValueType(0);
8582   SDLoc dl(N);
8583   const TargetOptions &Options = DAG.getTarget().Options;
8584 
8585   // Constant fold FMA.
8586   if (isa<ConstantFPSDNode>(N0) &&
8587       isa<ConstantFPSDNode>(N1) &&
8588       isa<ConstantFPSDNode>(N2)) {
8589     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8590   }
8591 
8592   if (Options.UnsafeFPMath) {
8593     if (N0CFP && N0CFP->isZero())
8594       return N2;
8595     if (N1CFP && N1CFP->isZero())
8596       return N2;
8597   }
8598   // TODO: The FMA node should have flags that propagate to these nodes.
8599   if (N0CFP && N0CFP->isExactlyValue(1.0))
8600     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8601   if (N1CFP && N1CFP->isExactlyValue(1.0))
8602     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8603 
8604   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8605   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8606      !isConstantFPBuildVectorOrConstantFP(N1))
8607     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8608 
8609   // TODO: FMA nodes should have flags that propagate to the created nodes.
8610   // For now, create a Flags object for use with all unsafe math transforms.
8611   SDNodeFlags Flags;
8612   Flags.setUnsafeAlgebra(true);
8613 
8614   if (Options.UnsafeFPMath) {
8615     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8616     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8617         isConstantFPBuildVectorOrConstantFP(N1) &&
8618         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8619       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8620                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8621                                      &Flags), &Flags);
8622     }
8623 
8624     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8625     if (N0.getOpcode() == ISD::FMUL &&
8626         isConstantFPBuildVectorOrConstantFP(N1) &&
8627         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8628       return DAG.getNode(ISD::FMA, dl, VT,
8629                          N0.getOperand(0),
8630                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8631                                      &Flags),
8632                          N2);
8633     }
8634   }
8635 
8636   // (fma x, 1, y) -> (fadd x, y)
8637   // (fma x, -1, y) -> (fadd (fneg x), y)
8638   if (N1CFP) {
8639     if (N1CFP->isExactlyValue(1.0))
8640       // TODO: The FMA node should have flags that propagate to this node.
8641       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8642 
8643     if (N1CFP->isExactlyValue(-1.0) &&
8644         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8645       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8646       AddToWorklist(RHSNeg.getNode());
8647       // TODO: The FMA node should have flags that propagate to this node.
8648       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8649     }
8650   }
8651 
8652   if (Options.UnsafeFPMath) {
8653     // (fma x, c, x) -> (fmul x, (c+1))
8654     if (N1CFP && N0 == N2) {
8655     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8656                          DAG.getNode(ISD::FADD, dl, VT,
8657                                      N1, DAG.getConstantFP(1.0, dl, VT),
8658                                      &Flags), &Flags);
8659     }
8660 
8661     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8662     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8663       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8664                          DAG.getNode(ISD::FADD, dl, VT,
8665                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8666                                      &Flags), &Flags);
8667     }
8668   }
8669 
8670   return SDValue();
8671 }
8672 
8673 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8674 // reciprocal.
8675 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8676 // Notice that this is not always beneficial. One reason is different target
8677 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8678 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8679 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8680 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8681   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8682   const SDNodeFlags *Flags = N->getFlags();
8683   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8684     return SDValue();
8685 
8686   // Skip if current node is a reciprocal.
8687   SDValue N0 = N->getOperand(0);
8688   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8689   if (N0CFP && N0CFP->isExactlyValue(1.0))
8690     return SDValue();
8691 
8692   // Exit early if the target does not want this transform or if there can't
8693   // possibly be enough uses of the divisor to make the transform worthwhile.
8694   SDValue N1 = N->getOperand(1);
8695   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8696   if (!MinUses || N1->use_size() < MinUses)
8697     return SDValue();
8698 
8699   // Find all FDIV users of the same divisor.
8700   // Use a set because duplicates may be present in the user list.
8701   SetVector<SDNode *> Users;
8702   for (auto *U : N1->uses()) {
8703     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8704       // This division is eligible for optimization only if global unsafe math
8705       // is enabled or if this division allows reciprocal formation.
8706       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8707         Users.insert(U);
8708     }
8709   }
8710 
8711   // Now that we have the actual number of divisor uses, make sure it meets
8712   // the minimum threshold specified by the target.
8713   if (Users.size() < MinUses)
8714     return SDValue();
8715 
8716   EVT VT = N->getValueType(0);
8717   SDLoc DL(N);
8718   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8719   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8720 
8721   // Dividend / Divisor -> Dividend * Reciprocal
8722   for (auto *U : Users) {
8723     SDValue Dividend = U->getOperand(0);
8724     if (Dividend != FPOne) {
8725       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8726                                     Reciprocal, Flags);
8727       CombineTo(U, NewNode);
8728     } else if (U != Reciprocal.getNode()) {
8729       // In the absence of fast-math-flags, this user node is always the
8730       // same node as Reciprocal, but with FMF they may be different nodes.
8731       CombineTo(U, Reciprocal);
8732     }
8733   }
8734   return SDValue(N, 0);  // N was replaced.
8735 }
8736 
8737 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8738   SDValue N0 = N->getOperand(0);
8739   SDValue N1 = N->getOperand(1);
8740   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8741   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8742   EVT VT = N->getValueType(0);
8743   SDLoc DL(N);
8744   const TargetOptions &Options = DAG.getTarget().Options;
8745   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8746 
8747   // fold vector ops
8748   if (VT.isVector())
8749     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8750       return FoldedVOp;
8751 
8752   // fold (fdiv c1, c2) -> c1/c2
8753   if (N0CFP && N1CFP)
8754     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8755 
8756   if (Options.UnsafeFPMath) {
8757     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8758     if (N1CFP) {
8759       // Compute the reciprocal 1.0 / c2.
8760       APFloat N1APF = N1CFP->getValueAPF();
8761       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8762       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8763       // Only do the transform if the reciprocal is a legal fp immediate that
8764       // isn't too nasty (eg NaN, denormal, ...).
8765       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8766           (!LegalOperations ||
8767            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8768            // backend)... we should handle this gracefully after Legalize.
8769            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8770            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8771            TLI.isFPImmLegal(Recip, VT)))
8772         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8773                            DAG.getConstantFP(Recip, DL, VT), Flags);
8774     }
8775 
8776     // If this FDIV is part of a reciprocal square root, it may be folded
8777     // into a target-specific square root estimate instruction.
8778     if (N1.getOpcode() == ISD::FSQRT) {
8779       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8780         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8781       }
8782     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8783                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8784       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8785                                           Flags)) {
8786         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8787         AddToWorklist(RV.getNode());
8788         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8789       }
8790     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8791                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8792       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8793                                           Flags)) {
8794         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8795         AddToWorklist(RV.getNode());
8796         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8797       }
8798     } else if (N1.getOpcode() == ISD::FMUL) {
8799       // Look through an FMUL. Even though this won't remove the FDIV directly,
8800       // it's still worthwhile to get rid of the FSQRT if possible.
8801       SDValue SqrtOp;
8802       SDValue OtherOp;
8803       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8804         SqrtOp = N1.getOperand(0);
8805         OtherOp = N1.getOperand(1);
8806       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8807         SqrtOp = N1.getOperand(1);
8808         OtherOp = N1.getOperand(0);
8809       }
8810       if (SqrtOp.getNode()) {
8811         // We found a FSQRT, so try to make this fold:
8812         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8813         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8814           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8815           AddToWorklist(RV.getNode());
8816           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8817         }
8818       }
8819     }
8820 
8821     // Fold into a reciprocal estimate and multiply instead of a real divide.
8822     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8823       AddToWorklist(RV.getNode());
8824       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8825     }
8826   }
8827 
8828   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8829   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8830     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8831       // Both can be negated for free, check to see if at least one is cheaper
8832       // negated.
8833       if (LHSNeg == 2 || RHSNeg == 2)
8834         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8835                            GetNegatedExpression(N0, DAG, LegalOperations),
8836                            GetNegatedExpression(N1, DAG, LegalOperations),
8837                            Flags);
8838     }
8839   }
8840 
8841   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8842     return CombineRepeatedDivisors;
8843 
8844   return SDValue();
8845 }
8846 
8847 SDValue DAGCombiner::visitFREM(SDNode *N) {
8848   SDValue N0 = N->getOperand(0);
8849   SDValue N1 = N->getOperand(1);
8850   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8851   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8852   EVT VT = N->getValueType(0);
8853 
8854   // fold (frem c1, c2) -> fmod(c1,c2)
8855   if (N0CFP && N1CFP)
8856     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8857                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8858 
8859   return SDValue();
8860 }
8861 
8862 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8863   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8864     return SDValue();
8865 
8866   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8867   // For now, create a Flags object for use with all unsafe math transforms.
8868   SDNodeFlags Flags;
8869   Flags.setUnsafeAlgebra(true);
8870 
8871   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8872   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8873   if (!RV)
8874     return SDValue();
8875 
8876   EVT VT = RV.getValueType();
8877   SDLoc DL(N);
8878   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8879   AddToWorklist(RV.getNode());
8880 
8881   // Unfortunately, RV is now NaN if the input was exactly 0.
8882   // Select out this case and force the answer to 0.
8883   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8884   EVT CCVT = getSetCCResultType(VT);
8885   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8886   AddToWorklist(ZeroCmp.getNode());
8887   AddToWorklist(RV.getNode());
8888 
8889   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8890                      ZeroCmp, Zero, RV);
8891 }
8892 
8893 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8894 /// copysign(x, fp_round(y)) -> copysign(x, y)
8895 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8896   SDValue N1 = N->getOperand(1);
8897   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8898        N1.getOpcode() == ISD::FP_ROUND)) {
8899     // Do not optimize out type conversion of f128 type yet.
8900     // For some targets like x86_64, configuration is changed to keep one f128
8901     // value in one SSE register, but instruction selection cannot handle
8902     // FCOPYSIGN on SSE registers yet.
8903     EVT N1VT = N1->getValueType(0);
8904     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8905     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8906   }
8907   return false;
8908 }
8909 
8910 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8911   SDValue N0 = N->getOperand(0);
8912   SDValue N1 = N->getOperand(1);
8913   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8914   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8915   EVT VT = N->getValueType(0);
8916 
8917   if (N0CFP && N1CFP)  // Constant fold
8918     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8919 
8920   if (N1CFP) {
8921     const APFloat& V = N1CFP->getValueAPF();
8922     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8923     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8924     if (!V.isNegative()) {
8925       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8926         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8927     } else {
8928       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8929         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8930                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8931     }
8932   }
8933 
8934   // copysign(fabs(x), y) -> copysign(x, y)
8935   // copysign(fneg(x), y) -> copysign(x, y)
8936   // copysign(copysign(x,z), y) -> copysign(x, y)
8937   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8938       N0.getOpcode() == ISD::FCOPYSIGN)
8939     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8940                        N0.getOperand(0), N1);
8941 
8942   // copysign(x, abs(y)) -> abs(x)
8943   if (N1.getOpcode() == ISD::FABS)
8944     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8945 
8946   // copysign(x, copysign(y,z)) -> copysign(x, z)
8947   if (N1.getOpcode() == ISD::FCOPYSIGN)
8948     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8949                        N0, N1.getOperand(1));
8950 
8951   // copysign(x, fp_extend(y)) -> copysign(x, y)
8952   // copysign(x, fp_round(y)) -> copysign(x, y)
8953   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8954     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8955                        N0, N1.getOperand(0));
8956 
8957   return SDValue();
8958 }
8959 
8960 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8961   SDValue N0 = N->getOperand(0);
8962   EVT VT = N->getValueType(0);
8963   EVT OpVT = N0.getValueType();
8964 
8965   // fold (sint_to_fp c1) -> c1fp
8966   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
8967       // ...but only if the target supports immediate floating-point values
8968       (!LegalOperations ||
8969        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8970     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8971 
8972   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8973   // but UINT_TO_FP is legal on this target, try to convert.
8974   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8975       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8976     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8977     if (DAG.SignBitIsZero(N0))
8978       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8979   }
8980 
8981   // The next optimizations are desirable only if SELECT_CC can be lowered.
8982   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8983     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8984     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8985         !VT.isVector() &&
8986         (!LegalOperations ||
8987          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8988       SDLoc DL(N);
8989       SDValue Ops[] =
8990         { N0.getOperand(0), N0.getOperand(1),
8991           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8992           N0.getOperand(2) };
8993       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8994     }
8995 
8996     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8997     //      (select_cc x, y, 1.0, 0.0,, cc)
8998     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8999         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9000         (!LegalOperations ||
9001          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9002       SDLoc DL(N);
9003       SDValue Ops[] =
9004         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9005           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9006           N0.getOperand(0).getOperand(2) };
9007       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9008     }
9009   }
9010 
9011   return SDValue();
9012 }
9013 
9014 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9015   SDValue N0 = N->getOperand(0);
9016   EVT VT = N->getValueType(0);
9017   EVT OpVT = N0.getValueType();
9018 
9019   // fold (uint_to_fp c1) -> c1fp
9020   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9021       // ...but only if the target supports immediate floating-point values
9022       (!LegalOperations ||
9023        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9024     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9025 
9026   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9027   // but SINT_TO_FP is legal on this target, try to convert.
9028   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9029       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9030     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9031     if (DAG.SignBitIsZero(N0))
9032       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9033   }
9034 
9035   // The next optimizations are desirable only if SELECT_CC can be lowered.
9036   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9037     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9038 
9039     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9040         (!LegalOperations ||
9041          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9042       SDLoc DL(N);
9043       SDValue Ops[] =
9044         { N0.getOperand(0), N0.getOperand(1),
9045           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9046           N0.getOperand(2) };
9047       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9048     }
9049   }
9050 
9051   return SDValue();
9052 }
9053 
9054 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9055 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9056   SDValue N0 = N->getOperand(0);
9057   EVT VT = N->getValueType(0);
9058 
9059   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9060     return SDValue();
9061 
9062   SDValue Src = N0.getOperand(0);
9063   EVT SrcVT = Src.getValueType();
9064   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9065   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9066 
9067   // We can safely assume the conversion won't overflow the output range,
9068   // because (for example) (uint8_t)18293.f is undefined behavior.
9069 
9070   // Since we can assume the conversion won't overflow, our decision as to
9071   // whether the input will fit in the float should depend on the minimum
9072   // of the input range and output range.
9073 
9074   // This means this is also safe for a signed input and unsigned output, since
9075   // a negative input would lead to undefined behavior.
9076   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9077   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9078   unsigned ActualSize = std::min(InputSize, OutputSize);
9079   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9080 
9081   // We can only fold away the float conversion if the input range can be
9082   // represented exactly in the float range.
9083   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9084     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9085       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9086                                                        : ISD::ZERO_EXTEND;
9087       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9088     }
9089     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9090       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9091     return DAG.getBitcast(VT, Src);
9092   }
9093   return SDValue();
9094 }
9095 
9096 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9097   SDValue N0 = N->getOperand(0);
9098   EVT VT = N->getValueType(0);
9099 
9100   // fold (fp_to_sint c1fp) -> c1
9101   if (isConstantFPBuildVectorOrConstantFP(N0))
9102     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9103 
9104   return FoldIntToFPToInt(N, DAG);
9105 }
9106 
9107 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9108   SDValue N0 = N->getOperand(0);
9109   EVT VT = N->getValueType(0);
9110 
9111   // fold (fp_to_uint c1fp) -> c1
9112   if (isConstantFPBuildVectorOrConstantFP(N0))
9113     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9114 
9115   return FoldIntToFPToInt(N, DAG);
9116 }
9117 
9118 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9119   SDValue N0 = N->getOperand(0);
9120   SDValue N1 = N->getOperand(1);
9121   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9122   EVT VT = N->getValueType(0);
9123 
9124   // fold (fp_round c1fp) -> c1fp
9125   if (N0CFP)
9126     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9127 
9128   // fold (fp_round (fp_extend x)) -> x
9129   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9130     return N0.getOperand(0);
9131 
9132   // fold (fp_round (fp_round x)) -> (fp_round x)
9133   if (N0.getOpcode() == ISD::FP_ROUND) {
9134     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9135     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9136 
9137     // Skip this folding if it results in an fp_round from f80 to f16.
9138     //
9139     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9140     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9141     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9142     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9143     // x86.
9144     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9145       return SDValue();
9146 
9147     // If the first fp_round isn't a value preserving truncation, it might
9148     // introduce a tie in the second fp_round, that wouldn't occur in the
9149     // single-step fp_round we want to fold to.
9150     // In other words, double rounding isn't the same as rounding.
9151     // Also, this is a value preserving truncation iff both fp_round's are.
9152     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9153       SDLoc DL(N);
9154       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9155                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9156     }
9157   }
9158 
9159   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9160   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9161     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9162                               N0.getOperand(0), N1);
9163     AddToWorklist(Tmp.getNode());
9164     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9165                        Tmp, N0.getOperand(1));
9166   }
9167 
9168   return SDValue();
9169 }
9170 
9171 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9172   SDValue N0 = N->getOperand(0);
9173   EVT VT = N->getValueType(0);
9174   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9175   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9176 
9177   // fold (fp_round_inreg c1fp) -> c1fp
9178   if (N0CFP && isTypeLegal(EVT)) {
9179     SDLoc DL(N);
9180     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9181     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9182   }
9183 
9184   return SDValue();
9185 }
9186 
9187 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9188   SDValue N0 = N->getOperand(0);
9189   EVT VT = N->getValueType(0);
9190 
9191   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9192   if (N->hasOneUse() &&
9193       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9194     return SDValue();
9195 
9196   // fold (fp_extend c1fp) -> c1fp
9197   if (isConstantFPBuildVectorOrConstantFP(N0))
9198     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9199 
9200   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9201   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9202       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9203     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9204 
9205   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9206   // value of X.
9207   if (N0.getOpcode() == ISD::FP_ROUND
9208       && N0.getNode()->getConstantOperandVal(1) == 1) {
9209     SDValue In = N0.getOperand(0);
9210     if (In.getValueType() == VT) return In;
9211     if (VT.bitsLT(In.getValueType()))
9212       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9213                          In, N0.getOperand(1));
9214     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9215   }
9216 
9217   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9218   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9219        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9220     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9221     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9222                                      LN0->getChain(),
9223                                      LN0->getBasePtr(), N0.getValueType(),
9224                                      LN0->getMemOperand());
9225     CombineTo(N, ExtLoad);
9226     CombineTo(N0.getNode(),
9227               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9228                           N0.getValueType(), ExtLoad,
9229                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9230               ExtLoad.getValue(1));
9231     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9232   }
9233 
9234   return SDValue();
9235 }
9236 
9237 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9238   SDValue N0 = N->getOperand(0);
9239   EVT VT = N->getValueType(0);
9240 
9241   // fold (fceil c1) -> fceil(c1)
9242   if (isConstantFPBuildVectorOrConstantFP(N0))
9243     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9244 
9245   return SDValue();
9246 }
9247 
9248 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9249   SDValue N0 = N->getOperand(0);
9250   EVT VT = N->getValueType(0);
9251 
9252   // fold (ftrunc c1) -> ftrunc(c1)
9253   if (isConstantFPBuildVectorOrConstantFP(N0))
9254     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9255 
9256   return SDValue();
9257 }
9258 
9259 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9260   SDValue N0 = N->getOperand(0);
9261   EVT VT = N->getValueType(0);
9262 
9263   // fold (ffloor c1) -> ffloor(c1)
9264   if (isConstantFPBuildVectorOrConstantFP(N0))
9265     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9266 
9267   return SDValue();
9268 }
9269 
9270 // FIXME: FNEG and FABS have a lot in common; refactor.
9271 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9272   SDValue N0 = N->getOperand(0);
9273   EVT VT = N->getValueType(0);
9274 
9275   // Constant fold FNEG.
9276   if (isConstantFPBuildVectorOrConstantFP(N0))
9277     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9278 
9279   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9280                          &DAG.getTarget().Options))
9281     return GetNegatedExpression(N0, DAG, LegalOperations);
9282 
9283   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9284   // constant pool values.
9285   if (!TLI.isFNegFree(VT) &&
9286       N0.getOpcode() == ISD::BITCAST &&
9287       N0.getNode()->hasOneUse()) {
9288     SDValue Int = N0.getOperand(0);
9289     EVT IntVT = Int.getValueType();
9290     if (IntVT.isInteger() && !IntVT.isVector()) {
9291       APInt SignMask;
9292       if (N0.getValueType().isVector()) {
9293         // For a vector, get a mask such as 0x80... per scalar element
9294         // and splat it.
9295         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9296         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9297       } else {
9298         // For a scalar, just generate 0x80...
9299         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9300       }
9301       SDLoc DL0(N0);
9302       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9303                         DAG.getConstant(SignMask, DL0, IntVT));
9304       AddToWorklist(Int.getNode());
9305       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9306     }
9307   }
9308 
9309   // (fneg (fmul c, x)) -> (fmul -c, x)
9310   if (N0.getOpcode() == ISD::FMUL &&
9311       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9312     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9313     if (CFP1) {
9314       APFloat CVal = CFP1->getValueAPF();
9315       CVal.changeSign();
9316       if (Level >= AfterLegalizeDAG &&
9317           (TLI.isFPImmLegal(CVal, VT) ||
9318            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9319         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9320                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9321                                        N0.getOperand(1)),
9322                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9323     }
9324   }
9325 
9326   return SDValue();
9327 }
9328 
9329 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9330   SDValue N0 = N->getOperand(0);
9331   SDValue N1 = N->getOperand(1);
9332   EVT VT = N->getValueType(0);
9333   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9334   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9335 
9336   if (N0CFP && N1CFP) {
9337     const APFloat &C0 = N0CFP->getValueAPF();
9338     const APFloat &C1 = N1CFP->getValueAPF();
9339     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9340   }
9341 
9342   // Canonicalize to constant on RHS.
9343   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9344      !isConstantFPBuildVectorOrConstantFP(N1))
9345     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9346 
9347   return SDValue();
9348 }
9349 
9350 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9351   SDValue N0 = N->getOperand(0);
9352   SDValue N1 = N->getOperand(1);
9353   EVT VT = N->getValueType(0);
9354   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9355   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9356 
9357   if (N0CFP && N1CFP) {
9358     const APFloat &C0 = N0CFP->getValueAPF();
9359     const APFloat &C1 = N1CFP->getValueAPF();
9360     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9361   }
9362 
9363   // Canonicalize to constant on RHS.
9364   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9365      !isConstantFPBuildVectorOrConstantFP(N1))
9366     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9367 
9368   return SDValue();
9369 }
9370 
9371 SDValue DAGCombiner::visitFABS(SDNode *N) {
9372   SDValue N0 = N->getOperand(0);
9373   EVT VT = N->getValueType(0);
9374 
9375   // fold (fabs c1) -> fabs(c1)
9376   if (isConstantFPBuildVectorOrConstantFP(N0))
9377     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9378 
9379   // fold (fabs (fabs x)) -> (fabs x)
9380   if (N0.getOpcode() == ISD::FABS)
9381     return N->getOperand(0);
9382 
9383   // fold (fabs (fneg x)) -> (fabs x)
9384   // fold (fabs (fcopysign x, y)) -> (fabs x)
9385   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9386     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9387 
9388   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9389   // constant pool values.
9390   if (!TLI.isFAbsFree(VT) &&
9391       N0.getOpcode() == ISD::BITCAST &&
9392       N0.getNode()->hasOneUse()) {
9393     SDValue Int = N0.getOperand(0);
9394     EVT IntVT = Int.getValueType();
9395     if (IntVT.isInteger() && !IntVT.isVector()) {
9396       APInt SignMask;
9397       if (N0.getValueType().isVector()) {
9398         // For a vector, get a mask such as 0x7f... per scalar element
9399         // and splat it.
9400         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9401         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9402       } else {
9403         // For a scalar, just generate 0x7f...
9404         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9405       }
9406       SDLoc DL(N0);
9407       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9408                         DAG.getConstant(SignMask, DL, IntVT));
9409       AddToWorklist(Int.getNode());
9410       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9411     }
9412   }
9413 
9414   return SDValue();
9415 }
9416 
9417 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9418   SDValue Chain = N->getOperand(0);
9419   SDValue N1 = N->getOperand(1);
9420   SDValue N2 = N->getOperand(2);
9421 
9422   // If N is a constant we could fold this into a fallthrough or unconditional
9423   // branch. However that doesn't happen very often in normal code, because
9424   // Instcombine/SimplifyCFG should have handled the available opportunities.
9425   // If we did this folding here, it would be necessary to update the
9426   // MachineBasicBlock CFG, which is awkward.
9427 
9428   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9429   // on the target.
9430   if (N1.getOpcode() == ISD::SETCC &&
9431       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9432                                    N1.getOperand(0).getValueType())) {
9433     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9434                        Chain, N1.getOperand(2),
9435                        N1.getOperand(0), N1.getOperand(1), N2);
9436   }
9437 
9438   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9439       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9440        (N1.getOperand(0).hasOneUse() &&
9441         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9442     SDNode *Trunc = nullptr;
9443     if (N1.getOpcode() == ISD::TRUNCATE) {
9444       // Look pass the truncate.
9445       Trunc = N1.getNode();
9446       N1 = N1.getOperand(0);
9447     }
9448 
9449     // Match this pattern so that we can generate simpler code:
9450     //
9451     //   %a = ...
9452     //   %b = and i32 %a, 2
9453     //   %c = srl i32 %b, 1
9454     //   brcond i32 %c ...
9455     //
9456     // into
9457     //
9458     //   %a = ...
9459     //   %b = and i32 %a, 2
9460     //   %c = setcc eq %b, 0
9461     //   brcond %c ...
9462     //
9463     // This applies only when the AND constant value has one bit set and the
9464     // SRL constant is equal to the log2 of the AND constant. The back-end is
9465     // smart enough to convert the result into a TEST/JMP sequence.
9466     SDValue Op0 = N1.getOperand(0);
9467     SDValue Op1 = N1.getOperand(1);
9468 
9469     if (Op0.getOpcode() == ISD::AND &&
9470         Op1.getOpcode() == ISD::Constant) {
9471       SDValue AndOp1 = Op0.getOperand(1);
9472 
9473       if (AndOp1.getOpcode() == ISD::Constant) {
9474         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9475 
9476         if (AndConst.isPowerOf2() &&
9477             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9478           SDLoc DL(N);
9479           SDValue SetCC =
9480             DAG.getSetCC(DL,
9481                          getSetCCResultType(Op0.getValueType()),
9482                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9483                          ISD::SETNE);
9484 
9485           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9486                                           MVT::Other, Chain, SetCC, N2);
9487           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9488           // will convert it back to (X & C1) >> C2.
9489           CombineTo(N, NewBRCond, false);
9490           // Truncate is dead.
9491           if (Trunc)
9492             deleteAndRecombine(Trunc);
9493           // Replace the uses of SRL with SETCC
9494           WorklistRemover DeadNodes(*this);
9495           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9496           deleteAndRecombine(N1.getNode());
9497           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9498         }
9499       }
9500     }
9501 
9502     if (Trunc)
9503       // Restore N1 if the above transformation doesn't match.
9504       N1 = N->getOperand(1);
9505   }
9506 
9507   // Transform br(xor(x, y)) -> br(x != y)
9508   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9509   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9510     SDNode *TheXor = N1.getNode();
9511     SDValue Op0 = TheXor->getOperand(0);
9512     SDValue Op1 = TheXor->getOperand(1);
9513     if (Op0.getOpcode() == Op1.getOpcode()) {
9514       // Avoid missing important xor optimizations.
9515       if (SDValue Tmp = visitXOR(TheXor)) {
9516         if (Tmp.getNode() != TheXor) {
9517           DEBUG(dbgs() << "\nReplacing.8 ";
9518                 TheXor->dump(&DAG);
9519                 dbgs() << "\nWith: ";
9520                 Tmp.getNode()->dump(&DAG);
9521                 dbgs() << '\n');
9522           WorklistRemover DeadNodes(*this);
9523           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9524           deleteAndRecombine(TheXor);
9525           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9526                              MVT::Other, Chain, Tmp, N2);
9527         }
9528 
9529         // visitXOR has changed XOR's operands or replaced the XOR completely,
9530         // bail out.
9531         return SDValue(N, 0);
9532       }
9533     }
9534 
9535     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9536       bool Equal = false;
9537       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9538           Op0.getOpcode() == ISD::XOR) {
9539         TheXor = Op0.getNode();
9540         Equal = true;
9541       }
9542 
9543       EVT SetCCVT = N1.getValueType();
9544       if (LegalTypes)
9545         SetCCVT = getSetCCResultType(SetCCVT);
9546       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9547                                    SetCCVT,
9548                                    Op0, Op1,
9549                                    Equal ? ISD::SETEQ : ISD::SETNE);
9550       // Replace the uses of XOR with SETCC
9551       WorklistRemover DeadNodes(*this);
9552       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9553       deleteAndRecombine(N1.getNode());
9554       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9555                          MVT::Other, Chain, SetCC, N2);
9556     }
9557   }
9558 
9559   return SDValue();
9560 }
9561 
9562 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9563 //
9564 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9565   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9566   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9567 
9568   // If N is a constant we could fold this into a fallthrough or unconditional
9569   // branch. However that doesn't happen very often in normal code, because
9570   // Instcombine/SimplifyCFG should have handled the available opportunities.
9571   // If we did this folding here, it would be necessary to update the
9572   // MachineBasicBlock CFG, which is awkward.
9573 
9574   // Use SimplifySetCC to simplify SETCC's.
9575   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9576                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9577                                false);
9578   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9579 
9580   // fold to a simpler setcc
9581   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9582     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9583                        N->getOperand(0), Simp.getOperand(2),
9584                        Simp.getOperand(0), Simp.getOperand(1),
9585                        N->getOperand(4));
9586 
9587   return SDValue();
9588 }
9589 
9590 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9591 /// and that N may be folded in the load / store addressing mode.
9592 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9593                                     SelectionDAG &DAG,
9594                                     const TargetLowering &TLI) {
9595   EVT VT;
9596   unsigned AS;
9597 
9598   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9599     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9600       return false;
9601     VT = LD->getMemoryVT();
9602     AS = LD->getAddressSpace();
9603   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9604     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9605       return false;
9606     VT = ST->getMemoryVT();
9607     AS = ST->getAddressSpace();
9608   } else
9609     return false;
9610 
9611   TargetLowering::AddrMode AM;
9612   if (N->getOpcode() == ISD::ADD) {
9613     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9614     if (Offset)
9615       // [reg +/- imm]
9616       AM.BaseOffs = Offset->getSExtValue();
9617     else
9618       // [reg +/- reg]
9619       AM.Scale = 1;
9620   } else if (N->getOpcode() == ISD::SUB) {
9621     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9622     if (Offset)
9623       // [reg +/- imm]
9624       AM.BaseOffs = -Offset->getSExtValue();
9625     else
9626       // [reg +/- reg]
9627       AM.Scale = 1;
9628   } else
9629     return false;
9630 
9631   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9632                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9633 }
9634 
9635 /// Try turning a load/store into a pre-indexed load/store when the base
9636 /// pointer is an add or subtract and it has other uses besides the load/store.
9637 /// After the transformation, the new indexed load/store has effectively folded
9638 /// the add/subtract in and all of its other uses are redirected to the
9639 /// new load/store.
9640 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9641   if (Level < AfterLegalizeDAG)
9642     return false;
9643 
9644   bool isLoad = true;
9645   SDValue Ptr;
9646   EVT VT;
9647   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9648     if (LD->isIndexed())
9649       return false;
9650     VT = LD->getMemoryVT();
9651     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9652         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9653       return false;
9654     Ptr = LD->getBasePtr();
9655   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9656     if (ST->isIndexed())
9657       return false;
9658     VT = ST->getMemoryVT();
9659     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9660         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9661       return false;
9662     Ptr = ST->getBasePtr();
9663     isLoad = false;
9664   } else {
9665     return false;
9666   }
9667 
9668   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9669   // out.  There is no reason to make this a preinc/predec.
9670   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9671       Ptr.getNode()->hasOneUse())
9672     return false;
9673 
9674   // Ask the target to do addressing mode selection.
9675   SDValue BasePtr;
9676   SDValue Offset;
9677   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9678   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9679     return false;
9680 
9681   // Backends without true r+i pre-indexed forms may need to pass a
9682   // constant base with a variable offset so that constant coercion
9683   // will work with the patterns in canonical form.
9684   bool Swapped = false;
9685   if (isa<ConstantSDNode>(BasePtr)) {
9686     std::swap(BasePtr, Offset);
9687     Swapped = true;
9688   }
9689 
9690   // Don't create a indexed load / store with zero offset.
9691   if (isNullConstant(Offset))
9692     return false;
9693 
9694   // Try turning it into a pre-indexed load / store except when:
9695   // 1) The new base ptr is a frame index.
9696   // 2) If N is a store and the new base ptr is either the same as or is a
9697   //    predecessor of the value being stored.
9698   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9699   //    that would create a cycle.
9700   // 4) All uses are load / store ops that use it as old base ptr.
9701 
9702   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9703   // (plus the implicit offset) to a register to preinc anyway.
9704   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9705     return false;
9706 
9707   // Check #2.
9708   if (!isLoad) {
9709     SDValue Val = cast<StoreSDNode>(N)->getValue();
9710     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9711       return false;
9712   }
9713 
9714   // Caches for hasPredecessorHelper.
9715   SmallPtrSet<const SDNode *, 32> Visited;
9716   SmallVector<const SDNode *, 16> Worklist;
9717   Worklist.push_back(N);
9718 
9719   // If the offset is a constant, there may be other adds of constants that
9720   // can be folded with this one. We should do this to avoid having to keep
9721   // a copy of the original base pointer.
9722   SmallVector<SDNode *, 16> OtherUses;
9723   if (isa<ConstantSDNode>(Offset))
9724     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9725                               UE = BasePtr.getNode()->use_end();
9726          UI != UE; ++UI) {
9727       SDUse &Use = UI.getUse();
9728       // Skip the use that is Ptr and uses of other results from BasePtr's
9729       // node (important for nodes that return multiple results).
9730       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9731         continue;
9732 
9733       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9734         continue;
9735 
9736       if (Use.getUser()->getOpcode() != ISD::ADD &&
9737           Use.getUser()->getOpcode() != ISD::SUB) {
9738         OtherUses.clear();
9739         break;
9740       }
9741 
9742       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9743       if (!isa<ConstantSDNode>(Op1)) {
9744         OtherUses.clear();
9745         break;
9746       }
9747 
9748       // FIXME: In some cases, we can be smarter about this.
9749       if (Op1.getValueType() != Offset.getValueType()) {
9750         OtherUses.clear();
9751         break;
9752       }
9753 
9754       OtherUses.push_back(Use.getUser());
9755     }
9756 
9757   if (Swapped)
9758     std::swap(BasePtr, Offset);
9759 
9760   // Now check for #3 and #4.
9761   bool RealUse = false;
9762 
9763   for (SDNode *Use : Ptr.getNode()->uses()) {
9764     if (Use == N)
9765       continue;
9766     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9767       return false;
9768 
9769     // If Ptr may be folded in addressing mode of other use, then it's
9770     // not profitable to do this transformation.
9771     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9772       RealUse = true;
9773   }
9774 
9775   if (!RealUse)
9776     return false;
9777 
9778   SDValue Result;
9779   if (isLoad)
9780     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9781                                 BasePtr, Offset, AM);
9782   else
9783     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9784                                  BasePtr, Offset, AM);
9785   ++PreIndexedNodes;
9786   ++NodesCombined;
9787   DEBUG(dbgs() << "\nReplacing.4 ";
9788         N->dump(&DAG);
9789         dbgs() << "\nWith: ";
9790         Result.getNode()->dump(&DAG);
9791         dbgs() << '\n');
9792   WorklistRemover DeadNodes(*this);
9793   if (isLoad) {
9794     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9795     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9796   } else {
9797     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9798   }
9799 
9800   // Finally, since the node is now dead, remove it from the graph.
9801   deleteAndRecombine(N);
9802 
9803   if (Swapped)
9804     std::swap(BasePtr, Offset);
9805 
9806   // Replace other uses of BasePtr that can be updated to use Ptr
9807   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9808     unsigned OffsetIdx = 1;
9809     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9810       OffsetIdx = 0;
9811     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9812            BasePtr.getNode() && "Expected BasePtr operand");
9813 
9814     // We need to replace ptr0 in the following expression:
9815     //   x0 * offset0 + y0 * ptr0 = t0
9816     // knowing that
9817     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9818     //
9819     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9820     // indexed load/store and the expresion that needs to be re-written.
9821     //
9822     // Therefore, we have:
9823     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9824 
9825     ConstantSDNode *CN =
9826       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9827     int X0, X1, Y0, Y1;
9828     APInt Offset0 = CN->getAPIntValue();
9829     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9830 
9831     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9832     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9833     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9834     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9835 
9836     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9837 
9838     APInt CNV = Offset0;
9839     if (X0 < 0) CNV = -CNV;
9840     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9841     else CNV = CNV - Offset1;
9842 
9843     SDLoc DL(OtherUses[i]);
9844 
9845     // We can now generate the new expression.
9846     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9847     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9848 
9849     SDValue NewUse = DAG.getNode(Opcode,
9850                                  DL,
9851                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9852     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9853     deleteAndRecombine(OtherUses[i]);
9854   }
9855 
9856   // Replace the uses of Ptr with uses of the updated base value.
9857   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9858   deleteAndRecombine(Ptr.getNode());
9859 
9860   return true;
9861 }
9862 
9863 /// Try to combine a load/store with a add/sub of the base pointer node into a
9864 /// post-indexed load/store. The transformation folded the add/subtract into the
9865 /// new indexed load/store effectively and all of its uses are redirected to the
9866 /// new load/store.
9867 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9868   if (Level < AfterLegalizeDAG)
9869     return false;
9870 
9871   bool isLoad = true;
9872   SDValue Ptr;
9873   EVT VT;
9874   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9875     if (LD->isIndexed())
9876       return false;
9877     VT = LD->getMemoryVT();
9878     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9879         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9880       return false;
9881     Ptr = LD->getBasePtr();
9882   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9883     if (ST->isIndexed())
9884       return false;
9885     VT = ST->getMemoryVT();
9886     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9887         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9888       return false;
9889     Ptr = ST->getBasePtr();
9890     isLoad = false;
9891   } else {
9892     return false;
9893   }
9894 
9895   if (Ptr.getNode()->hasOneUse())
9896     return false;
9897 
9898   for (SDNode *Op : Ptr.getNode()->uses()) {
9899     if (Op == N ||
9900         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9901       continue;
9902 
9903     SDValue BasePtr;
9904     SDValue Offset;
9905     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9906     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9907       // Don't create a indexed load / store with zero offset.
9908       if (isNullConstant(Offset))
9909         continue;
9910 
9911       // Try turning it into a post-indexed load / store except when
9912       // 1) All uses are load / store ops that use it as base ptr (and
9913       //    it may be folded as addressing mmode).
9914       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9915       //    nor a successor of N. Otherwise, if Op is folded that would
9916       //    create a cycle.
9917 
9918       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9919         continue;
9920 
9921       // Check for #1.
9922       bool TryNext = false;
9923       for (SDNode *Use : BasePtr.getNode()->uses()) {
9924         if (Use == Ptr.getNode())
9925           continue;
9926 
9927         // If all the uses are load / store addresses, then don't do the
9928         // transformation.
9929         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9930           bool RealUse = false;
9931           for (SDNode *UseUse : Use->uses()) {
9932             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9933               RealUse = true;
9934           }
9935 
9936           if (!RealUse) {
9937             TryNext = true;
9938             break;
9939           }
9940         }
9941       }
9942 
9943       if (TryNext)
9944         continue;
9945 
9946       // Check for #2
9947       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9948         SDValue Result = isLoad
9949           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9950                                BasePtr, Offset, AM)
9951           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9952                                 BasePtr, Offset, AM);
9953         ++PostIndexedNodes;
9954         ++NodesCombined;
9955         DEBUG(dbgs() << "\nReplacing.5 ";
9956               N->dump(&DAG);
9957               dbgs() << "\nWith: ";
9958               Result.getNode()->dump(&DAG);
9959               dbgs() << '\n');
9960         WorklistRemover DeadNodes(*this);
9961         if (isLoad) {
9962           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9963           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9964         } else {
9965           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9966         }
9967 
9968         // Finally, since the node is now dead, remove it from the graph.
9969         deleteAndRecombine(N);
9970 
9971         // Replace the uses of Use with uses of the updated base value.
9972         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9973                                       Result.getValue(isLoad ? 1 : 0));
9974         deleteAndRecombine(Op);
9975         return true;
9976       }
9977     }
9978   }
9979 
9980   return false;
9981 }
9982 
9983 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9984 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9985   ISD::MemIndexedMode AM = LD->getAddressingMode();
9986   assert(AM != ISD::UNINDEXED);
9987   SDValue BP = LD->getOperand(1);
9988   SDValue Inc = LD->getOperand(2);
9989 
9990   // Some backends use TargetConstants for load offsets, but don't expect
9991   // TargetConstants in general ADD nodes. We can convert these constants into
9992   // regular Constants (if the constant is not opaque).
9993   assert((Inc.getOpcode() != ISD::TargetConstant ||
9994           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9995          "Cannot split out indexing using opaque target constants");
9996   if (Inc.getOpcode() == ISD::TargetConstant) {
9997     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9998     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9999                           ConstInc->getValueType(0));
10000   }
10001 
10002   unsigned Opc =
10003       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10004   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10005 }
10006 
10007 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10008   LoadSDNode *LD  = cast<LoadSDNode>(N);
10009   SDValue Chain = LD->getChain();
10010   SDValue Ptr   = LD->getBasePtr();
10011 
10012   // If load is not volatile and there are no uses of the loaded value (and
10013   // the updated indexed value in case of indexed loads), change uses of the
10014   // chain value into uses of the chain input (i.e. delete the dead load).
10015   if (!LD->isVolatile()) {
10016     if (N->getValueType(1) == MVT::Other) {
10017       // Unindexed loads.
10018       if (!N->hasAnyUseOfValue(0)) {
10019         // It's not safe to use the two value CombineTo variant here. e.g.
10020         // v1, chain2 = load chain1, loc
10021         // v2, chain3 = load chain2, loc
10022         // v3         = add v2, c
10023         // Now we replace use of chain2 with chain1.  This makes the second load
10024         // isomorphic to the one we are deleting, and thus makes this load live.
10025         DEBUG(dbgs() << "\nReplacing.6 ";
10026               N->dump(&DAG);
10027               dbgs() << "\nWith chain: ";
10028               Chain.getNode()->dump(&DAG);
10029               dbgs() << "\n");
10030         WorklistRemover DeadNodes(*this);
10031         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10032 
10033         if (N->use_empty())
10034           deleteAndRecombine(N);
10035 
10036         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10037       }
10038     } else {
10039       // Indexed loads.
10040       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10041 
10042       // If this load has an opaque TargetConstant offset, then we cannot split
10043       // the indexing into an add/sub directly (that TargetConstant may not be
10044       // valid for a different type of node, and we cannot convert an opaque
10045       // target constant into a regular constant).
10046       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10047                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10048 
10049       if (!N->hasAnyUseOfValue(0) &&
10050           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10051         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10052         SDValue Index;
10053         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10054           Index = SplitIndexingFromLoad(LD);
10055           // Try to fold the base pointer arithmetic into subsequent loads and
10056           // stores.
10057           AddUsersToWorklist(N);
10058         } else
10059           Index = DAG.getUNDEF(N->getValueType(1));
10060         DEBUG(dbgs() << "\nReplacing.7 ";
10061               N->dump(&DAG);
10062               dbgs() << "\nWith: ";
10063               Undef.getNode()->dump(&DAG);
10064               dbgs() << " and 2 other values\n");
10065         WorklistRemover DeadNodes(*this);
10066         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10067         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10068         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10069         deleteAndRecombine(N);
10070         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10071       }
10072     }
10073   }
10074 
10075   // If this load is directly stored, replace the load value with the stored
10076   // value.
10077   // TODO: Handle store large -> read small portion.
10078   // TODO: Handle TRUNCSTORE/LOADEXT
10079   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10080     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10081       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10082       if (PrevST->getBasePtr() == Ptr &&
10083           PrevST->getValue().getValueType() == N->getValueType(0))
10084       return CombineTo(N, Chain.getOperand(1), Chain);
10085     }
10086   }
10087 
10088   // Try to infer better alignment information than the load already has.
10089   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10090     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10091       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10092         SDValue NewLoad =
10093                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10094                               LD->getValueType(0),
10095                               Chain, Ptr, LD->getPointerInfo(),
10096                               LD->getMemoryVT(),
10097                               LD->isVolatile(), LD->isNonTemporal(),
10098                               LD->isInvariant(), Align, LD->getAAInfo());
10099         if (NewLoad.getNode() != N)
10100           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10101       }
10102     }
10103   }
10104 
10105   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10106                                                   : DAG.getSubtarget().useAA();
10107 #ifndef NDEBUG
10108   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10109       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10110     UseAA = false;
10111 #endif
10112   if (UseAA && LD->isUnindexed()) {
10113     // Walk up chain skipping non-aliasing memory nodes.
10114     SDValue BetterChain = FindBetterChain(N, Chain);
10115 
10116     // If there is a better chain.
10117     if (Chain != BetterChain) {
10118       SDValue ReplLoad;
10119 
10120       // Replace the chain to void dependency.
10121       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10122         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10123                                BetterChain, Ptr, LD->getMemOperand());
10124       } else {
10125         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10126                                   LD->getValueType(0),
10127                                   BetterChain, Ptr, LD->getMemoryVT(),
10128                                   LD->getMemOperand());
10129       }
10130 
10131       // Create token factor to keep old chain connected.
10132       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10133                                   MVT::Other, Chain, ReplLoad.getValue(1));
10134 
10135       // Make sure the new and old chains are cleaned up.
10136       AddToWorklist(Token.getNode());
10137 
10138       // Replace uses with load result and token factor. Don't add users
10139       // to work list.
10140       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10141     }
10142   }
10143 
10144   // Try transforming N to an indexed load.
10145   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10146     return SDValue(N, 0);
10147 
10148   // Try to slice up N to more direct loads if the slices are mapped to
10149   // different register banks or pairing can take place.
10150   if (SliceUpLoad(N))
10151     return SDValue(N, 0);
10152 
10153   return SDValue();
10154 }
10155 
10156 namespace {
10157 /// \brief Helper structure used to slice a load in smaller loads.
10158 /// Basically a slice is obtained from the following sequence:
10159 /// Origin = load Ty1, Base
10160 /// Shift = srl Ty1 Origin, CstTy Amount
10161 /// Inst = trunc Shift to Ty2
10162 ///
10163 /// Then, it will be rewriten into:
10164 /// Slice = load SliceTy, Base + SliceOffset
10165 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10166 ///
10167 /// SliceTy is deduced from the number of bits that are actually used to
10168 /// build Inst.
10169 struct LoadedSlice {
10170   /// \brief Helper structure used to compute the cost of a slice.
10171   struct Cost {
10172     /// Are we optimizing for code size.
10173     bool ForCodeSize;
10174     /// Various cost.
10175     unsigned Loads;
10176     unsigned Truncates;
10177     unsigned CrossRegisterBanksCopies;
10178     unsigned ZExts;
10179     unsigned Shift;
10180 
10181     Cost(bool ForCodeSize = false)
10182         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10183           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10184 
10185     /// \brief Get the cost of one isolated slice.
10186     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10187         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10188           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10189       EVT TruncType = LS.Inst->getValueType(0);
10190       EVT LoadedType = LS.getLoadedType();
10191       if (TruncType != LoadedType &&
10192           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10193         ZExts = 1;
10194     }
10195 
10196     /// \brief Account for slicing gain in the current cost.
10197     /// Slicing provide a few gains like removing a shift or a
10198     /// truncate. This method allows to grow the cost of the original
10199     /// load with the gain from this slice.
10200     void addSliceGain(const LoadedSlice &LS) {
10201       // Each slice saves a truncate.
10202       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10203       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10204                               LS.Inst->getValueType(0)))
10205         ++Truncates;
10206       // If there is a shift amount, this slice gets rid of it.
10207       if (LS.Shift)
10208         ++Shift;
10209       // If this slice can merge a cross register bank copy, account for it.
10210       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10211         ++CrossRegisterBanksCopies;
10212     }
10213 
10214     Cost &operator+=(const Cost &RHS) {
10215       Loads += RHS.Loads;
10216       Truncates += RHS.Truncates;
10217       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10218       ZExts += RHS.ZExts;
10219       Shift += RHS.Shift;
10220       return *this;
10221     }
10222 
10223     bool operator==(const Cost &RHS) const {
10224       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10225              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10226              ZExts == RHS.ZExts && Shift == RHS.Shift;
10227     }
10228 
10229     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10230 
10231     bool operator<(const Cost &RHS) const {
10232       // Assume cross register banks copies are as expensive as loads.
10233       // FIXME: Do we want some more target hooks?
10234       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10235       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10236       // Unless we are optimizing for code size, consider the
10237       // expensive operation first.
10238       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10239         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10240       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10241              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10242     }
10243 
10244     bool operator>(const Cost &RHS) const { return RHS < *this; }
10245 
10246     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10247 
10248     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10249   };
10250   // The last instruction that represent the slice. This should be a
10251   // truncate instruction.
10252   SDNode *Inst;
10253   // The original load instruction.
10254   LoadSDNode *Origin;
10255   // The right shift amount in bits from the original load.
10256   unsigned Shift;
10257   // The DAG from which Origin came from.
10258   // This is used to get some contextual information about legal types, etc.
10259   SelectionDAG *DAG;
10260 
10261   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10262               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10263       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10264 
10265   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10266   /// \return Result is \p BitWidth and has used bits set to 1 and
10267   ///         not used bits set to 0.
10268   APInt getUsedBits() const {
10269     // Reproduce the trunc(lshr) sequence:
10270     // - Start from the truncated value.
10271     // - Zero extend to the desired bit width.
10272     // - Shift left.
10273     assert(Origin && "No original load to compare against.");
10274     unsigned BitWidth = Origin->getValueSizeInBits(0);
10275     assert(Inst && "This slice is not bound to an instruction");
10276     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10277            "Extracted slice is bigger than the whole type!");
10278     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10279     UsedBits.setAllBits();
10280     UsedBits = UsedBits.zext(BitWidth);
10281     UsedBits <<= Shift;
10282     return UsedBits;
10283   }
10284 
10285   /// \brief Get the size of the slice to be loaded in bytes.
10286   unsigned getLoadedSize() const {
10287     unsigned SliceSize = getUsedBits().countPopulation();
10288     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10289     return SliceSize / 8;
10290   }
10291 
10292   /// \brief Get the type that will be loaded for this slice.
10293   /// Note: This may not be the final type for the slice.
10294   EVT getLoadedType() const {
10295     assert(DAG && "Missing context");
10296     LLVMContext &Ctxt = *DAG->getContext();
10297     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10298   }
10299 
10300   /// \brief Get the alignment of the load used for this slice.
10301   unsigned getAlignment() const {
10302     unsigned Alignment = Origin->getAlignment();
10303     unsigned Offset = getOffsetFromBase();
10304     if (Offset != 0)
10305       Alignment = MinAlign(Alignment, Alignment + Offset);
10306     return Alignment;
10307   }
10308 
10309   /// \brief Check if this slice can be rewritten with legal operations.
10310   bool isLegal() const {
10311     // An invalid slice is not legal.
10312     if (!Origin || !Inst || !DAG)
10313       return false;
10314 
10315     // Offsets are for indexed load only, we do not handle that.
10316     if (!Origin->getOffset().isUndef())
10317       return false;
10318 
10319     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10320 
10321     // Check that the type is legal.
10322     EVT SliceType = getLoadedType();
10323     if (!TLI.isTypeLegal(SliceType))
10324       return false;
10325 
10326     // Check that the load is legal for this type.
10327     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10328       return false;
10329 
10330     // Check that the offset can be computed.
10331     // 1. Check its type.
10332     EVT PtrType = Origin->getBasePtr().getValueType();
10333     if (PtrType == MVT::Untyped || PtrType.isExtended())
10334       return false;
10335 
10336     // 2. Check that it fits in the immediate.
10337     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10338       return false;
10339 
10340     // 3. Check that the computation is legal.
10341     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10342       return false;
10343 
10344     // Check that the zext is legal if it needs one.
10345     EVT TruncateType = Inst->getValueType(0);
10346     if (TruncateType != SliceType &&
10347         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10348       return false;
10349 
10350     return true;
10351   }
10352 
10353   /// \brief Get the offset in bytes of this slice in the original chunk of
10354   /// bits.
10355   /// \pre DAG != nullptr.
10356   uint64_t getOffsetFromBase() const {
10357     assert(DAG && "Missing context.");
10358     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10359     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10360     uint64_t Offset = Shift / 8;
10361     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10362     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10363            "The size of the original loaded type is not a multiple of a"
10364            " byte.");
10365     // If Offset is bigger than TySizeInBytes, it means we are loading all
10366     // zeros. This should have been optimized before in the process.
10367     assert(TySizeInBytes > Offset &&
10368            "Invalid shift amount for given loaded size");
10369     if (IsBigEndian)
10370       Offset = TySizeInBytes - Offset - getLoadedSize();
10371     return Offset;
10372   }
10373 
10374   /// \brief Generate the sequence of instructions to load the slice
10375   /// represented by this object and redirect the uses of this slice to
10376   /// this new sequence of instructions.
10377   /// \pre this->Inst && this->Origin are valid Instructions and this
10378   /// object passed the legal check: LoadedSlice::isLegal returned true.
10379   /// \return The last instruction of the sequence used to load the slice.
10380   SDValue loadSlice() const {
10381     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10382     const SDValue &OldBaseAddr = Origin->getBasePtr();
10383     SDValue BaseAddr = OldBaseAddr;
10384     // Get the offset in that chunk of bytes w.r.t. the endianess.
10385     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10386     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10387     if (Offset) {
10388       // BaseAddr = BaseAddr + Offset.
10389       EVT ArithType = BaseAddr.getValueType();
10390       SDLoc DL(Origin);
10391       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10392                               DAG->getConstant(Offset, DL, ArithType));
10393     }
10394 
10395     // Create the type of the loaded slice according to its size.
10396     EVT SliceType = getLoadedType();
10397 
10398     // Create the load for the slice.
10399     SDValue LastInst = DAG->getLoad(
10400         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10401         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10402         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10403     // If the final type is not the same as the loaded type, this means that
10404     // we have to pad with zero. Create a zero extend for that.
10405     EVT FinalType = Inst->getValueType(0);
10406     if (SliceType != FinalType)
10407       LastInst =
10408           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10409     return LastInst;
10410   }
10411 
10412   /// \brief Check if this slice can be merged with an expensive cross register
10413   /// bank copy. E.g.,
10414   /// i = load i32
10415   /// f = bitcast i32 i to float
10416   bool canMergeExpensiveCrossRegisterBankCopy() const {
10417     if (!Inst || !Inst->hasOneUse())
10418       return false;
10419     SDNode *Use = *Inst->use_begin();
10420     if (Use->getOpcode() != ISD::BITCAST)
10421       return false;
10422     assert(DAG && "Missing context");
10423     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10424     EVT ResVT = Use->getValueType(0);
10425     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10426     const TargetRegisterClass *ArgRC =
10427         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10428     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10429       return false;
10430 
10431     // At this point, we know that we perform a cross-register-bank copy.
10432     // Check if it is expensive.
10433     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10434     // Assume bitcasts are cheap, unless both register classes do not
10435     // explicitly share a common sub class.
10436     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10437       return false;
10438 
10439     // Check if it will be merged with the load.
10440     // 1. Check the alignment constraint.
10441     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10442         ResVT.getTypeForEVT(*DAG->getContext()));
10443 
10444     if (RequiredAlignment > getAlignment())
10445       return false;
10446 
10447     // 2. Check that the load is a legal operation for that type.
10448     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10449       return false;
10450 
10451     // 3. Check that we do not have a zext in the way.
10452     if (Inst->getValueType(0) != getLoadedType())
10453       return false;
10454 
10455     return true;
10456   }
10457 };
10458 }
10459 
10460 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10461 /// \p UsedBits looks like 0..0 1..1 0..0.
10462 static bool areUsedBitsDense(const APInt &UsedBits) {
10463   // If all the bits are one, this is dense!
10464   if (UsedBits.isAllOnesValue())
10465     return true;
10466 
10467   // Get rid of the unused bits on the right.
10468   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10469   // Get rid of the unused bits on the left.
10470   if (NarrowedUsedBits.countLeadingZeros())
10471     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10472   // Check that the chunk of bits is completely used.
10473   return NarrowedUsedBits.isAllOnesValue();
10474 }
10475 
10476 /// \brief Check whether or not \p First and \p Second are next to each other
10477 /// in memory. This means that there is no hole between the bits loaded
10478 /// by \p First and the bits loaded by \p Second.
10479 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10480                                      const LoadedSlice &Second) {
10481   assert(First.Origin == Second.Origin && First.Origin &&
10482          "Unable to match different memory origins.");
10483   APInt UsedBits = First.getUsedBits();
10484   assert((UsedBits & Second.getUsedBits()) == 0 &&
10485          "Slices are not supposed to overlap.");
10486   UsedBits |= Second.getUsedBits();
10487   return areUsedBitsDense(UsedBits);
10488 }
10489 
10490 /// \brief Adjust the \p GlobalLSCost according to the target
10491 /// paring capabilities and the layout of the slices.
10492 /// \pre \p GlobalLSCost should account for at least as many loads as
10493 /// there is in the slices in \p LoadedSlices.
10494 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10495                                  LoadedSlice::Cost &GlobalLSCost) {
10496   unsigned NumberOfSlices = LoadedSlices.size();
10497   // If there is less than 2 elements, no pairing is possible.
10498   if (NumberOfSlices < 2)
10499     return;
10500 
10501   // Sort the slices so that elements that are likely to be next to each
10502   // other in memory are next to each other in the list.
10503   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10504             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10505     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10506     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10507   });
10508   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10509   // First (resp. Second) is the first (resp. Second) potentially candidate
10510   // to be placed in a paired load.
10511   const LoadedSlice *First = nullptr;
10512   const LoadedSlice *Second = nullptr;
10513   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10514                 // Set the beginning of the pair.
10515                                                            First = Second) {
10516 
10517     Second = &LoadedSlices[CurrSlice];
10518 
10519     // If First is NULL, it means we start a new pair.
10520     // Get to the next slice.
10521     if (!First)
10522       continue;
10523 
10524     EVT LoadedType = First->getLoadedType();
10525 
10526     // If the types of the slices are different, we cannot pair them.
10527     if (LoadedType != Second->getLoadedType())
10528       continue;
10529 
10530     // Check if the target supplies paired loads for this type.
10531     unsigned RequiredAlignment = 0;
10532     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10533       // move to the next pair, this type is hopeless.
10534       Second = nullptr;
10535       continue;
10536     }
10537     // Check if we meet the alignment requirement.
10538     if (RequiredAlignment > First->getAlignment())
10539       continue;
10540 
10541     // Check that both loads are next to each other in memory.
10542     if (!areSlicesNextToEachOther(*First, *Second))
10543       continue;
10544 
10545     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10546     --GlobalLSCost.Loads;
10547     // Move to the next pair.
10548     Second = nullptr;
10549   }
10550 }
10551 
10552 /// \brief Check the profitability of all involved LoadedSlice.
10553 /// Currently, it is considered profitable if there is exactly two
10554 /// involved slices (1) which are (2) next to each other in memory, and
10555 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10556 ///
10557 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10558 /// the elements themselves.
10559 ///
10560 /// FIXME: When the cost model will be mature enough, we can relax
10561 /// constraints (1) and (2).
10562 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10563                                 const APInt &UsedBits, bool ForCodeSize) {
10564   unsigned NumberOfSlices = LoadedSlices.size();
10565   if (StressLoadSlicing)
10566     return NumberOfSlices > 1;
10567 
10568   // Check (1).
10569   if (NumberOfSlices != 2)
10570     return false;
10571 
10572   // Check (2).
10573   if (!areUsedBitsDense(UsedBits))
10574     return false;
10575 
10576   // Check (3).
10577   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10578   // The original code has one big load.
10579   OrigCost.Loads = 1;
10580   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10581     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10582     // Accumulate the cost of all the slices.
10583     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10584     GlobalSlicingCost += SliceCost;
10585 
10586     // Account as cost in the original configuration the gain obtained
10587     // with the current slices.
10588     OrigCost.addSliceGain(LS);
10589   }
10590 
10591   // If the target supports paired load, adjust the cost accordingly.
10592   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10593   return OrigCost > GlobalSlicingCost;
10594 }
10595 
10596 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10597 /// operations, split it in the various pieces being extracted.
10598 ///
10599 /// This sort of thing is introduced by SROA.
10600 /// This slicing takes care not to insert overlapping loads.
10601 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10602 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10603   if (Level < AfterLegalizeDAG)
10604     return false;
10605 
10606   LoadSDNode *LD = cast<LoadSDNode>(N);
10607   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10608       !LD->getValueType(0).isInteger())
10609     return false;
10610 
10611   // Keep track of already used bits to detect overlapping values.
10612   // In that case, we will just abort the transformation.
10613   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10614 
10615   SmallVector<LoadedSlice, 4> LoadedSlices;
10616 
10617   // Check if this load is used as several smaller chunks of bits.
10618   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10619   // of computation for each trunc.
10620   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10621        UI != UIEnd; ++UI) {
10622     // Skip the uses of the chain.
10623     if (UI.getUse().getResNo() != 0)
10624       continue;
10625 
10626     SDNode *User = *UI;
10627     unsigned Shift = 0;
10628 
10629     // Check if this is a trunc(lshr).
10630     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10631         isa<ConstantSDNode>(User->getOperand(1))) {
10632       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10633       User = *User->use_begin();
10634     }
10635 
10636     // At this point, User is a Truncate, iff we encountered, trunc or
10637     // trunc(lshr).
10638     if (User->getOpcode() != ISD::TRUNCATE)
10639       return false;
10640 
10641     // The width of the type must be a power of 2 and greater than 8-bits.
10642     // Otherwise the load cannot be represented in LLVM IR.
10643     // Moreover, if we shifted with a non-8-bits multiple, the slice
10644     // will be across several bytes. We do not support that.
10645     unsigned Width = User->getValueSizeInBits(0);
10646     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10647       return 0;
10648 
10649     // Build the slice for this chain of computations.
10650     LoadedSlice LS(User, LD, Shift, &DAG);
10651     APInt CurrentUsedBits = LS.getUsedBits();
10652 
10653     // Check if this slice overlaps with another.
10654     if ((CurrentUsedBits & UsedBits) != 0)
10655       return false;
10656     // Update the bits used globally.
10657     UsedBits |= CurrentUsedBits;
10658 
10659     // Check if the new slice would be legal.
10660     if (!LS.isLegal())
10661       return false;
10662 
10663     // Record the slice.
10664     LoadedSlices.push_back(LS);
10665   }
10666 
10667   // Abort slicing if it does not seem to be profitable.
10668   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10669     return false;
10670 
10671   ++SlicedLoads;
10672 
10673   // Rewrite each chain to use an independent load.
10674   // By construction, each chain can be represented by a unique load.
10675 
10676   // Prepare the argument for the new token factor for all the slices.
10677   SmallVector<SDValue, 8> ArgChains;
10678   for (SmallVectorImpl<LoadedSlice>::const_iterator
10679            LSIt = LoadedSlices.begin(),
10680            LSItEnd = LoadedSlices.end();
10681        LSIt != LSItEnd; ++LSIt) {
10682     SDValue SliceInst = LSIt->loadSlice();
10683     CombineTo(LSIt->Inst, SliceInst, true);
10684     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10685       SliceInst = SliceInst.getOperand(0);
10686     assert(SliceInst->getOpcode() == ISD::LOAD &&
10687            "It takes more than a zext to get to the loaded slice!!");
10688     ArgChains.push_back(SliceInst.getValue(1));
10689   }
10690 
10691   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10692                               ArgChains);
10693   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10694   return true;
10695 }
10696 
10697 /// Check to see if V is (and load (ptr), imm), where the load is having
10698 /// specific bytes cleared out.  If so, return the byte size being masked out
10699 /// and the shift amount.
10700 static std::pair<unsigned, unsigned>
10701 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10702   std::pair<unsigned, unsigned> Result(0, 0);
10703 
10704   // Check for the structure we're looking for.
10705   if (V->getOpcode() != ISD::AND ||
10706       !isa<ConstantSDNode>(V->getOperand(1)) ||
10707       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10708     return Result;
10709 
10710   // Check the chain and pointer.
10711   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10712   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10713 
10714   // The store should be chained directly to the load or be an operand of a
10715   // tokenfactor.
10716   if (LD == Chain.getNode())
10717     ; // ok.
10718   else if (Chain->getOpcode() != ISD::TokenFactor)
10719     return Result; // Fail.
10720   else {
10721     bool isOk = false;
10722     for (const SDValue &ChainOp : Chain->op_values())
10723       if (ChainOp.getNode() == LD) {
10724         isOk = true;
10725         break;
10726       }
10727     if (!isOk) return Result;
10728   }
10729 
10730   // This only handles simple types.
10731   if (V.getValueType() != MVT::i16 &&
10732       V.getValueType() != MVT::i32 &&
10733       V.getValueType() != MVT::i64)
10734     return Result;
10735 
10736   // Check the constant mask.  Invert it so that the bits being masked out are
10737   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10738   // follow the sign bit for uniformity.
10739   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10740   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10741   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10742   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10743   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10744   if (NotMaskLZ == 64) return Result;  // All zero mask.
10745 
10746   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10747   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10748     return Result;
10749 
10750   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10751   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10752     NotMaskLZ -= 64-V.getValueSizeInBits();
10753 
10754   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10755   switch (MaskedBytes) {
10756   case 1:
10757   case 2:
10758   case 4: break;
10759   default: return Result; // All one mask, or 5-byte mask.
10760   }
10761 
10762   // Verify that the first bit starts at a multiple of mask so that the access
10763   // is aligned the same as the access width.
10764   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10765 
10766   Result.first = MaskedBytes;
10767   Result.second = NotMaskTZ/8;
10768   return Result;
10769 }
10770 
10771 
10772 /// Check to see if IVal is something that provides a value as specified by
10773 /// MaskInfo. If so, replace the specified store with a narrower store of
10774 /// truncated IVal.
10775 static SDNode *
10776 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10777                                 SDValue IVal, StoreSDNode *St,
10778                                 DAGCombiner *DC) {
10779   unsigned NumBytes = MaskInfo.first;
10780   unsigned ByteShift = MaskInfo.second;
10781   SelectionDAG &DAG = DC->getDAG();
10782 
10783   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10784   // that uses this.  If not, this is not a replacement.
10785   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10786                                   ByteShift*8, (ByteShift+NumBytes)*8);
10787   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10788 
10789   // Check that it is legal on the target to do this.  It is legal if the new
10790   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10791   // legalization.
10792   MVT VT = MVT::getIntegerVT(NumBytes*8);
10793   if (!DC->isTypeLegal(VT))
10794     return nullptr;
10795 
10796   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10797   // shifted by ByteShift and truncated down to NumBytes.
10798   if (ByteShift) {
10799     SDLoc DL(IVal);
10800     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10801                        DAG.getConstant(ByteShift*8, DL,
10802                                     DC->getShiftAmountTy(IVal.getValueType())));
10803   }
10804 
10805   // Figure out the offset for the store and the alignment of the access.
10806   unsigned StOffset;
10807   unsigned NewAlign = St->getAlignment();
10808 
10809   if (DAG.getDataLayout().isLittleEndian())
10810     StOffset = ByteShift;
10811   else
10812     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10813 
10814   SDValue Ptr = St->getBasePtr();
10815   if (StOffset) {
10816     SDLoc DL(IVal);
10817     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10818                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10819     NewAlign = MinAlign(NewAlign, StOffset);
10820   }
10821 
10822   // Truncate down to the new size.
10823   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10824 
10825   ++OpsNarrowed;
10826   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10827                       St->getPointerInfo().getWithOffset(StOffset),
10828                       false, false, NewAlign).getNode();
10829 }
10830 
10831 
10832 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10833 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10834 /// narrowing the load and store if it would end up being a win for performance
10835 /// or code size.
10836 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10837   StoreSDNode *ST  = cast<StoreSDNode>(N);
10838   if (ST->isVolatile())
10839     return SDValue();
10840 
10841   SDValue Chain = ST->getChain();
10842   SDValue Value = ST->getValue();
10843   SDValue Ptr   = ST->getBasePtr();
10844   EVT VT = Value.getValueType();
10845 
10846   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10847     return SDValue();
10848 
10849   unsigned Opc = Value.getOpcode();
10850 
10851   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10852   // is a byte mask indicating a consecutive number of bytes, check to see if
10853   // Y is known to provide just those bytes.  If so, we try to replace the
10854   // load + replace + store sequence with a single (narrower) store, which makes
10855   // the load dead.
10856   if (Opc == ISD::OR) {
10857     std::pair<unsigned, unsigned> MaskedLoad;
10858     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10859     if (MaskedLoad.first)
10860       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10861                                                   Value.getOperand(1), ST,this))
10862         return SDValue(NewST, 0);
10863 
10864     // Or is commutative, so try swapping X and Y.
10865     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10866     if (MaskedLoad.first)
10867       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10868                                                   Value.getOperand(0), ST,this))
10869         return SDValue(NewST, 0);
10870   }
10871 
10872   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10873       Value.getOperand(1).getOpcode() != ISD::Constant)
10874     return SDValue();
10875 
10876   SDValue N0 = Value.getOperand(0);
10877   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10878       Chain == SDValue(N0.getNode(), 1)) {
10879     LoadSDNode *LD = cast<LoadSDNode>(N0);
10880     if (LD->getBasePtr() != Ptr ||
10881         LD->getPointerInfo().getAddrSpace() !=
10882         ST->getPointerInfo().getAddrSpace())
10883       return SDValue();
10884 
10885     // Find the type to narrow it the load / op / store to.
10886     SDValue N1 = Value.getOperand(1);
10887     unsigned BitWidth = N1.getValueSizeInBits();
10888     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10889     if (Opc == ISD::AND)
10890       Imm ^= APInt::getAllOnesValue(BitWidth);
10891     if (Imm == 0 || Imm.isAllOnesValue())
10892       return SDValue();
10893     unsigned ShAmt = Imm.countTrailingZeros();
10894     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10895     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10896     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10897     // The narrowing should be profitable, the load/store operation should be
10898     // legal (or custom) and the store size should be equal to the NewVT width.
10899     while (NewBW < BitWidth &&
10900            (NewVT.getStoreSizeInBits() != NewBW ||
10901             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10902             !TLI.isNarrowingProfitable(VT, NewVT))) {
10903       NewBW = NextPowerOf2(NewBW);
10904       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10905     }
10906     if (NewBW >= BitWidth)
10907       return SDValue();
10908 
10909     // If the lsb changed does not start at the type bitwidth boundary,
10910     // start at the previous one.
10911     if (ShAmt % NewBW)
10912       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10913     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10914                                    std::min(BitWidth, ShAmt + NewBW));
10915     if ((Imm & Mask) == Imm) {
10916       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10917       if (Opc == ISD::AND)
10918         NewImm ^= APInt::getAllOnesValue(NewBW);
10919       uint64_t PtrOff = ShAmt / 8;
10920       // For big endian targets, we need to adjust the offset to the pointer to
10921       // load the correct bytes.
10922       if (DAG.getDataLayout().isBigEndian())
10923         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10924 
10925       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10926       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10927       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10928         return SDValue();
10929 
10930       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10931                                    Ptr.getValueType(), Ptr,
10932                                    DAG.getConstant(PtrOff, SDLoc(LD),
10933                                                    Ptr.getValueType()));
10934       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10935                                   LD->getChain(), NewPtr,
10936                                   LD->getPointerInfo().getWithOffset(PtrOff),
10937                                   LD->isVolatile(), LD->isNonTemporal(),
10938                                   LD->isInvariant(), NewAlign,
10939                                   LD->getAAInfo());
10940       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10941                                    DAG.getConstant(NewImm, SDLoc(Value),
10942                                                    NewVT));
10943       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10944                                    NewVal, NewPtr,
10945                                    ST->getPointerInfo().getWithOffset(PtrOff),
10946                                    false, false, NewAlign);
10947 
10948       AddToWorklist(NewPtr.getNode());
10949       AddToWorklist(NewLD.getNode());
10950       AddToWorklist(NewVal.getNode());
10951       WorklistRemover DeadNodes(*this);
10952       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10953       ++OpsNarrowed;
10954       return NewST;
10955     }
10956   }
10957 
10958   return SDValue();
10959 }
10960 
10961 /// For a given floating point load / store pair, if the load value isn't used
10962 /// by any other operations, then consider transforming the pair to integer
10963 /// load / store operations if the target deems the transformation profitable.
10964 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10965   StoreSDNode *ST  = cast<StoreSDNode>(N);
10966   SDValue Chain = ST->getChain();
10967   SDValue Value = ST->getValue();
10968   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10969       Value.hasOneUse() &&
10970       Chain == SDValue(Value.getNode(), 1)) {
10971     LoadSDNode *LD = cast<LoadSDNode>(Value);
10972     EVT VT = LD->getMemoryVT();
10973     if (!VT.isFloatingPoint() ||
10974         VT != ST->getMemoryVT() ||
10975         LD->isNonTemporal() ||
10976         ST->isNonTemporal() ||
10977         LD->getPointerInfo().getAddrSpace() != 0 ||
10978         ST->getPointerInfo().getAddrSpace() != 0)
10979       return SDValue();
10980 
10981     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10982     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10983         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10984         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10985         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10986       return SDValue();
10987 
10988     unsigned LDAlign = LD->getAlignment();
10989     unsigned STAlign = ST->getAlignment();
10990     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10991     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10992     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10993       return SDValue();
10994 
10995     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10996                                 LD->getChain(), LD->getBasePtr(),
10997                                 LD->getPointerInfo(),
10998                                 false, false, false, LDAlign);
10999 
11000     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
11001                                  NewLD, ST->getBasePtr(),
11002                                  ST->getPointerInfo(),
11003                                  false, false, STAlign);
11004 
11005     AddToWorklist(NewLD.getNode());
11006     AddToWorklist(NewST.getNode());
11007     WorklistRemover DeadNodes(*this);
11008     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11009     ++LdStFP2Int;
11010     return NewST;
11011   }
11012 
11013   return SDValue();
11014 }
11015 
11016 namespace {
11017 /// Helper struct to parse and store a memory address as base + index + offset.
11018 /// We ignore sign extensions when it is safe to do so.
11019 /// The following two expressions are not equivalent. To differentiate we need
11020 /// to store whether there was a sign extension involved in the index
11021 /// computation.
11022 ///  (load (i64 add (i64 copyfromreg %c)
11023 ///                 (i64 signextend (add (i8 load %index)
11024 ///                                      (i8 1))))
11025 /// vs
11026 ///
11027 /// (load (i64 add (i64 copyfromreg %c)
11028 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11029 ///                                         (i32 1)))))
11030 struct BaseIndexOffset {
11031   SDValue Base;
11032   SDValue Index;
11033   int64_t Offset;
11034   bool IsIndexSignExt;
11035 
11036   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11037 
11038   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11039                   bool IsIndexSignExt) :
11040     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11041 
11042   bool equalBaseIndex(const BaseIndexOffset &Other) {
11043     return Other.Base == Base && Other.Index == Index &&
11044       Other.IsIndexSignExt == IsIndexSignExt;
11045   }
11046 
11047   /// Parses tree in Ptr for base, index, offset addresses.
11048   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11049     bool IsIndexSignExt = false;
11050 
11051     // Split up a folded GlobalAddress+Offset into its component parts.
11052     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11053       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11054         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11055                                                     SDLoc(GA),
11056                                                     GA->getValueType(0),
11057                                                     /*Offset=*/0,
11058                                                     /*isTargetGA=*/false,
11059                                                     GA->getTargetFlags()),
11060                                SDValue(),
11061                                GA->getOffset(),
11062                                IsIndexSignExt);
11063       }
11064 
11065     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11066     // instruction, then it could be just the BASE or everything else we don't
11067     // know how to handle. Just use Ptr as BASE and give up.
11068     if (Ptr->getOpcode() != ISD::ADD)
11069       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11070 
11071     // We know that we have at least an ADD instruction. Try to pattern match
11072     // the simple case of BASE + OFFSET.
11073     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11074       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11075       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11076                               IsIndexSignExt);
11077     }
11078 
11079     // Inside a loop the current BASE pointer is calculated using an ADD and a
11080     // MUL instruction. In this case Ptr is the actual BASE pointer.
11081     // (i64 add (i64 %array_ptr)
11082     //          (i64 mul (i64 %induction_var)
11083     //                   (i64 %element_size)))
11084     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11085       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11086 
11087     // Look at Base + Index + Offset cases.
11088     SDValue Base = Ptr->getOperand(0);
11089     SDValue IndexOffset = Ptr->getOperand(1);
11090 
11091     // Skip signextends.
11092     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11093       IndexOffset = IndexOffset->getOperand(0);
11094       IsIndexSignExt = true;
11095     }
11096 
11097     // Either the case of Base + Index (no offset) or something else.
11098     if (IndexOffset->getOpcode() != ISD::ADD)
11099       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11100 
11101     // Now we have the case of Base + Index + offset.
11102     SDValue Index = IndexOffset->getOperand(0);
11103     SDValue Offset = IndexOffset->getOperand(1);
11104 
11105     if (!isa<ConstantSDNode>(Offset))
11106       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11107 
11108     // Ignore signextends.
11109     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11110       Index = Index->getOperand(0);
11111       IsIndexSignExt = true;
11112     } else IsIndexSignExt = false;
11113 
11114     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11115     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11116   }
11117 };
11118 } // namespace
11119 
11120 // This is a helper function for visitMUL to check the profitability
11121 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11122 // MulNode is the original multiply, AddNode is (add x, c1),
11123 // and ConstNode is c2.
11124 //
11125 // If the (add x, c1) has multiple uses, we could increase
11126 // the number of adds if we make this transformation.
11127 // It would only be worth doing this if we can remove a
11128 // multiply in the process. Check for that here.
11129 // To illustrate:
11130 //     (A + c1) * c3
11131 //     (A + c2) * c3
11132 // We're checking for cases where we have common "c3 * A" expressions.
11133 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11134                                               SDValue &AddNode,
11135                                               SDValue &ConstNode) {
11136   APInt Val;
11137 
11138   // If the add only has one use, this would be OK to do.
11139   if (AddNode.getNode()->hasOneUse())
11140     return true;
11141 
11142   // Walk all the users of the constant with which we're multiplying.
11143   for (SDNode *Use : ConstNode->uses()) {
11144 
11145     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11146       continue;
11147 
11148     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11149       SDNode *OtherOp;
11150       SDNode *MulVar = AddNode.getOperand(0).getNode();
11151 
11152       // OtherOp is what we're multiplying against the constant.
11153       if (Use->getOperand(0) == ConstNode)
11154         OtherOp = Use->getOperand(1).getNode();
11155       else
11156         OtherOp = Use->getOperand(0).getNode();
11157 
11158       // Check to see if multiply is with the same operand of our "add".
11159       //
11160       //     ConstNode  = CONST
11161       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11162       //     ...
11163       //     AddNode  = (A + c1)  <-- MulVar is A.
11164       //         = AddNode * ConstNode   <-- current visiting instruction.
11165       //
11166       // If we make this transformation, we will have a common
11167       // multiply (ConstNode * A) that we can save.
11168       if (OtherOp == MulVar)
11169         return true;
11170 
11171       // Now check to see if a future expansion will give us a common
11172       // multiply.
11173       //
11174       //     ConstNode  = CONST
11175       //     AddNode    = (A + c1)
11176       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11177       //     ...
11178       //     OtherOp = (A + c2)
11179       //     Use     = OtherOp * ConstNode <-- visiting Use.
11180       //
11181       // If we make this transformation, we will have a common
11182       // multiply (CONST * A) after we also do the same transformation
11183       // to the "t2" instruction.
11184       if (OtherOp->getOpcode() == ISD::ADD &&
11185           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11186           OtherOp->getOperand(0).getNode() == MulVar)
11187         return true;
11188     }
11189   }
11190 
11191   // Didn't find a case where this would be profitable.
11192   return false;
11193 }
11194 
11195 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11196                                                   SDLoc SL,
11197                                                   ArrayRef<MemOpLink> Stores,
11198                                                   SmallVectorImpl<SDValue> &Chains,
11199                                                   EVT Ty) const {
11200   SmallVector<SDValue, 8> BuildVector;
11201 
11202   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11203     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11204     Chains.push_back(St->getChain());
11205     BuildVector.push_back(St->getValue());
11206   }
11207 
11208   return DAG.getBuildVector(Ty, SL, BuildVector);
11209 }
11210 
11211 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11212                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11213                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11214   // Make sure we have something to merge.
11215   if (NumStores < 2)
11216     return false;
11217 
11218   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11219   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11220   unsigned LatestNodeUsed = 0;
11221 
11222   for (unsigned i=0; i < NumStores; ++i) {
11223     // Find a chain for the new wide-store operand. Notice that some
11224     // of the store nodes that we found may not be selected for inclusion
11225     // in the wide store. The chain we use needs to be the chain of the
11226     // latest store node which is *used* and replaced by the wide store.
11227     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11228       LatestNodeUsed = i;
11229   }
11230 
11231   SmallVector<SDValue, 8> Chains;
11232 
11233   // The latest Node in the DAG.
11234   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11235   SDLoc DL(StoreNodes[0].MemNode);
11236 
11237   SDValue StoredVal;
11238   if (UseVector) {
11239     bool IsVec = MemVT.isVector();
11240     unsigned Elts = NumStores;
11241     if (IsVec) {
11242       // When merging vector stores, get the total number of elements.
11243       Elts *= MemVT.getVectorNumElements();
11244     }
11245     // Get the type for the merged vector store.
11246     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11247     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11248 
11249     if (IsConstantSrc) {
11250       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11251     } else {
11252       SmallVector<SDValue, 8> Ops;
11253       for (unsigned i = 0; i < NumStores; ++i) {
11254         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11255         SDValue Val = St->getValue();
11256         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11257         if (Val.getValueType() != MemVT)
11258           return false;
11259         Ops.push_back(Val);
11260         Chains.push_back(St->getChain());
11261       }
11262 
11263       // Build the extracted vector elements back into a vector.
11264       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11265                               DL, Ty, Ops);    }
11266   } else {
11267     // We should always use a vector store when merging extracted vector
11268     // elements, so this path implies a store of constants.
11269     assert(IsConstantSrc && "Merged vector elements should use vector store");
11270 
11271     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11272     APInt StoreInt(SizeInBits, 0);
11273 
11274     // Construct a single integer constant which is made of the smaller
11275     // constant inputs.
11276     bool IsLE = DAG.getDataLayout().isLittleEndian();
11277     for (unsigned i = 0; i < NumStores; ++i) {
11278       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11279       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11280       Chains.push_back(St->getChain());
11281 
11282       SDValue Val = St->getValue();
11283       StoreInt <<= ElementSizeBytes * 8;
11284       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11285         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11286       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11287         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11288       } else {
11289         llvm_unreachable("Invalid constant element type");
11290       }
11291     }
11292 
11293     // Create the new Load and Store operations.
11294     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11295     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11296   }
11297 
11298   assert(!Chains.empty());
11299 
11300   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11301   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11302                                   FirstInChain->getBasePtr(),
11303                                   FirstInChain->getPointerInfo(),
11304                                   false, false,
11305                                   FirstInChain->getAlignment());
11306 
11307   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11308                                                   : DAG.getSubtarget().useAA();
11309   if (UseAA) {
11310     // Replace all merged stores with the new store.
11311     for (unsigned i = 0; i < NumStores; ++i)
11312       CombineTo(StoreNodes[i].MemNode, NewStore);
11313   } else {
11314     // Replace the last store with the new store.
11315     CombineTo(LatestOp, NewStore);
11316     // Erase all other stores.
11317     for (unsigned i = 0; i < NumStores; ++i) {
11318       if (StoreNodes[i].MemNode == LatestOp)
11319         continue;
11320       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11321       // ReplaceAllUsesWith will replace all uses that existed when it was
11322       // called, but graph optimizations may cause new ones to appear. For
11323       // example, the case in pr14333 looks like
11324       //
11325       //  St's chain -> St -> another store -> X
11326       //
11327       // And the only difference from St to the other store is the chain.
11328       // When we change it's chain to be St's chain they become identical,
11329       // get CSEed and the net result is that X is now a use of St.
11330       // Since we know that St is redundant, just iterate.
11331       while (!St->use_empty())
11332         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11333       deleteAndRecombine(St);
11334     }
11335   }
11336 
11337   return true;
11338 }
11339 
11340 void DAGCombiner::getStoreMergeAndAliasCandidates(
11341     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11342     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11343   // This holds the base pointer, index, and the offset in bytes from the base
11344   // pointer.
11345   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11346 
11347   // We must have a base and an offset.
11348   if (!BasePtr.Base.getNode())
11349     return;
11350 
11351   // Do not handle stores to undef base pointers.
11352   if (BasePtr.Base.isUndef())
11353     return;
11354 
11355   // Walk up the chain and look for nodes with offsets from the same
11356   // base pointer. Stop when reaching an instruction with a different kind
11357   // or instruction which has a different base pointer.
11358   EVT MemVT = St->getMemoryVT();
11359   unsigned Seq = 0;
11360   StoreSDNode *Index = St;
11361 
11362 
11363   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11364                                                   : DAG.getSubtarget().useAA();
11365 
11366   if (UseAA) {
11367     // Look at other users of the same chain. Stores on the same chain do not
11368     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11369     // to be on the same chain, so don't bother looking at adjacent chains.
11370 
11371     SDValue Chain = St->getChain();
11372     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11373       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11374         if (I.getOperandNo() != 0)
11375           continue;
11376 
11377         if (OtherST->isVolatile() || OtherST->isIndexed())
11378           continue;
11379 
11380         if (OtherST->getMemoryVT() != MemVT)
11381           continue;
11382 
11383         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11384 
11385         if (Ptr.equalBaseIndex(BasePtr))
11386           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11387       }
11388     }
11389 
11390     return;
11391   }
11392 
11393   while (Index) {
11394     // If the chain has more than one use, then we can't reorder the mem ops.
11395     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11396       break;
11397 
11398     // Find the base pointer and offset for this memory node.
11399     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11400 
11401     // Check that the base pointer is the same as the original one.
11402     if (!Ptr.equalBaseIndex(BasePtr))
11403       break;
11404 
11405     // The memory operands must not be volatile.
11406     if (Index->isVolatile() || Index->isIndexed())
11407       break;
11408 
11409     // No truncation.
11410     if (Index->isTruncatingStore())
11411       break;
11412 
11413     // The stored memory type must be the same.
11414     if (Index->getMemoryVT() != MemVT)
11415       break;
11416 
11417     // We do not allow under-aligned stores in order to prevent
11418     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11419     // be irrelevant here; what MATTERS is that we not move memory
11420     // operations that potentially overlap past each-other.
11421     if (Index->getAlignment() < MemVT.getStoreSize())
11422       break;
11423 
11424     // We found a potential memory operand to merge.
11425     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11426 
11427     // Find the next memory operand in the chain. If the next operand in the
11428     // chain is a store then move up and continue the scan with the next
11429     // memory operand. If the next operand is a load save it and use alias
11430     // information to check if it interferes with anything.
11431     SDNode *NextInChain = Index->getChain().getNode();
11432     while (1) {
11433       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11434         // We found a store node. Use it for the next iteration.
11435         Index = STn;
11436         break;
11437       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11438         if (Ldn->isVolatile()) {
11439           Index = nullptr;
11440           break;
11441         }
11442 
11443         // Save the load node for later. Continue the scan.
11444         AliasLoadNodes.push_back(Ldn);
11445         NextInChain = Ldn->getChain().getNode();
11446         continue;
11447       } else {
11448         Index = nullptr;
11449         break;
11450       }
11451     }
11452   }
11453 }
11454 
11455 // We need to check that merging these stores does not cause a loop
11456 // in the DAG. Any store candidate may depend on another candidate
11457 // indirectly through its operand (we already consider dependencies
11458 // through the chain). Check in parallel by searching up from
11459 // non-chain operands of candidates.
11460 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11461     SmallVectorImpl<MemOpLink> &StoreNodes) {
11462   SmallPtrSet<const SDNode *, 16> Visited;
11463   SmallVector<const SDNode *, 8> Worklist;
11464   // search ops of store candidates
11465   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11466     SDNode *n = StoreNodes[i].MemNode;
11467     // Potential loops may happen only through non-chain operands
11468     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11469       Worklist.push_back(n->getOperand(j).getNode());
11470   }
11471   // search through DAG. We can stop early if we find a storenode
11472   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11473     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11474       return false;
11475   }
11476   return true;
11477 }
11478 
11479 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11480   if (OptLevel == CodeGenOpt::None)
11481     return false;
11482 
11483   EVT MemVT = St->getMemoryVT();
11484   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11485   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11486       Attribute::NoImplicitFloat);
11487 
11488   // This function cannot currently deal with non-byte-sized memory sizes.
11489   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11490     return false;
11491 
11492   if (!MemVT.isSimple())
11493     return false;
11494 
11495   // Perform an early exit check. Do not bother looking at stored values that
11496   // are not constants, loads, or extracted vector elements.
11497   SDValue StoredVal = St->getValue();
11498   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11499   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11500                        isa<ConstantFPSDNode>(StoredVal);
11501   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11502                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11503 
11504   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11505     return false;
11506 
11507   // Don't merge vectors into wider vectors if the source data comes from loads.
11508   // TODO: This restriction can be lifted by using logic similar to the
11509   // ExtractVecSrc case.
11510   if (MemVT.isVector() && IsLoadSrc)
11511     return false;
11512 
11513   // Only look at ends of store sequences.
11514   SDValue Chain = SDValue(St, 0);
11515   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11516     return false;
11517 
11518   // Save the LoadSDNodes that we find in the chain.
11519   // We need to make sure that these nodes do not interfere with
11520   // any of the store nodes.
11521   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11522 
11523   // Save the StoreSDNodes that we find in the chain.
11524   SmallVector<MemOpLink, 8> StoreNodes;
11525 
11526   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11527 
11528   // Check if there is anything to merge.
11529   if (StoreNodes.size() < 2)
11530     return false;
11531 
11532   // only do dep endence check in AA case
11533   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11534                                                   : DAG.getSubtarget().useAA();
11535   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11536     return false;
11537 
11538   // Sort the memory operands according to their distance from the
11539   // base pointer.  As a secondary criteria: make sure stores coming
11540   // later in the code come first in the list. This is important for
11541   // the non-UseAA case, because we're merging stores into the FINAL
11542   // store along a chain which potentially contains aliasing stores.
11543   // Thus, if there are multiple stores to the same address, the last
11544   // one can be considered for merging but not the others.
11545   std::sort(StoreNodes.begin(), StoreNodes.end(),
11546             [](MemOpLink LHS, MemOpLink RHS) {
11547     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11548            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11549             LHS.SequenceNum < RHS.SequenceNum);
11550   });
11551 
11552   // Scan the memory operations on the chain and find the first non-consecutive
11553   // store memory address.
11554   unsigned LastConsecutiveStore = 0;
11555   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11556   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11557 
11558     // Check that the addresses are consecutive starting from the second
11559     // element in the list of stores.
11560     if (i > 0) {
11561       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11562       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11563         break;
11564     }
11565 
11566     // Check if this store interferes with any of the loads that we found.
11567     // If we find a load that alias with this store. Stop the sequence.
11568     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11569                     [&](LSBaseSDNode* Ldn) {
11570                       return isAlias(Ldn, StoreNodes[i].MemNode);
11571                     }))
11572       break;
11573 
11574     // Mark this node as useful.
11575     LastConsecutiveStore = i;
11576   }
11577 
11578   // The node with the lowest store address.
11579   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11580   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11581   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11582   LLVMContext &Context = *DAG.getContext();
11583   const DataLayout &DL = DAG.getDataLayout();
11584 
11585   // Store the constants into memory as one consecutive store.
11586   if (IsConstantSrc) {
11587     unsigned LastLegalType = 0;
11588     unsigned LastLegalVectorType = 0;
11589     bool NonZero = false;
11590     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11591       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11592       SDValue StoredVal = St->getValue();
11593 
11594       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11595         NonZero |= !C->isNullValue();
11596       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11597         NonZero |= !C->getConstantFPValue()->isNullValue();
11598       } else {
11599         // Non-constant.
11600         break;
11601       }
11602 
11603       // Find a legal type for the constant store.
11604       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11605       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11606       bool IsFast;
11607       if (TLI.isTypeLegal(StoreTy) &&
11608           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11609                                  FirstStoreAlign, &IsFast) && IsFast) {
11610         LastLegalType = i+1;
11611       // Or check whether a truncstore is legal.
11612       } else if (TLI.getTypeAction(Context, StoreTy) ==
11613                  TargetLowering::TypePromoteInteger) {
11614         EVT LegalizedStoredValueTy =
11615           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11616         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11617             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11618                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11619             IsFast) {
11620           LastLegalType = i + 1;
11621         }
11622       }
11623 
11624       // We only use vectors if the constant is known to be zero or the target
11625       // allows it and the function is not marked with the noimplicitfloat
11626       // attribute.
11627       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11628                                                         FirstStoreAS)) &&
11629           !NoVectors) {
11630         // Find a legal type for the vector store.
11631         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11632         if (TLI.isTypeLegal(Ty) &&
11633             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11634                                    FirstStoreAlign, &IsFast) && IsFast)
11635           LastLegalVectorType = i + 1;
11636       }
11637     }
11638 
11639     // Check if we found a legal integer type to store.
11640     if (LastLegalType == 0 && LastLegalVectorType == 0)
11641       return false;
11642 
11643     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11644     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11645 
11646     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11647                                            true, UseVector);
11648   }
11649 
11650   // When extracting multiple vector elements, try to store them
11651   // in one vector store rather than a sequence of scalar stores.
11652   if (IsExtractVecSrc) {
11653     unsigned NumStoresToMerge = 0;
11654     bool IsVec = MemVT.isVector();
11655     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11656       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11657       unsigned StoreValOpcode = St->getValue().getOpcode();
11658       // This restriction could be loosened.
11659       // Bail out if any stored values are not elements extracted from a vector.
11660       // It should be possible to handle mixed sources, but load sources need
11661       // more careful handling (see the block of code below that handles
11662       // consecutive loads).
11663       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11664           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11665         return false;
11666 
11667       // Find a legal type for the vector store.
11668       unsigned Elts = i + 1;
11669       if (IsVec) {
11670         // When merging vector stores, get the total number of elements.
11671         Elts *= MemVT.getVectorNumElements();
11672       }
11673       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11674       bool IsFast;
11675       if (TLI.isTypeLegal(Ty) &&
11676           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11677                                  FirstStoreAlign, &IsFast) && IsFast)
11678         NumStoresToMerge = i + 1;
11679     }
11680 
11681     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11682                                            false, true);
11683   }
11684 
11685   // Below we handle the case of multiple consecutive stores that
11686   // come from multiple consecutive loads. We merge them into a single
11687   // wide load and a single wide store.
11688 
11689   // Look for load nodes which are used by the stored values.
11690   SmallVector<MemOpLink, 8> LoadNodes;
11691 
11692   // Find acceptable loads. Loads need to have the same chain (token factor),
11693   // must not be zext, volatile, indexed, and they must be consecutive.
11694   BaseIndexOffset LdBasePtr;
11695   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11696     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11697     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11698     if (!Ld) break;
11699 
11700     // Loads must only have one use.
11701     if (!Ld->hasNUsesOfValue(1, 0))
11702       break;
11703 
11704     // The memory operands must not be volatile.
11705     if (Ld->isVolatile() || Ld->isIndexed())
11706       break;
11707 
11708     // We do not accept ext loads.
11709     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11710       break;
11711 
11712     // The stored memory type must be the same.
11713     if (Ld->getMemoryVT() != MemVT)
11714       break;
11715 
11716     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11717     // If this is not the first ptr that we check.
11718     if (LdBasePtr.Base.getNode()) {
11719       // The base ptr must be the same.
11720       if (!LdPtr.equalBaseIndex(LdBasePtr))
11721         break;
11722     } else {
11723       // Check that all other base pointers are the same as this one.
11724       LdBasePtr = LdPtr;
11725     }
11726 
11727     // We found a potential memory operand to merge.
11728     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11729   }
11730 
11731   if (LoadNodes.size() < 2)
11732     return false;
11733 
11734   // If we have load/store pair instructions and we only have two values,
11735   // don't bother.
11736   unsigned RequiredAlignment;
11737   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11738       St->getAlignment() >= RequiredAlignment)
11739     return false;
11740 
11741   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11742   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11743   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11744 
11745   // Scan the memory operations on the chain and find the first non-consecutive
11746   // load memory address. These variables hold the index in the store node
11747   // array.
11748   unsigned LastConsecutiveLoad = 0;
11749   // This variable refers to the size and not index in the array.
11750   unsigned LastLegalVectorType = 0;
11751   unsigned LastLegalIntegerType = 0;
11752   StartAddress = LoadNodes[0].OffsetFromBase;
11753   SDValue FirstChain = FirstLoad->getChain();
11754   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11755     // All loads must share the same chain.
11756     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11757       break;
11758 
11759     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11760     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11761       break;
11762     LastConsecutiveLoad = i;
11763     // Find a legal type for the vector store.
11764     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11765     bool IsFastSt, IsFastLd;
11766     if (TLI.isTypeLegal(StoreTy) &&
11767         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11768                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11769         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11770                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11771       LastLegalVectorType = i + 1;
11772     }
11773 
11774     // Find a legal type for the integer store.
11775     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11776     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11777     if (TLI.isTypeLegal(StoreTy) &&
11778         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11779                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11780         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11781                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11782       LastLegalIntegerType = i + 1;
11783     // Or check whether a truncstore and extload is legal.
11784     else if (TLI.getTypeAction(Context, StoreTy) ==
11785              TargetLowering::TypePromoteInteger) {
11786       EVT LegalizedStoredValueTy =
11787         TLI.getTypeToTransformTo(Context, StoreTy);
11788       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11789           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11790           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11791           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11792           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11793                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11794           IsFastSt &&
11795           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11796                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11797           IsFastLd)
11798         LastLegalIntegerType = i+1;
11799     }
11800   }
11801 
11802   // Only use vector types if the vector type is larger than the integer type.
11803   // If they are the same, use integers.
11804   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11805   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11806 
11807   // We add +1 here because the LastXXX variables refer to location while
11808   // the NumElem refers to array/index size.
11809   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11810   NumElem = std::min(LastLegalType, NumElem);
11811 
11812   if (NumElem < 2)
11813     return false;
11814 
11815   // Collect the chains from all merged stores.
11816   SmallVector<SDValue, 8> MergeStoreChains;
11817   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11818 
11819   // The latest Node in the DAG.
11820   unsigned LatestNodeUsed = 0;
11821   for (unsigned i=1; i<NumElem; ++i) {
11822     // Find a chain for the new wide-store operand. Notice that some
11823     // of the store nodes that we found may not be selected for inclusion
11824     // in the wide store. The chain we use needs to be the chain of the
11825     // latest store node which is *used* and replaced by the wide store.
11826     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11827       LatestNodeUsed = i;
11828 
11829     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11830   }
11831 
11832   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11833 
11834   // Find if it is better to use vectors or integers to load and store
11835   // to memory.
11836   EVT JointMemOpVT;
11837   if (UseVectorTy) {
11838     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11839   } else {
11840     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11841     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11842   }
11843 
11844   SDLoc LoadDL(LoadNodes[0].MemNode);
11845   SDLoc StoreDL(StoreNodes[0].MemNode);
11846 
11847   // The merged loads are required to have the same incoming chain, so
11848   // using the first's chain is acceptable.
11849   SDValue NewLoad = DAG.getLoad(
11850       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11851       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11852 
11853   SDValue NewStoreChain =
11854     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11855 
11856   SDValue NewStore = DAG.getStore(
11857     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11858       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11859 
11860   // Transfer chain users from old loads to the new load.
11861   for (unsigned i = 0; i < NumElem; ++i) {
11862     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11863     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11864                                   SDValue(NewLoad.getNode(), 1));
11865   }
11866 
11867   if (UseAA) {
11868     // Replace the all stores with the new store.
11869     for (unsigned i = 0; i < NumElem; ++i)
11870       CombineTo(StoreNodes[i].MemNode, NewStore);
11871   } else {
11872     // Replace the last store with the new store.
11873     CombineTo(LatestOp, NewStore);
11874     // Erase all other stores.
11875     for (unsigned i = 0; i < NumElem; ++i) {
11876       // Remove all Store nodes.
11877       if (StoreNodes[i].MemNode == LatestOp)
11878         continue;
11879       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11880       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11881       deleteAndRecombine(St);
11882     }
11883   }
11884 
11885   return true;
11886 }
11887 
11888 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11889   SDLoc SL(ST);
11890   SDValue ReplStore;
11891 
11892   // Replace the chain to avoid dependency.
11893   if (ST->isTruncatingStore()) {
11894     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11895                                   ST->getBasePtr(), ST->getMemoryVT(),
11896                                   ST->getMemOperand());
11897   } else {
11898     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11899                              ST->getMemOperand());
11900   }
11901 
11902   // Create token to keep both nodes around.
11903   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11904                               MVT::Other, ST->getChain(), ReplStore);
11905 
11906   // Make sure the new and old chains are cleaned up.
11907   AddToWorklist(Token.getNode());
11908 
11909   // Don't add users to work list.
11910   return CombineTo(ST, Token, false);
11911 }
11912 
11913 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11914   SDValue Value = ST->getValue();
11915   if (Value.getOpcode() == ISD::TargetConstantFP)
11916     return SDValue();
11917 
11918   SDLoc DL(ST);
11919 
11920   SDValue Chain = ST->getChain();
11921   SDValue Ptr = ST->getBasePtr();
11922 
11923   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11924 
11925   // NOTE: If the original store is volatile, this transform must not increase
11926   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11927   // processor operation but an i64 (which is not legal) requires two.  So the
11928   // transform should not be done in this case.
11929 
11930   SDValue Tmp;
11931   switch (CFP->getSimpleValueType(0).SimpleTy) {
11932   default:
11933     llvm_unreachable("Unknown FP type");
11934   case MVT::f16:    // We don't do this for these yet.
11935   case MVT::f80:
11936   case MVT::f128:
11937   case MVT::ppcf128:
11938     return SDValue();
11939   case MVT::f32:
11940     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11941         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11942       ;
11943       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11944                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11945                             MVT::i32);
11946       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11947     }
11948 
11949     return SDValue();
11950   case MVT::f64:
11951     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11952          !ST->isVolatile()) ||
11953         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11954       ;
11955       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11956                             getZExtValue(), SDLoc(CFP), MVT::i64);
11957       return DAG.getStore(Chain, DL, Tmp,
11958                           Ptr, ST->getMemOperand());
11959     }
11960 
11961     if (!ST->isVolatile() &&
11962         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11963       // Many FP stores are not made apparent until after legalize, e.g. for
11964       // argument passing.  Since this is so common, custom legalize the
11965       // 64-bit integer store into two 32-bit stores.
11966       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11967       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11968       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11969       if (DAG.getDataLayout().isBigEndian())
11970         std::swap(Lo, Hi);
11971 
11972       unsigned Alignment = ST->getAlignment();
11973       bool isVolatile = ST->isVolatile();
11974       bool isNonTemporal = ST->isNonTemporal();
11975       AAMDNodes AAInfo = ST->getAAInfo();
11976 
11977       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11978                                  Ptr, ST->getPointerInfo(),
11979                                  isVolatile, isNonTemporal,
11980                                  ST->getAlignment(), AAInfo);
11981       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11982                         DAG.getConstant(4, DL, Ptr.getValueType()));
11983       Alignment = MinAlign(Alignment, 4U);
11984       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11985                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11986                                  isVolatile, isNonTemporal,
11987                                  Alignment, AAInfo);
11988       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11989                          St0, St1);
11990     }
11991 
11992     return SDValue();
11993   }
11994 }
11995 
11996 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11997   StoreSDNode *ST  = cast<StoreSDNode>(N);
11998   SDValue Chain = ST->getChain();
11999   SDValue Value = ST->getValue();
12000   SDValue Ptr   = ST->getBasePtr();
12001 
12002   // If this is a store of a bit convert, store the input value if the
12003   // resultant store does not need a higher alignment than the original.
12004   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12005       ST->isUnindexed()) {
12006     EVT SVT = Value.getOperand(0).getValueType();
12007     if (((!LegalOperations && !ST->isVolatile()) ||
12008          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12009         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12010       unsigned OrigAlign = ST->getAlignment();
12011       bool Fast = false;
12012       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12013                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12014           Fast) {
12015         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
12016                             Ptr, ST->getPointerInfo(), ST->isVolatile(),
12017                             ST->isNonTemporal(), OrigAlign,
12018                             ST->getAAInfo());
12019       }
12020     }
12021   }
12022 
12023   // Turn 'store undef, Ptr' -> nothing.
12024   if (Value.isUndef() && ST->isUnindexed())
12025     return Chain;
12026 
12027   // Try to infer better alignment information than the store already has.
12028   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12029     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12030       if (Align > ST->getAlignment()) {
12031         SDValue NewStore =
12032                DAG.getTruncStore(Chain, SDLoc(N), Value,
12033                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
12034                                  ST->isVolatile(), ST->isNonTemporal(), Align,
12035                                  ST->getAAInfo());
12036         if (NewStore.getNode() != N)
12037           return CombineTo(ST, NewStore, true);
12038       }
12039     }
12040   }
12041 
12042   // Try transforming a pair floating point load / store ops to integer
12043   // load / store ops.
12044   if (SDValue NewST = TransformFPLoadStorePair(N))
12045     return NewST;
12046 
12047   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12048                                                   : DAG.getSubtarget().useAA();
12049 #ifndef NDEBUG
12050   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12051       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12052     UseAA = false;
12053 #endif
12054   if (UseAA && ST->isUnindexed()) {
12055     // FIXME: We should do this even without AA enabled. AA will just allow
12056     // FindBetterChain to work in more situations. The problem with this is that
12057     // any combine that expects memory operations to be on consecutive chains
12058     // first needs to be updated to look for users of the same chain.
12059 
12060     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12061     // adjacent stores.
12062     if (findBetterNeighborChains(ST)) {
12063       // replaceStoreChain uses CombineTo, which handled all of the worklist
12064       // manipulation. Return the original node to not do anything else.
12065       return SDValue(ST, 0);
12066     }
12067   }
12068 
12069   // Try transforming N to an indexed store.
12070   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12071     return SDValue(N, 0);
12072 
12073   // FIXME: is there such a thing as a truncating indexed store?
12074   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12075       Value.getValueType().isInteger()) {
12076     // See if we can simplify the input to this truncstore with knowledge that
12077     // only the low bits are being used.  For example:
12078     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12079     SDValue Shorter =
12080       GetDemandedBits(Value,
12081                       APInt::getLowBitsSet(
12082                         Value.getValueType().getScalarType().getSizeInBits(),
12083                         ST->getMemoryVT().getScalarType().getSizeInBits()));
12084     AddToWorklist(Value.getNode());
12085     if (Shorter.getNode())
12086       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12087                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12088 
12089     // Otherwise, see if we can simplify the operation with
12090     // SimplifyDemandedBits, which only works if the value has a single use.
12091     if (SimplifyDemandedBits(Value,
12092                         APInt::getLowBitsSet(
12093                           Value.getValueType().getScalarType().getSizeInBits(),
12094                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12095       return SDValue(N, 0);
12096   }
12097 
12098   // If this is a load followed by a store to the same location, then the store
12099   // is dead/noop.
12100   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12101     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12102         ST->isUnindexed() && !ST->isVolatile() &&
12103         // There can't be any side effects between the load and store, such as
12104         // a call or store.
12105         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12106       // The store is dead, remove it.
12107       return Chain;
12108     }
12109   }
12110 
12111   // If this is a store followed by a store with the same value to the same
12112   // location, then the store is dead/noop.
12113   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12114     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12115         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12116         ST1->isUnindexed() && !ST1->isVolatile()) {
12117       // The store is dead, remove it.
12118       return Chain;
12119     }
12120   }
12121 
12122   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12123   // truncating store.  We can do this even if this is already a truncstore.
12124   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12125       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12126       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12127                             ST->getMemoryVT())) {
12128     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12129                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12130   }
12131 
12132   // Only perform this optimization before the types are legal, because we
12133   // don't want to perform this optimization on every DAGCombine invocation.
12134   if (!LegalTypes) {
12135     bool EverChanged = false;
12136 
12137     do {
12138       // There can be multiple store sequences on the same chain.
12139       // Keep trying to merge store sequences until we are unable to do so
12140       // or until we merge the last store on the chain.
12141       bool Changed = MergeConsecutiveStores(ST);
12142       EverChanged |= Changed;
12143       if (!Changed) break;
12144     } while (ST->getOpcode() != ISD::DELETED_NODE);
12145 
12146     if (EverChanged)
12147       return SDValue(N, 0);
12148   }
12149 
12150   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12151   //
12152   // Make sure to do this only after attempting to merge stores in order to
12153   //  avoid changing the types of some subset of stores due to visit order,
12154   //  preventing their merging.
12155   if (isa<ConstantFPSDNode>(Value)) {
12156     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12157       return NewSt;
12158   }
12159 
12160   return ReduceLoadOpStoreWidth(N);
12161 }
12162 
12163 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12164   SDValue InVec = N->getOperand(0);
12165   SDValue InVal = N->getOperand(1);
12166   SDValue EltNo = N->getOperand(2);
12167   SDLoc dl(N);
12168 
12169   // If the inserted element is an UNDEF, just use the input vector.
12170   if (InVal.isUndef())
12171     return InVec;
12172 
12173   EVT VT = InVec.getValueType();
12174 
12175   // If we can't generate a legal BUILD_VECTOR, exit
12176   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12177     return SDValue();
12178 
12179   // Check that we know which element is being inserted
12180   if (!isa<ConstantSDNode>(EltNo))
12181     return SDValue();
12182   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12183 
12184   // Canonicalize insert_vector_elt dag nodes.
12185   // Example:
12186   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12187   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12188   //
12189   // Do this only if the child insert_vector node has one use; also
12190   // do this only if indices are both constants and Idx1 < Idx0.
12191   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12192       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12193     unsigned OtherElt =
12194       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12195     if (Elt < OtherElt) {
12196       // Swap nodes.
12197       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12198                                   InVec.getOperand(0), InVal, EltNo);
12199       AddToWorklist(NewOp.getNode());
12200       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12201                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12202     }
12203   }
12204 
12205   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12206   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12207   // vector elements.
12208   SmallVector<SDValue, 8> Ops;
12209   // Do not combine these two vectors if the output vector will not replace
12210   // the input vector.
12211   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12212     Ops.append(InVec.getNode()->op_begin(),
12213                InVec.getNode()->op_end());
12214   } else if (InVec.isUndef()) {
12215     unsigned NElts = VT.getVectorNumElements();
12216     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12217   } else {
12218     return SDValue();
12219   }
12220 
12221   // Insert the element
12222   if (Elt < Ops.size()) {
12223     // All the operands of BUILD_VECTOR must have the same type;
12224     // we enforce that here.
12225     EVT OpVT = Ops[0].getValueType();
12226     if (InVal.getValueType() != OpVT)
12227       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12228                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12229                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12230     Ops[Elt] = InVal;
12231   }
12232 
12233   // Return the new vector
12234   return DAG.getBuildVector(VT, dl, Ops);
12235 }
12236 
12237 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12238     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12239   EVT ResultVT = EVE->getValueType(0);
12240   EVT VecEltVT = InVecVT.getVectorElementType();
12241   unsigned Align = OriginalLoad->getAlignment();
12242   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12243       VecEltVT.getTypeForEVT(*DAG.getContext()));
12244 
12245   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12246     return SDValue();
12247 
12248   Align = NewAlign;
12249 
12250   SDValue NewPtr = OriginalLoad->getBasePtr();
12251   SDValue Offset;
12252   EVT PtrType = NewPtr.getValueType();
12253   MachinePointerInfo MPI;
12254   SDLoc DL(EVE);
12255   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12256     int Elt = ConstEltNo->getZExtValue();
12257     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12258     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12259     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12260   } else {
12261     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12262     Offset = DAG.getNode(
12263         ISD::MUL, DL, PtrType, Offset,
12264         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12265     MPI = OriginalLoad->getPointerInfo();
12266   }
12267   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12268 
12269   // The replacement we need to do here is a little tricky: we need to
12270   // replace an extractelement of a load with a load.
12271   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12272   // Note that this replacement assumes that the extractvalue is the only
12273   // use of the load; that's okay because we don't want to perform this
12274   // transformation in other cases anyway.
12275   SDValue Load;
12276   SDValue Chain;
12277   if (ResultVT.bitsGT(VecEltVT)) {
12278     // If the result type of vextract is wider than the load, then issue an
12279     // extending load instead.
12280     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12281                                                   VecEltVT)
12282                                    ? ISD::ZEXTLOAD
12283                                    : ISD::EXTLOAD;
12284     Load = DAG.getExtLoad(
12285         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12286         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12287         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12288     Chain = Load.getValue(1);
12289   } else {
12290     Load = DAG.getLoad(
12291         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12292         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12293         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12294     Chain = Load.getValue(1);
12295     if (ResultVT.bitsLT(VecEltVT))
12296       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12297     else
12298       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12299   }
12300   WorklistRemover DeadNodes(*this);
12301   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12302   SDValue To[] = { Load, Chain };
12303   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12304   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12305   // worklist explicitly as well.
12306   AddToWorklist(Load.getNode());
12307   AddUsersToWorklist(Load.getNode()); // Add users too
12308   // Make sure to revisit this node to clean it up; it will usually be dead.
12309   AddToWorklist(EVE);
12310   ++OpsNarrowed;
12311   return SDValue(EVE, 0);
12312 }
12313 
12314 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12315   // (vextract (scalar_to_vector val, 0) -> val
12316   SDValue InVec = N->getOperand(0);
12317   EVT VT = InVec.getValueType();
12318   EVT NVT = N->getValueType(0);
12319 
12320   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12321     // Check if the result type doesn't match the inserted element type. A
12322     // SCALAR_TO_VECTOR may truncate the inserted element and the
12323     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12324     SDValue InOp = InVec.getOperand(0);
12325     if (InOp.getValueType() != NVT) {
12326       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12327       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12328     }
12329     return InOp;
12330   }
12331 
12332   SDValue EltNo = N->getOperand(1);
12333   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12334 
12335   // extract_vector_elt (build_vector x, y), 1 -> y
12336   if (ConstEltNo &&
12337       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12338       TLI.isTypeLegal(VT) &&
12339       (InVec.hasOneUse() ||
12340        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12341     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12342     EVT InEltVT = Elt.getValueType();
12343 
12344     // Sometimes build_vector's scalar input types do not match result type.
12345     if (NVT == InEltVT)
12346       return Elt;
12347 
12348     // TODO: It may be useful to truncate if free if the build_vector implicitly
12349     // converts.
12350   }
12351 
12352   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12353   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12354       ConstEltNo->isNullValue() && VT.isInteger()) {
12355     SDValue BCSrc = InVec.getOperand(0);
12356     if (BCSrc.getValueType().isScalarInteger())
12357       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12358   }
12359 
12360   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12361   // We only perform this optimization before the op legalization phase because
12362   // we may introduce new vector instructions which are not backed by TD
12363   // patterns. For example on AVX, extracting elements from a wide vector
12364   // without using extract_subvector. However, if we can find an underlying
12365   // scalar value, then we can always use that.
12366   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12367     int NumElem = VT.getVectorNumElements();
12368     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12369     // Find the new index to extract from.
12370     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12371 
12372     // Extracting an undef index is undef.
12373     if (OrigElt == -1)
12374       return DAG.getUNDEF(NVT);
12375 
12376     // Select the right vector half to extract from.
12377     SDValue SVInVec;
12378     if (OrigElt < NumElem) {
12379       SVInVec = InVec->getOperand(0);
12380     } else {
12381       SVInVec = InVec->getOperand(1);
12382       OrigElt -= NumElem;
12383     }
12384 
12385     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12386       SDValue InOp = SVInVec.getOperand(OrigElt);
12387       if (InOp.getValueType() != NVT) {
12388         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12389         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12390       }
12391 
12392       return InOp;
12393     }
12394 
12395     // FIXME: We should handle recursing on other vector shuffles and
12396     // scalar_to_vector here as well.
12397 
12398     if (!LegalOperations) {
12399       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12400       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12401                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12402     }
12403   }
12404 
12405   bool BCNumEltsChanged = false;
12406   EVT ExtVT = VT.getVectorElementType();
12407   EVT LVT = ExtVT;
12408 
12409   // If the result of load has to be truncated, then it's not necessarily
12410   // profitable.
12411   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12412     return SDValue();
12413 
12414   if (InVec.getOpcode() == ISD::BITCAST) {
12415     // Don't duplicate a load with other uses.
12416     if (!InVec.hasOneUse())
12417       return SDValue();
12418 
12419     EVT BCVT = InVec.getOperand(0).getValueType();
12420     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12421       return SDValue();
12422     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12423       BCNumEltsChanged = true;
12424     InVec = InVec.getOperand(0);
12425     ExtVT = BCVT.getVectorElementType();
12426   }
12427 
12428   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12429   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12430       ISD::isNormalLoad(InVec.getNode()) &&
12431       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12432     SDValue Index = N->getOperand(1);
12433     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12434       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12435                                                            OrigLoad);
12436   }
12437 
12438   // Perform only after legalization to ensure build_vector / vector_shuffle
12439   // optimizations have already been done.
12440   if (!LegalOperations) return SDValue();
12441 
12442   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12443   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12444   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12445 
12446   if (ConstEltNo) {
12447     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12448 
12449     LoadSDNode *LN0 = nullptr;
12450     const ShuffleVectorSDNode *SVN = nullptr;
12451     if (ISD::isNormalLoad(InVec.getNode())) {
12452       LN0 = cast<LoadSDNode>(InVec);
12453     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12454                InVec.getOperand(0).getValueType() == ExtVT &&
12455                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12456       // Don't duplicate a load with other uses.
12457       if (!InVec.hasOneUse())
12458         return SDValue();
12459 
12460       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12461     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12462       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12463       // =>
12464       // (load $addr+1*size)
12465 
12466       // Don't duplicate a load with other uses.
12467       if (!InVec.hasOneUse())
12468         return SDValue();
12469 
12470       // If the bit convert changed the number of elements, it is unsafe
12471       // to examine the mask.
12472       if (BCNumEltsChanged)
12473         return SDValue();
12474 
12475       // Select the input vector, guarding against out of range extract vector.
12476       unsigned NumElems = VT.getVectorNumElements();
12477       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12478       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12479 
12480       if (InVec.getOpcode() == ISD::BITCAST) {
12481         // Don't duplicate a load with other uses.
12482         if (!InVec.hasOneUse())
12483           return SDValue();
12484 
12485         InVec = InVec.getOperand(0);
12486       }
12487       if (ISD::isNormalLoad(InVec.getNode())) {
12488         LN0 = cast<LoadSDNode>(InVec);
12489         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12490         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12491       }
12492     }
12493 
12494     // Make sure we found a non-volatile load and the extractelement is
12495     // the only use.
12496     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12497       return SDValue();
12498 
12499     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12500     if (Elt == -1)
12501       return DAG.getUNDEF(LVT);
12502 
12503     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12504   }
12505 
12506   return SDValue();
12507 }
12508 
12509 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12510 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12511   // We perform this optimization post type-legalization because
12512   // the type-legalizer often scalarizes integer-promoted vectors.
12513   // Performing this optimization before may create bit-casts which
12514   // will be type-legalized to complex code sequences.
12515   // We perform this optimization only before the operation legalizer because we
12516   // may introduce illegal operations.
12517   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12518     return SDValue();
12519 
12520   unsigned NumInScalars = N->getNumOperands();
12521   SDLoc dl(N);
12522   EVT VT = N->getValueType(0);
12523 
12524   // Check to see if this is a BUILD_VECTOR of a bunch of values
12525   // which come from any_extend or zero_extend nodes. If so, we can create
12526   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12527   // optimizations. We do not handle sign-extend because we can't fill the sign
12528   // using shuffles.
12529   EVT SourceType = MVT::Other;
12530   bool AllAnyExt = true;
12531 
12532   for (unsigned i = 0; i != NumInScalars; ++i) {
12533     SDValue In = N->getOperand(i);
12534     // Ignore undef inputs.
12535     if (In.isUndef()) continue;
12536 
12537     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12538     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12539 
12540     // Abort if the element is not an extension.
12541     if (!ZeroExt && !AnyExt) {
12542       SourceType = MVT::Other;
12543       break;
12544     }
12545 
12546     // The input is a ZeroExt or AnyExt. Check the original type.
12547     EVT InTy = In.getOperand(0).getValueType();
12548 
12549     // Check that all of the widened source types are the same.
12550     if (SourceType == MVT::Other)
12551       // First time.
12552       SourceType = InTy;
12553     else if (InTy != SourceType) {
12554       // Multiple income types. Abort.
12555       SourceType = MVT::Other;
12556       break;
12557     }
12558 
12559     // Check if all of the extends are ANY_EXTENDs.
12560     AllAnyExt &= AnyExt;
12561   }
12562 
12563   // In order to have valid types, all of the inputs must be extended from the
12564   // same source type and all of the inputs must be any or zero extend.
12565   // Scalar sizes must be a power of two.
12566   EVT OutScalarTy = VT.getScalarType();
12567   bool ValidTypes = SourceType != MVT::Other &&
12568                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12569                  isPowerOf2_32(SourceType.getSizeInBits());
12570 
12571   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12572   // turn into a single shuffle instruction.
12573   if (!ValidTypes)
12574     return SDValue();
12575 
12576   bool isLE = DAG.getDataLayout().isLittleEndian();
12577   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12578   assert(ElemRatio > 1 && "Invalid element size ratio");
12579   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12580                                DAG.getConstant(0, SDLoc(N), SourceType);
12581 
12582   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12583   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12584 
12585   // Populate the new build_vector
12586   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12587     SDValue Cast = N->getOperand(i);
12588     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12589             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12590             Cast.isUndef()) && "Invalid cast opcode");
12591     SDValue In;
12592     if (Cast.isUndef())
12593       In = DAG.getUNDEF(SourceType);
12594     else
12595       In = Cast->getOperand(0);
12596     unsigned Index = isLE ? (i * ElemRatio) :
12597                             (i * ElemRatio + (ElemRatio - 1));
12598 
12599     assert(Index < Ops.size() && "Invalid index");
12600     Ops[Index] = In;
12601   }
12602 
12603   // The type of the new BUILD_VECTOR node.
12604   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12605   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12606          "Invalid vector size");
12607   // Check if the new vector type is legal.
12608   if (!isTypeLegal(VecVT)) return SDValue();
12609 
12610   // Make the new BUILD_VECTOR.
12611   SDValue BV = DAG.getBuildVector(VecVT, dl, Ops);
12612 
12613   // The new BUILD_VECTOR node has the potential to be further optimized.
12614   AddToWorklist(BV.getNode());
12615   // Bitcast to the desired type.
12616   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12617 }
12618 
12619 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12620   EVT VT = N->getValueType(0);
12621 
12622   unsigned NumInScalars = N->getNumOperands();
12623   SDLoc dl(N);
12624 
12625   EVT SrcVT = MVT::Other;
12626   unsigned Opcode = ISD::DELETED_NODE;
12627   unsigned NumDefs = 0;
12628 
12629   for (unsigned i = 0; i != NumInScalars; ++i) {
12630     SDValue In = N->getOperand(i);
12631     unsigned Opc = In.getOpcode();
12632 
12633     if (Opc == ISD::UNDEF)
12634       continue;
12635 
12636     // If all scalar values are floats and converted from integers.
12637     if (Opcode == ISD::DELETED_NODE &&
12638         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12639       Opcode = Opc;
12640     }
12641 
12642     if (Opc != Opcode)
12643       return SDValue();
12644 
12645     EVT InVT = In.getOperand(0).getValueType();
12646 
12647     // If all scalar values are typed differently, bail out. It's chosen to
12648     // simplify BUILD_VECTOR of integer types.
12649     if (SrcVT == MVT::Other)
12650       SrcVT = InVT;
12651     if (SrcVT != InVT)
12652       return SDValue();
12653     NumDefs++;
12654   }
12655 
12656   // If the vector has just one element defined, it's not worth to fold it into
12657   // a vectorized one.
12658   if (NumDefs < 2)
12659     return SDValue();
12660 
12661   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12662          && "Should only handle conversion from integer to float.");
12663   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12664 
12665   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12666 
12667   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12668     return SDValue();
12669 
12670   // Just because the floating-point vector type is legal does not necessarily
12671   // mean that the corresponding integer vector type is.
12672   if (!isTypeLegal(NVT))
12673     return SDValue();
12674 
12675   SmallVector<SDValue, 8> Opnds;
12676   for (unsigned i = 0; i != NumInScalars; ++i) {
12677     SDValue In = N->getOperand(i);
12678 
12679     if (In.isUndef())
12680       Opnds.push_back(DAG.getUNDEF(SrcVT));
12681     else
12682       Opnds.push_back(In.getOperand(0));
12683   }
12684   SDValue BV = DAG.getBuildVector(NVT, dl, Opnds);
12685   AddToWorklist(BV.getNode());
12686 
12687   return DAG.getNode(Opcode, dl, VT, BV);
12688 }
12689 
12690 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12691   unsigned NumInScalars = N->getNumOperands();
12692   SDLoc dl(N);
12693   EVT VT = N->getValueType(0);
12694 
12695   // A vector built entirely of undefs is undef.
12696   if (ISD::allOperandsUndef(N))
12697     return DAG.getUNDEF(VT);
12698 
12699   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12700     return V;
12701 
12702   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12703     return V;
12704 
12705   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12706   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12707   // at most two distinct vectors, turn this into a shuffle node.
12708 
12709   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12710   if (!isTypeLegal(VT))
12711     return SDValue();
12712 
12713   // May only combine to shuffle after legalize if shuffle is legal.
12714   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12715     return SDValue();
12716 
12717   SDValue VecIn1, VecIn2;
12718   bool UsesZeroVector = false;
12719   for (unsigned i = 0; i != NumInScalars; ++i) {
12720     SDValue Op = N->getOperand(i);
12721     // Ignore undef inputs.
12722     if (Op.isUndef()) continue;
12723 
12724     // See if we can combine this build_vector into a blend with a zero vector.
12725     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12726       UsesZeroVector = true;
12727       continue;
12728     }
12729 
12730     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12731     // constant index, bail out.
12732     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12733         !isa<ConstantSDNode>(Op.getOperand(1))) {
12734       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12735       break;
12736     }
12737 
12738     // We allow up to two distinct input vectors.
12739     SDValue ExtractedFromVec = Op.getOperand(0);
12740     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12741       continue;
12742 
12743     if (!VecIn1.getNode()) {
12744       VecIn1 = ExtractedFromVec;
12745     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12746       VecIn2 = ExtractedFromVec;
12747     } else {
12748       // Too many inputs.
12749       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12750       break;
12751     }
12752   }
12753 
12754   // If everything is good, we can make a shuffle operation.
12755   if (VecIn1.getNode()) {
12756     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12757     SmallVector<int, 8> Mask;
12758     for (unsigned i = 0; i != NumInScalars; ++i) {
12759       unsigned Opcode = N->getOperand(i).getOpcode();
12760       if (Opcode == ISD::UNDEF) {
12761         Mask.push_back(-1);
12762         continue;
12763       }
12764 
12765       // Operands can also be zero.
12766       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12767         assert(UsesZeroVector &&
12768                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12769                "Unexpected node found!");
12770         Mask.push_back(NumInScalars+i);
12771         continue;
12772       }
12773 
12774       // If extracting from the first vector, just use the index directly.
12775       SDValue Extract = N->getOperand(i);
12776       SDValue ExtVal = Extract.getOperand(1);
12777       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12778       if (Extract.getOperand(0) == VecIn1) {
12779         Mask.push_back(ExtIndex);
12780         continue;
12781       }
12782 
12783       // Otherwise, use InIdx + InputVecSize
12784       Mask.push_back(InNumElements + ExtIndex);
12785     }
12786 
12787     // Avoid introducing illegal shuffles with zero.
12788     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12789       return SDValue();
12790 
12791     // We can't generate a shuffle node with mismatched input and output types.
12792     // Attempt to transform a single input vector to the correct type.
12793     if ((VT != VecIn1.getValueType())) {
12794       // If the input vector type has a different base type to the output
12795       // vector type, bail out.
12796       EVT VTElemType = VT.getVectorElementType();
12797       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12798           (VecIn2.getNode() &&
12799            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12800         return SDValue();
12801 
12802       // If the input vector is too small, widen it.
12803       // We only support widening of vectors which are half the size of the
12804       // output registers. For example XMM->YMM widening on X86 with AVX.
12805       EVT VecInT = VecIn1.getValueType();
12806       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12807         // If we only have one small input, widen it by adding undef values.
12808         if (!VecIn2.getNode())
12809           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12810                                DAG.getUNDEF(VecIn1.getValueType()));
12811         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12812           // If we have two small inputs of the same type, try to concat them.
12813           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12814           VecIn2 = SDValue(nullptr, 0);
12815         } else
12816           return SDValue();
12817       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12818         // If the input vector is too large, try to split it.
12819         // We don't support having two input vectors that are too large.
12820         // If the zero vector was used, we can not split the vector,
12821         // since we'd need 3 inputs.
12822         if (UsesZeroVector || VecIn2.getNode())
12823           return SDValue();
12824 
12825         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12826           return SDValue();
12827 
12828         // Try to replace VecIn1 with two extract_subvectors
12829         // No need to update the masks, they should still be correct.
12830         VecIn2 = DAG.getNode(
12831             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12832             DAG.getConstant(VT.getVectorNumElements(), dl,
12833                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12834         VecIn1 = DAG.getNode(
12835             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12836             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12837       } else
12838         return SDValue();
12839     }
12840 
12841     if (UsesZeroVector)
12842       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12843                                 DAG.getConstantFP(0.0, dl, VT);
12844     else
12845       // If VecIn2 is unused then change it to undef.
12846       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12847 
12848     // Check that we were able to transform all incoming values to the same
12849     // type.
12850     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12851         VecIn1.getValueType() != VT)
12852           return SDValue();
12853 
12854     // Return the new VECTOR_SHUFFLE node.
12855     SDValue Ops[2];
12856     Ops[0] = VecIn1;
12857     Ops[1] = VecIn2;
12858     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12859   }
12860 
12861   return SDValue();
12862 }
12863 
12864 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12866   EVT OpVT = N->getOperand(0).getValueType();
12867 
12868   // If the operands are legal vectors, leave them alone.
12869   if (TLI.isTypeLegal(OpVT))
12870     return SDValue();
12871 
12872   SDLoc DL(N);
12873   EVT VT = N->getValueType(0);
12874   SmallVector<SDValue, 8> Ops;
12875 
12876   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12877   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12878 
12879   // Keep track of what we encounter.
12880   bool AnyInteger = false;
12881   bool AnyFP = false;
12882   for (const SDValue &Op : N->ops()) {
12883     if (ISD::BITCAST == Op.getOpcode() &&
12884         !Op.getOperand(0).getValueType().isVector())
12885       Ops.push_back(Op.getOperand(0));
12886     else if (ISD::UNDEF == Op.getOpcode())
12887       Ops.push_back(ScalarUndef);
12888     else
12889       return SDValue();
12890 
12891     // Note whether we encounter an integer or floating point scalar.
12892     // If it's neither, bail out, it could be something weird like x86mmx.
12893     EVT LastOpVT = Ops.back().getValueType();
12894     if (LastOpVT.isFloatingPoint())
12895       AnyFP = true;
12896     else if (LastOpVT.isInteger())
12897       AnyInteger = true;
12898     else
12899       return SDValue();
12900   }
12901 
12902   // If any of the operands is a floating point scalar bitcast to a vector,
12903   // use floating point types throughout, and bitcast everything.
12904   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12905   if (AnyFP) {
12906     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12907     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12908     if (AnyInteger) {
12909       for (SDValue &Op : Ops) {
12910         if (Op.getValueType() == SVT)
12911           continue;
12912         if (Op.isUndef())
12913           Op = ScalarUndef;
12914         else
12915           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12916       }
12917     }
12918   }
12919 
12920   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12921                                VT.getSizeInBits() / SVT.getSizeInBits());
12922   return DAG.getNode(ISD::BITCAST, DL, VT,
12923                      DAG.getBuildVector(VecVT, DL, Ops));
12924 }
12925 
12926 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12927 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12928 // most two distinct vectors the same size as the result, attempt to turn this
12929 // into a legal shuffle.
12930 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12931   EVT VT = N->getValueType(0);
12932   EVT OpVT = N->getOperand(0).getValueType();
12933   int NumElts = VT.getVectorNumElements();
12934   int NumOpElts = OpVT.getVectorNumElements();
12935 
12936   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12937   SmallVector<int, 8> Mask;
12938 
12939   for (SDValue Op : N->ops()) {
12940     // Peek through any bitcast.
12941     while (Op.getOpcode() == ISD::BITCAST)
12942       Op = Op.getOperand(0);
12943 
12944     // UNDEF nodes convert to UNDEF shuffle mask values.
12945     if (Op.isUndef()) {
12946       Mask.append((unsigned)NumOpElts, -1);
12947       continue;
12948     }
12949 
12950     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12951       return SDValue();
12952 
12953     // What vector are we extracting the subvector from and at what index?
12954     SDValue ExtVec = Op.getOperand(0);
12955 
12956     // We want the EVT of the original extraction to correctly scale the
12957     // extraction index.
12958     EVT ExtVT = ExtVec.getValueType();
12959 
12960     // Peek through any bitcast.
12961     while (ExtVec.getOpcode() == ISD::BITCAST)
12962       ExtVec = ExtVec.getOperand(0);
12963 
12964     // UNDEF nodes convert to UNDEF shuffle mask values.
12965     if (ExtVec.isUndef()) {
12966       Mask.append((unsigned)NumOpElts, -1);
12967       continue;
12968     }
12969 
12970     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12971       return SDValue();
12972     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12973 
12974     // Ensure that we are extracting a subvector from a vector the same
12975     // size as the result.
12976     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12977       return SDValue();
12978 
12979     // Scale the subvector index to account for any bitcast.
12980     int NumExtElts = ExtVT.getVectorNumElements();
12981     if (0 == (NumExtElts % NumElts))
12982       ExtIdx /= (NumExtElts / NumElts);
12983     else if (0 == (NumElts % NumExtElts))
12984       ExtIdx *= (NumElts / NumExtElts);
12985     else
12986       return SDValue();
12987 
12988     // At most we can reference 2 inputs in the final shuffle.
12989     if (SV0.isUndef() || SV0 == ExtVec) {
12990       SV0 = ExtVec;
12991       for (int i = 0; i != NumOpElts; ++i)
12992         Mask.push_back(i + ExtIdx);
12993     } else if (SV1.isUndef() || SV1 == ExtVec) {
12994       SV1 = ExtVec;
12995       for (int i = 0; i != NumOpElts; ++i)
12996         Mask.push_back(i + ExtIdx + NumElts);
12997     } else {
12998       return SDValue();
12999     }
13000   }
13001 
13002   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13003     return SDValue();
13004 
13005   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13006                               DAG.getBitcast(VT, SV1), Mask);
13007 }
13008 
13009 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13010   // If we only have one input vector, we don't need to do any concatenation.
13011   if (N->getNumOperands() == 1)
13012     return N->getOperand(0);
13013 
13014   // Check if all of the operands are undefs.
13015   EVT VT = N->getValueType(0);
13016   if (ISD::allOperandsUndef(N))
13017     return DAG.getUNDEF(VT);
13018 
13019   // Optimize concat_vectors where all but the first of the vectors are undef.
13020   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13021         return Op.isUndef();
13022       })) {
13023     SDValue In = N->getOperand(0);
13024     assert(In.getValueType().isVector() && "Must concat vectors");
13025 
13026     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13027     if (In->getOpcode() == ISD::BITCAST &&
13028         !In->getOperand(0)->getValueType(0).isVector()) {
13029       SDValue Scalar = In->getOperand(0);
13030 
13031       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13032       // look through the trunc so we can still do the transform:
13033       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13034       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13035           !TLI.isTypeLegal(Scalar.getValueType()) &&
13036           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13037         Scalar = Scalar->getOperand(0);
13038 
13039       EVT SclTy = Scalar->getValueType(0);
13040 
13041       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13042         return SDValue();
13043 
13044       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13045                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13046       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13047         return SDValue();
13048 
13049       SDLoc dl = SDLoc(N);
13050       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
13051       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
13052     }
13053   }
13054 
13055   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13056   // We have already tested above for an UNDEF only concatenation.
13057   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13058   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13059   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13060     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13061   };
13062   bool AllBuildVectorsOrUndefs =
13063       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
13064   if (AllBuildVectorsOrUndefs) {
13065     SmallVector<SDValue, 8> Opnds;
13066     EVT SVT = VT.getScalarType();
13067 
13068     EVT MinVT = SVT;
13069     if (!SVT.isFloatingPoint()) {
13070       // If BUILD_VECTOR are from built from integer, they may have different
13071       // operand types. Get the smallest type and truncate all operands to it.
13072       bool FoundMinVT = false;
13073       for (const SDValue &Op : N->ops())
13074         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13075           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13076           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13077           FoundMinVT = true;
13078         }
13079       assert(FoundMinVT && "Concat vector type mismatch");
13080     }
13081 
13082     for (const SDValue &Op : N->ops()) {
13083       EVT OpVT = Op.getValueType();
13084       unsigned NumElts = OpVT.getVectorNumElements();
13085 
13086       if (ISD::UNDEF == Op.getOpcode())
13087         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13088 
13089       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13090         if (SVT.isFloatingPoint()) {
13091           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13092           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13093         } else {
13094           for (unsigned i = 0; i != NumElts; ++i)
13095             Opnds.push_back(
13096                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13097         }
13098       }
13099     }
13100 
13101     assert(VT.getVectorNumElements() == Opnds.size() &&
13102            "Concat vector type mismatch");
13103     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13104   }
13105 
13106   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13107   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13108     return V;
13109 
13110   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13111   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13112     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13113       return V;
13114 
13115   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13116   // nodes often generate nop CONCAT_VECTOR nodes.
13117   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13118   // place the incoming vectors at the exact same location.
13119   SDValue SingleSource = SDValue();
13120   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13121 
13122   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13123     SDValue Op = N->getOperand(i);
13124 
13125     if (Op.isUndef())
13126       continue;
13127 
13128     // Check if this is the identity extract:
13129     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13130       return SDValue();
13131 
13132     // Find the single incoming vector for the extract_subvector.
13133     if (SingleSource.getNode()) {
13134       if (Op.getOperand(0) != SingleSource)
13135         return SDValue();
13136     } else {
13137       SingleSource = Op.getOperand(0);
13138 
13139       // Check the source type is the same as the type of the result.
13140       // If not, this concat may extend the vector, so we can not
13141       // optimize it away.
13142       if (SingleSource.getValueType() != N->getValueType(0))
13143         return SDValue();
13144     }
13145 
13146     unsigned IdentityIndex = i * PartNumElem;
13147     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13148     // The extract index must be constant.
13149     if (!CS)
13150       return SDValue();
13151 
13152     // Check that we are reading from the identity index.
13153     if (CS->getZExtValue() != IdentityIndex)
13154       return SDValue();
13155   }
13156 
13157   if (SingleSource.getNode())
13158     return SingleSource;
13159 
13160   return SDValue();
13161 }
13162 
13163 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13164   EVT NVT = N->getValueType(0);
13165   SDValue V = N->getOperand(0);
13166 
13167   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13168     // Combine:
13169     //    (extract_subvec (concat V1, V2, ...), i)
13170     // Into:
13171     //    Vi if possible
13172     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13173     // type.
13174     if (V->getOperand(0).getValueType() != NVT)
13175       return SDValue();
13176     unsigned Idx = N->getConstantOperandVal(1);
13177     unsigned NumElems = NVT.getVectorNumElements();
13178     assert((Idx % NumElems) == 0 &&
13179            "IDX in concat is not a multiple of the result vector length.");
13180     return V->getOperand(Idx / NumElems);
13181   }
13182 
13183   // Skip bitcasting
13184   if (V->getOpcode() == ISD::BITCAST)
13185     V = V.getOperand(0);
13186 
13187   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13188     SDLoc dl(N);
13189     // Handle only simple case where vector being inserted and vector
13190     // being extracted are of same type, and are half size of larger vectors.
13191     EVT BigVT = V->getOperand(0).getValueType();
13192     EVT SmallVT = V->getOperand(1).getValueType();
13193     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13194       return SDValue();
13195 
13196     // Only handle cases where both indexes are constants with the same type.
13197     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13198     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13199 
13200     if (InsIdx && ExtIdx &&
13201         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13202         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13203       // Combine:
13204       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13205       // Into:
13206       //    indices are equal or bit offsets are equal => V1
13207       //    otherwise => (extract_subvec V1, ExtIdx)
13208       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13209           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13210         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13211       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13212                          DAG.getNode(ISD::BITCAST, dl,
13213                                      N->getOperand(0).getValueType(),
13214                                      V->getOperand(0)), N->getOperand(1));
13215     }
13216   }
13217 
13218   return SDValue();
13219 }
13220 
13221 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13222                                                  SDValue V, SelectionDAG &DAG) {
13223   SDLoc DL(V);
13224   EVT VT = V.getValueType();
13225 
13226   switch (V.getOpcode()) {
13227   default:
13228     return V;
13229 
13230   case ISD::CONCAT_VECTORS: {
13231     EVT OpVT = V->getOperand(0).getValueType();
13232     int OpSize = OpVT.getVectorNumElements();
13233     SmallBitVector OpUsedElements(OpSize, false);
13234     bool FoundSimplification = false;
13235     SmallVector<SDValue, 4> NewOps;
13236     NewOps.reserve(V->getNumOperands());
13237     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13238       SDValue Op = V->getOperand(i);
13239       bool OpUsed = false;
13240       for (int j = 0; j < OpSize; ++j)
13241         if (UsedElements[i * OpSize + j]) {
13242           OpUsedElements[j] = true;
13243           OpUsed = true;
13244         }
13245       NewOps.push_back(
13246           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13247                  : DAG.getUNDEF(OpVT));
13248       FoundSimplification |= Op == NewOps.back();
13249       OpUsedElements.reset();
13250     }
13251     if (FoundSimplification)
13252       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13253     return V;
13254   }
13255 
13256   case ISD::INSERT_SUBVECTOR: {
13257     SDValue BaseV = V->getOperand(0);
13258     SDValue SubV = V->getOperand(1);
13259     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13260     if (!IdxN)
13261       return V;
13262 
13263     int SubSize = SubV.getValueType().getVectorNumElements();
13264     int Idx = IdxN->getZExtValue();
13265     bool SubVectorUsed = false;
13266     SmallBitVector SubUsedElements(SubSize, false);
13267     for (int i = 0; i < SubSize; ++i)
13268       if (UsedElements[i + Idx]) {
13269         SubVectorUsed = true;
13270         SubUsedElements[i] = true;
13271         UsedElements[i + Idx] = false;
13272       }
13273 
13274     // Now recurse on both the base and sub vectors.
13275     SDValue SimplifiedSubV =
13276         SubVectorUsed
13277             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13278             : DAG.getUNDEF(SubV.getValueType());
13279     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13280     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13281       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13282                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13283     return V;
13284   }
13285   }
13286 }
13287 
13288 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13289                                        SDValue N1, SelectionDAG &DAG) {
13290   EVT VT = SVN->getValueType(0);
13291   int NumElts = VT.getVectorNumElements();
13292   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13293   for (int M : SVN->getMask())
13294     if (M >= 0 && M < NumElts)
13295       N0UsedElements[M] = true;
13296     else if (M >= NumElts)
13297       N1UsedElements[M - NumElts] = true;
13298 
13299   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13300   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13301   if (S0 == N0 && S1 == N1)
13302     return SDValue();
13303 
13304   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13305 }
13306 
13307 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13308 // or turn a shuffle of a single concat into simpler shuffle then concat.
13309 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13310   EVT VT = N->getValueType(0);
13311   unsigned NumElts = VT.getVectorNumElements();
13312 
13313   SDValue N0 = N->getOperand(0);
13314   SDValue N1 = N->getOperand(1);
13315   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13316 
13317   SmallVector<SDValue, 4> Ops;
13318   EVT ConcatVT = N0.getOperand(0).getValueType();
13319   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13320   unsigned NumConcats = NumElts / NumElemsPerConcat;
13321 
13322   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13323   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13324   // half vector elements.
13325   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13326       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13327                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13328     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13329                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13330     N1 = DAG.getUNDEF(ConcatVT);
13331     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13332   }
13333 
13334   // Look at every vector that's inserted. We're looking for exact
13335   // subvector-sized copies from a concatenated vector
13336   for (unsigned I = 0; I != NumConcats; ++I) {
13337     // Make sure we're dealing with a copy.
13338     unsigned Begin = I * NumElemsPerConcat;
13339     bool AllUndef = true, NoUndef = true;
13340     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13341       if (SVN->getMaskElt(J) >= 0)
13342         AllUndef = false;
13343       else
13344         NoUndef = false;
13345     }
13346 
13347     if (NoUndef) {
13348       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13349         return SDValue();
13350 
13351       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13352         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13353           return SDValue();
13354 
13355       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13356       if (FirstElt < N0.getNumOperands())
13357         Ops.push_back(N0.getOperand(FirstElt));
13358       else
13359         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13360 
13361     } else if (AllUndef) {
13362       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13363     } else { // Mixed with general masks and undefs, can't do optimization.
13364       return SDValue();
13365     }
13366   }
13367 
13368   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13369 }
13370 
13371 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13372   EVT VT = N->getValueType(0);
13373   unsigned NumElts = VT.getVectorNumElements();
13374 
13375   SDValue N0 = N->getOperand(0);
13376   SDValue N1 = N->getOperand(1);
13377 
13378   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13379 
13380   // Canonicalize shuffle undef, undef -> undef
13381   if (N0.isUndef() && N1.isUndef())
13382     return DAG.getUNDEF(VT);
13383 
13384   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13385 
13386   // Canonicalize shuffle v, v -> v, undef
13387   if (N0 == N1) {
13388     SmallVector<int, 8> NewMask;
13389     for (unsigned i = 0; i != NumElts; ++i) {
13390       int Idx = SVN->getMaskElt(i);
13391       if (Idx >= (int)NumElts) Idx -= NumElts;
13392       NewMask.push_back(Idx);
13393     }
13394     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13395                                 &NewMask[0]);
13396   }
13397 
13398   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13399   if (N0.isUndef()) {
13400     SmallVector<int, 8> NewMask;
13401     for (unsigned i = 0; i != NumElts; ++i) {
13402       int Idx = SVN->getMaskElt(i);
13403       if (Idx >= 0) {
13404         if (Idx >= (int)NumElts)
13405           Idx -= NumElts;
13406         else
13407           Idx = -1; // remove reference to lhs
13408       }
13409       NewMask.push_back(Idx);
13410     }
13411     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13412                                 &NewMask[0]);
13413   }
13414 
13415   // Remove references to rhs if it is undef
13416   if (N1.isUndef()) {
13417     bool Changed = false;
13418     SmallVector<int, 8> NewMask;
13419     for (unsigned i = 0; i != NumElts; ++i) {
13420       int Idx = SVN->getMaskElt(i);
13421       if (Idx >= (int)NumElts) {
13422         Idx = -1;
13423         Changed = true;
13424       }
13425       NewMask.push_back(Idx);
13426     }
13427     if (Changed)
13428       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13429   }
13430 
13431   // If it is a splat, check if the argument vector is another splat or a
13432   // build_vector.
13433   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13434     SDNode *V = N0.getNode();
13435 
13436     // If this is a bit convert that changes the element type of the vector but
13437     // not the number of vector elements, look through it.  Be careful not to
13438     // look though conversions that change things like v4f32 to v2f64.
13439     if (V->getOpcode() == ISD::BITCAST) {
13440       SDValue ConvInput = V->getOperand(0);
13441       if (ConvInput.getValueType().isVector() &&
13442           ConvInput.getValueType().getVectorNumElements() == NumElts)
13443         V = ConvInput.getNode();
13444     }
13445 
13446     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13447       assert(V->getNumOperands() == NumElts &&
13448              "BUILD_VECTOR has wrong number of operands");
13449       SDValue Base;
13450       bool AllSame = true;
13451       for (unsigned i = 0; i != NumElts; ++i) {
13452         if (!V->getOperand(i).isUndef()) {
13453           Base = V->getOperand(i);
13454           break;
13455         }
13456       }
13457       // Splat of <u, u, u, u>, return <u, u, u, u>
13458       if (!Base.getNode())
13459         return N0;
13460       for (unsigned i = 0; i != NumElts; ++i) {
13461         if (V->getOperand(i) != Base) {
13462           AllSame = false;
13463           break;
13464         }
13465       }
13466       // Splat of <x, x, x, x>, return <x, x, x, x>
13467       if (AllSame)
13468         return N0;
13469 
13470       // Canonicalize any other splat as a build_vector.
13471       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13472       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13473       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13474 
13475       // We may have jumped through bitcasts, so the type of the
13476       // BUILD_VECTOR may not match the type of the shuffle.
13477       if (V->getValueType(0) != VT)
13478         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13479       return NewBV;
13480     }
13481   }
13482 
13483   // There are various patterns used to build up a vector from smaller vectors,
13484   // subvectors, or elements. Scan chains of these and replace unused insertions
13485   // or components with undef.
13486   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13487     return S;
13488 
13489   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13490       Level < AfterLegalizeVectorOps &&
13491       (N1.isUndef() ||
13492       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13493        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13494     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13495       return V;
13496   }
13497 
13498   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13499   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13500   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13501     SmallVector<SDValue, 8> Ops;
13502     for (int M : SVN->getMask()) {
13503       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13504       if (M >= 0) {
13505         int Idx = M % NumElts;
13506         SDValue &S = (M < (int)NumElts ? N0 : N1);
13507         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13508           Op = S.getOperand(Idx);
13509         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13510           if (Idx == 0)
13511             Op = S.getOperand(0);
13512         } else {
13513           // Operand can't be combined - bail out.
13514           break;
13515         }
13516       }
13517       Ops.push_back(Op);
13518     }
13519     if (Ops.size() == VT.getVectorNumElements()) {
13520       // BUILD_VECTOR requires all inputs to be of the same type, find the
13521       // maximum type and extend them all.
13522       EVT SVT = VT.getScalarType();
13523       if (SVT.isInteger())
13524         for (SDValue &Op : Ops)
13525           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13526       if (SVT != VT.getScalarType())
13527         for (SDValue &Op : Ops)
13528           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13529                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13530                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13531       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13532     }
13533   }
13534 
13535   // If this shuffle only has a single input that is a bitcasted shuffle,
13536   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13537   // back to their original types.
13538   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13539       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13540       TLI.isTypeLegal(VT)) {
13541 
13542     // Peek through the bitcast only if there is one user.
13543     SDValue BC0 = N0;
13544     while (BC0.getOpcode() == ISD::BITCAST) {
13545       if (!BC0.hasOneUse())
13546         break;
13547       BC0 = BC0.getOperand(0);
13548     }
13549 
13550     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13551       if (Scale == 1)
13552         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13553 
13554       SmallVector<int, 8> NewMask;
13555       for (int M : Mask)
13556         for (int s = 0; s != Scale; ++s)
13557           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13558       return NewMask;
13559     };
13560 
13561     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13562       EVT SVT = VT.getScalarType();
13563       EVT InnerVT = BC0->getValueType(0);
13564       EVT InnerSVT = InnerVT.getScalarType();
13565 
13566       // Determine which shuffle works with the smaller scalar type.
13567       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13568       EVT ScaleSVT = ScaleVT.getScalarType();
13569 
13570       if (TLI.isTypeLegal(ScaleVT) &&
13571           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13572           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13573 
13574         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13575         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13576 
13577         // Scale the shuffle masks to the smaller scalar type.
13578         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13579         SmallVector<int, 8> InnerMask =
13580             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13581         SmallVector<int, 8> OuterMask =
13582             ScaleShuffleMask(SVN->getMask(), OuterScale);
13583 
13584         // Merge the shuffle masks.
13585         SmallVector<int, 8> NewMask;
13586         for (int M : OuterMask)
13587           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13588 
13589         // Test for shuffle mask legality over both commutations.
13590         SDValue SV0 = BC0->getOperand(0);
13591         SDValue SV1 = BC0->getOperand(1);
13592         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13593         if (!LegalMask) {
13594           std::swap(SV0, SV1);
13595           ShuffleVectorSDNode::commuteMask(NewMask);
13596           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13597         }
13598 
13599         if (LegalMask) {
13600           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13601           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13602           return DAG.getNode(
13603               ISD::BITCAST, SDLoc(N), VT,
13604               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13605         }
13606       }
13607     }
13608   }
13609 
13610   // Canonicalize shuffles according to rules:
13611   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13612   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13613   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13614   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13615       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13616       TLI.isTypeLegal(VT)) {
13617     // The incoming shuffle must be of the same type as the result of the
13618     // current shuffle.
13619     assert(N1->getOperand(0).getValueType() == VT &&
13620            "Shuffle types don't match");
13621 
13622     SDValue SV0 = N1->getOperand(0);
13623     SDValue SV1 = N1->getOperand(1);
13624     bool HasSameOp0 = N0 == SV0;
13625     bool IsSV1Undef = SV1.isUndef();
13626     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13627       // Commute the operands of this shuffle so that next rule
13628       // will trigger.
13629       return DAG.getCommutedVectorShuffle(*SVN);
13630   }
13631 
13632   // Try to fold according to rules:
13633   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13634   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13635   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13636   // Don't try to fold shuffles with illegal type.
13637   // Only fold if this shuffle is the only user of the other shuffle.
13638   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13639       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13640     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13641 
13642     // The incoming shuffle must be of the same type as the result of the
13643     // current shuffle.
13644     assert(OtherSV->getOperand(0).getValueType() == VT &&
13645            "Shuffle types don't match");
13646 
13647     SDValue SV0, SV1;
13648     SmallVector<int, 4> Mask;
13649     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13650     // operand, and SV1 as the second operand.
13651     for (unsigned i = 0; i != NumElts; ++i) {
13652       int Idx = SVN->getMaskElt(i);
13653       if (Idx < 0) {
13654         // Propagate Undef.
13655         Mask.push_back(Idx);
13656         continue;
13657       }
13658 
13659       SDValue CurrentVec;
13660       if (Idx < (int)NumElts) {
13661         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13662         // shuffle mask to identify which vector is actually referenced.
13663         Idx = OtherSV->getMaskElt(Idx);
13664         if (Idx < 0) {
13665           // Propagate Undef.
13666           Mask.push_back(Idx);
13667           continue;
13668         }
13669 
13670         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13671                                            : OtherSV->getOperand(1);
13672       } else {
13673         // This shuffle index references an element within N1.
13674         CurrentVec = N1;
13675       }
13676 
13677       // Simple case where 'CurrentVec' is UNDEF.
13678       if (CurrentVec.isUndef()) {
13679         Mask.push_back(-1);
13680         continue;
13681       }
13682 
13683       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13684       // will be the first or second operand of the combined shuffle.
13685       Idx = Idx % NumElts;
13686       if (!SV0.getNode() || SV0 == CurrentVec) {
13687         // Ok. CurrentVec is the left hand side.
13688         // Update the mask accordingly.
13689         SV0 = CurrentVec;
13690         Mask.push_back(Idx);
13691         continue;
13692       }
13693 
13694       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13695       if (SV1.getNode() && SV1 != CurrentVec)
13696         return SDValue();
13697 
13698       // Ok. CurrentVec is the right hand side.
13699       // Update the mask accordingly.
13700       SV1 = CurrentVec;
13701       Mask.push_back(Idx + NumElts);
13702     }
13703 
13704     // Check if all indices in Mask are Undef. In case, propagate Undef.
13705     bool isUndefMask = true;
13706     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13707       isUndefMask &= Mask[i] < 0;
13708 
13709     if (isUndefMask)
13710       return DAG.getUNDEF(VT);
13711 
13712     if (!SV0.getNode())
13713       SV0 = DAG.getUNDEF(VT);
13714     if (!SV1.getNode())
13715       SV1 = DAG.getUNDEF(VT);
13716 
13717     // Avoid introducing shuffles with illegal mask.
13718     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13719       ShuffleVectorSDNode::commuteMask(Mask);
13720 
13721       if (!TLI.isShuffleMaskLegal(Mask, VT))
13722         return SDValue();
13723 
13724       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13725       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13726       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13727       std::swap(SV0, SV1);
13728     }
13729 
13730     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13731     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13732     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13733     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13734   }
13735 
13736   return SDValue();
13737 }
13738 
13739 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13740   SDValue InVal = N->getOperand(0);
13741   EVT VT = N->getValueType(0);
13742 
13743   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13744   // with a VECTOR_SHUFFLE.
13745   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13746     SDValue InVec = InVal->getOperand(0);
13747     SDValue EltNo = InVal->getOperand(1);
13748 
13749     // FIXME: We could support implicit truncation if the shuffle can be
13750     // scaled to a smaller vector scalar type.
13751     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13752     if (C0 && VT == InVec.getValueType() &&
13753         VT.getScalarType() == InVal.getValueType()) {
13754       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13755       int Elt = C0->getZExtValue();
13756       NewMask[0] = Elt;
13757 
13758       if (TLI.isShuffleMaskLegal(NewMask, VT))
13759         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13760                                     NewMask);
13761     }
13762   }
13763 
13764   return SDValue();
13765 }
13766 
13767 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13768   SDValue N0 = N->getOperand(0);
13769   SDValue N2 = N->getOperand(2);
13770 
13771   // If the input vector is a concatenation, and the insert replaces
13772   // one of the halves, we can optimize into a single concat_vectors.
13773   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13774       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13775     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13776     EVT VT = N->getValueType(0);
13777 
13778     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13779     // (concat_vectors Z, Y)
13780     if (InsIdx == 0)
13781       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13782                          N->getOperand(1), N0.getOperand(1));
13783 
13784     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13785     // (concat_vectors X, Z)
13786     if (InsIdx == VT.getVectorNumElements()/2)
13787       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13788                          N0.getOperand(0), N->getOperand(1));
13789   }
13790 
13791   return SDValue();
13792 }
13793 
13794 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13795   SDValue N0 = N->getOperand(0);
13796 
13797   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13798   if (N0->getOpcode() == ISD::FP16_TO_FP)
13799     return N0->getOperand(0);
13800 
13801   return SDValue();
13802 }
13803 
13804 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13805   SDValue N0 = N->getOperand(0);
13806 
13807   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13808   if (N0->getOpcode() == ISD::AND) {
13809     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13810     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13811       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13812                          N0.getOperand(0));
13813     }
13814   }
13815 
13816   return SDValue();
13817 }
13818 
13819 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13820 /// with the destination vector and a zero vector.
13821 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13822 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13823 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13824   EVT VT = N->getValueType(0);
13825   SDValue LHS = N->getOperand(0);
13826   SDValue RHS = N->getOperand(1);
13827   SDLoc dl(N);
13828 
13829   // Make sure we're not running after operation legalization where it
13830   // may have custom lowered the vector shuffles.
13831   if (LegalOperations)
13832     return SDValue();
13833 
13834   if (N->getOpcode() != ISD::AND)
13835     return SDValue();
13836 
13837   if (RHS.getOpcode() == ISD::BITCAST)
13838     RHS = RHS.getOperand(0);
13839 
13840   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13841     return SDValue();
13842 
13843   EVT RVT = RHS.getValueType();
13844   unsigned NumElts = RHS.getNumOperands();
13845 
13846   // Attempt to create a valid clear mask, splitting the mask into
13847   // sub elements and checking to see if each is
13848   // all zeros or all ones - suitable for shuffle masking.
13849   auto BuildClearMask = [&](int Split) {
13850     int NumSubElts = NumElts * Split;
13851     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13852 
13853     SmallVector<int, 8> Indices;
13854     for (int i = 0; i != NumSubElts; ++i) {
13855       int EltIdx = i / Split;
13856       int SubIdx = i % Split;
13857       SDValue Elt = RHS.getOperand(EltIdx);
13858       if (Elt.isUndef()) {
13859         Indices.push_back(-1);
13860         continue;
13861       }
13862 
13863       APInt Bits;
13864       if (isa<ConstantSDNode>(Elt))
13865         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13866       else if (isa<ConstantFPSDNode>(Elt))
13867         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13868       else
13869         return SDValue();
13870 
13871       // Extract the sub element from the constant bit mask.
13872       if (DAG.getDataLayout().isBigEndian()) {
13873         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13874       } else {
13875         Bits = Bits.lshr(SubIdx * NumSubBits);
13876       }
13877 
13878       if (Split > 1)
13879         Bits = Bits.trunc(NumSubBits);
13880 
13881       if (Bits.isAllOnesValue())
13882         Indices.push_back(i);
13883       else if (Bits == 0)
13884         Indices.push_back(i + NumSubElts);
13885       else
13886         return SDValue();
13887     }
13888 
13889     // Let's see if the target supports this vector_shuffle.
13890     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13891     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13892     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13893       return SDValue();
13894 
13895     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13896     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13897                                                    DAG.getBitcast(ClearVT, LHS),
13898                                                    Zero, &Indices[0]));
13899   };
13900 
13901   // Determine maximum split level (byte level masking).
13902   int MaxSplit = 1;
13903   if (RVT.getScalarSizeInBits() % 8 == 0)
13904     MaxSplit = RVT.getScalarSizeInBits() / 8;
13905 
13906   for (int Split = 1; Split <= MaxSplit; ++Split)
13907     if (RVT.getScalarSizeInBits() % Split == 0)
13908       if (SDValue S = BuildClearMask(Split))
13909         return S;
13910 
13911   return SDValue();
13912 }
13913 
13914 /// Visit a binary vector operation, like ADD.
13915 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13916   assert(N->getValueType(0).isVector() &&
13917          "SimplifyVBinOp only works on vectors!");
13918 
13919   SDValue LHS = N->getOperand(0);
13920   SDValue RHS = N->getOperand(1);
13921   SDValue Ops[] = {LHS, RHS};
13922 
13923   // See if we can constant fold the vector operation.
13924   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13925           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13926     return Fold;
13927 
13928   // Try to convert a constant mask AND into a shuffle clear mask.
13929   if (SDValue Shuffle = XformToShuffleWithZero(N))
13930     return Shuffle;
13931 
13932   // Type legalization might introduce new shuffles in the DAG.
13933   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13934   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13935   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13936       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13937       LHS.getOperand(1).isUndef() &&
13938       RHS.getOperand(1).isUndef()) {
13939     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13940     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13941 
13942     if (SVN0->getMask().equals(SVN1->getMask())) {
13943       EVT VT = N->getValueType(0);
13944       SDValue UndefVector = LHS.getOperand(1);
13945       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13946                                      LHS.getOperand(0), RHS.getOperand(0),
13947                                      N->getFlags());
13948       AddUsersToWorklist(N);
13949       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13950                                   &SVN0->getMask()[0]);
13951     }
13952   }
13953 
13954   return SDValue();
13955 }
13956 
13957 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13958                                     SDValue N1, SDValue N2){
13959   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13960 
13961   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13962                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13963 
13964   // If we got a simplified select_cc node back from SimplifySelectCC, then
13965   // break it down into a new SETCC node, and a new SELECT node, and then return
13966   // the SELECT node, since we were called with a SELECT node.
13967   if (SCC.getNode()) {
13968     // Check to see if we got a select_cc back (to turn into setcc/select).
13969     // Otherwise, just return whatever node we got back, like fabs.
13970     if (SCC.getOpcode() == ISD::SELECT_CC) {
13971       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13972                                   N0.getValueType(),
13973                                   SCC.getOperand(0), SCC.getOperand(1),
13974                                   SCC.getOperand(4));
13975       AddToWorklist(SETCC.getNode());
13976       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13977                            SCC.getOperand(2), SCC.getOperand(3));
13978     }
13979 
13980     return SCC;
13981   }
13982   return SDValue();
13983 }
13984 
13985 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13986 /// being selected between, see if we can simplify the select.  Callers of this
13987 /// should assume that TheSelect is deleted if this returns true.  As such, they
13988 /// should return the appropriate thing (e.g. the node) back to the top-level of
13989 /// the DAG combiner loop to avoid it being looked at.
13990 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13991                                     SDValue RHS) {
13992 
13993   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
13994   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
13995   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13996     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13997       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13998       SDValue Sqrt = RHS;
13999       ISD::CondCode CC;
14000       SDValue CmpLHS;
14001       const ConstantFPSDNode *Zero = nullptr;
14002 
14003       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14004         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14005         CmpLHS = TheSelect->getOperand(0);
14006         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14007       } else {
14008         // SELECT or VSELECT
14009         SDValue Cmp = TheSelect->getOperand(0);
14010         if (Cmp.getOpcode() == ISD::SETCC) {
14011           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14012           CmpLHS = Cmp.getOperand(0);
14013           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14014         }
14015       }
14016       if (Zero && Zero->isZero() &&
14017           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14018           CC == ISD::SETULT || CC == ISD::SETLT)) {
14019         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14020         CombineTo(TheSelect, Sqrt);
14021         return true;
14022       }
14023     }
14024   }
14025   // Cannot simplify select with vector condition
14026   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14027 
14028   // If this is a select from two identical things, try to pull the operation
14029   // through the select.
14030   if (LHS.getOpcode() != RHS.getOpcode() ||
14031       !LHS.hasOneUse() || !RHS.hasOneUse())
14032     return false;
14033 
14034   // If this is a load and the token chain is identical, replace the select
14035   // of two loads with a load through a select of the address to load from.
14036   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14037   // constants have been dropped into the constant pool.
14038   if (LHS.getOpcode() == ISD::LOAD) {
14039     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14040     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14041 
14042     // Token chains must be identical.
14043     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14044         // Do not let this transformation reduce the number of volatile loads.
14045         LLD->isVolatile() || RLD->isVolatile() ||
14046         // FIXME: If either is a pre/post inc/dec load,
14047         // we'd need to split out the address adjustment.
14048         LLD->isIndexed() || RLD->isIndexed() ||
14049         // If this is an EXTLOAD, the VT's must match.
14050         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14051         // If this is an EXTLOAD, the kind of extension must match.
14052         (LLD->getExtensionType() != RLD->getExtensionType() &&
14053          // The only exception is if one of the extensions is anyext.
14054          LLD->getExtensionType() != ISD::EXTLOAD &&
14055          RLD->getExtensionType() != ISD::EXTLOAD) ||
14056         // FIXME: this discards src value information.  This is
14057         // over-conservative. It would be beneficial to be able to remember
14058         // both potential memory locations.  Since we are discarding
14059         // src value info, don't do the transformation if the memory
14060         // locations are not in the default address space.
14061         LLD->getPointerInfo().getAddrSpace() != 0 ||
14062         RLD->getPointerInfo().getAddrSpace() != 0 ||
14063         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14064                                       LLD->getBasePtr().getValueType()))
14065       return false;
14066 
14067     // Check that the select condition doesn't reach either load.  If so,
14068     // folding this will induce a cycle into the DAG.  If not, this is safe to
14069     // xform, so create a select of the addresses.
14070     SDValue Addr;
14071     if (TheSelect->getOpcode() == ISD::SELECT) {
14072       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14073       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14074           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14075         return false;
14076       // The loads must not depend on one another.
14077       if (LLD->isPredecessorOf(RLD) ||
14078           RLD->isPredecessorOf(LLD))
14079         return false;
14080       Addr = DAG.getSelect(SDLoc(TheSelect),
14081                            LLD->getBasePtr().getValueType(),
14082                            TheSelect->getOperand(0), LLD->getBasePtr(),
14083                            RLD->getBasePtr());
14084     } else {  // Otherwise SELECT_CC
14085       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14086       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14087 
14088       if ((LLD->hasAnyUseOfValue(1) &&
14089            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14090           (RLD->hasAnyUseOfValue(1) &&
14091            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14092         return false;
14093 
14094       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14095                          LLD->getBasePtr().getValueType(),
14096                          TheSelect->getOperand(0),
14097                          TheSelect->getOperand(1),
14098                          LLD->getBasePtr(), RLD->getBasePtr(),
14099                          TheSelect->getOperand(4));
14100     }
14101 
14102     SDValue Load;
14103     // It is safe to replace the two loads if they have different alignments,
14104     // but the new load must be the minimum (most restrictive) alignment of the
14105     // inputs.
14106     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
14107     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14108     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14109       Load = DAG.getLoad(TheSelect->getValueType(0),
14110                          SDLoc(TheSelect),
14111                          // FIXME: Discards pointer and AA info.
14112                          LLD->getChain(), Addr, MachinePointerInfo(),
14113                          LLD->isVolatile(), LLD->isNonTemporal(),
14114                          isInvariant, Alignment);
14115     } else {
14116       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14117                             RLD->getExtensionType() : LLD->getExtensionType(),
14118                             SDLoc(TheSelect),
14119                             TheSelect->getValueType(0),
14120                             // FIXME: Discards pointer and AA info.
14121                             LLD->getChain(), Addr, MachinePointerInfo(),
14122                             LLD->getMemoryVT(), LLD->isVolatile(),
14123                             LLD->isNonTemporal(), isInvariant, Alignment);
14124     }
14125 
14126     // Users of the select now use the result of the load.
14127     CombineTo(TheSelect, Load);
14128 
14129     // Users of the old loads now use the new load's chain.  We know the
14130     // old-load value is dead now.
14131     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14132     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14133     return true;
14134   }
14135 
14136   return false;
14137 }
14138 
14139 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14140 /// where 'cond' is the comparison specified by CC.
14141 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
14142                                       SDValue N2, SDValue N3,
14143                                       ISD::CondCode CC, bool NotExtCompare) {
14144   // (x ? y : y) -> y.
14145   if (N2 == N3) return N2;
14146 
14147   EVT VT = N2.getValueType();
14148   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14149   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14150 
14151   // Determine if the condition we're dealing with is constant
14152   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14153                               N0, N1, CC, DL, false);
14154   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14155 
14156   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14157     // fold select_cc true, x, y -> x
14158     // fold select_cc false, x, y -> y
14159     return !SCCC->isNullValue() ? N2 : N3;
14160   }
14161 
14162   // Check to see if we can simplify the select into an fabs node
14163   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14164     // Allow either -0.0 or 0.0
14165     if (CFP->isZero()) {
14166       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14167       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14168           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14169           N2 == N3.getOperand(0))
14170         return DAG.getNode(ISD::FABS, DL, VT, N0);
14171 
14172       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14173       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14174           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14175           N2.getOperand(0) == N3)
14176         return DAG.getNode(ISD::FABS, DL, VT, N3);
14177     }
14178   }
14179 
14180   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14181   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14182   // in it.  This is a win when the constant is not otherwise available because
14183   // it replaces two constant pool loads with one.  We only do this if the FP
14184   // type is known to be legal, because if it isn't, then we are before legalize
14185   // types an we want the other legalization to happen first (e.g. to avoid
14186   // messing with soft float) and if the ConstantFP is not legal, because if
14187   // it is legal, we may not need to store the FP constant in a constant pool.
14188   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14189     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14190       if (TLI.isTypeLegal(N2.getValueType()) &&
14191           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14192                TargetLowering::Legal &&
14193            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14194            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14195           // If both constants have multiple uses, then we won't need to do an
14196           // extra load, they are likely around in registers for other users.
14197           (TV->hasOneUse() || FV->hasOneUse())) {
14198         Constant *Elts[] = {
14199           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14200           const_cast<ConstantFP*>(TV->getConstantFPValue())
14201         };
14202         Type *FPTy = Elts[0]->getType();
14203         const DataLayout &TD = DAG.getDataLayout();
14204 
14205         // Create a ConstantArray of the two constants.
14206         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14207         SDValue CPIdx =
14208             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14209                                 TD.getPrefTypeAlignment(FPTy));
14210         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14211 
14212         // Get the offsets to the 0 and 1 element of the array so that we can
14213         // select between them.
14214         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14215         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14216         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14217 
14218         SDValue Cond = DAG.getSetCC(DL,
14219                                     getSetCCResultType(N0.getValueType()),
14220                                     N0, N1, CC);
14221         AddToWorklist(Cond.getNode());
14222         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14223                                           Cond, One, Zero);
14224         AddToWorklist(CstOffset.getNode());
14225         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14226                             CstOffset);
14227         AddToWorklist(CPIdx.getNode());
14228         return DAG.getLoad(
14229             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14230             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14231             false, false, false, Alignment);
14232       }
14233     }
14234 
14235   // Check to see if we can perform the "gzip trick", transforming
14236   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14237   if (isNullConstant(N3) && CC == ISD::SETLT &&
14238       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14239        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14240     EVT XType = N0.getValueType();
14241     EVT AType = N2.getValueType();
14242     if (XType.bitsGE(AType)) {
14243       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14244       // single-bit constant.
14245       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14246         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14247         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14248         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14249                                        getShiftAmountTy(N0.getValueType()));
14250         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14251                                     XType, N0, ShCt);
14252         AddToWorklist(Shift.getNode());
14253 
14254         if (XType.bitsGT(AType)) {
14255           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14256           AddToWorklist(Shift.getNode());
14257         }
14258 
14259         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14260       }
14261 
14262       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14263                                   XType, N0,
14264                                   DAG.getConstant(XType.getSizeInBits() - 1,
14265                                                   SDLoc(N0),
14266                                          getShiftAmountTy(N0.getValueType())));
14267       AddToWorklist(Shift.getNode());
14268 
14269       if (XType.bitsGT(AType)) {
14270         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14271         AddToWorklist(Shift.getNode());
14272       }
14273 
14274       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14275     }
14276   }
14277 
14278   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14279   // where y is has a single bit set.
14280   // A plaintext description would be, we can turn the SELECT_CC into an AND
14281   // when the condition can be materialized as an all-ones register.  Any
14282   // single bit-test can be materialized as an all-ones register with
14283   // shift-left and shift-right-arith.
14284   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14285       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14286     SDValue AndLHS = N0->getOperand(0);
14287     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14288     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14289       // Shift the tested bit over the sign bit.
14290       APInt AndMask = ConstAndRHS->getAPIntValue();
14291       SDValue ShlAmt =
14292         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14293                         getShiftAmountTy(AndLHS.getValueType()));
14294       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14295 
14296       // Now arithmetic right shift it all the way over, so the result is either
14297       // all-ones, or zero.
14298       SDValue ShrAmt =
14299         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14300                         getShiftAmountTy(Shl.getValueType()));
14301       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14302 
14303       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14304     }
14305   }
14306 
14307   // fold select C, 16, 0 -> shl C, 4
14308   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14309       TLI.getBooleanContents(N0.getValueType()) ==
14310           TargetLowering::ZeroOrOneBooleanContent) {
14311 
14312     // If the caller doesn't want us to simplify this into a zext of a compare,
14313     // don't do it.
14314     if (NotExtCompare && N2C->isOne())
14315       return SDValue();
14316 
14317     // Get a SetCC of the condition
14318     // NOTE: Don't create a SETCC if it's not legal on this target.
14319     if (!LegalOperations ||
14320         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14321       SDValue Temp, SCC;
14322       // cast from setcc result type to select result type
14323       if (LegalTypes) {
14324         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14325                             N0, N1, CC);
14326         if (N2.getValueType().bitsLT(SCC.getValueType()))
14327           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14328                                         N2.getValueType());
14329         else
14330           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14331                              N2.getValueType(), SCC);
14332       } else {
14333         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14334         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14335                            N2.getValueType(), SCC);
14336       }
14337 
14338       AddToWorklist(SCC.getNode());
14339       AddToWorklist(Temp.getNode());
14340 
14341       if (N2C->isOne())
14342         return Temp;
14343 
14344       // shl setcc result by log2 n2c
14345       return DAG.getNode(
14346           ISD::SHL, DL, N2.getValueType(), Temp,
14347           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14348                           getShiftAmountTy(Temp.getValueType())));
14349     }
14350   }
14351 
14352   // Check to see if this is an integer abs.
14353   // select_cc setg[te] X,  0,  X, -X ->
14354   // select_cc setgt    X, -1,  X, -X ->
14355   // select_cc setl[te] X,  0, -X,  X ->
14356   // select_cc setlt    X,  1, -X,  X ->
14357   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14358   if (N1C) {
14359     ConstantSDNode *SubC = nullptr;
14360     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14361          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14362         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14363       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14364     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14365               (N1C->isOne() && CC == ISD::SETLT)) &&
14366              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14367       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14368 
14369     EVT XType = N0.getValueType();
14370     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14371       SDLoc DL(N0);
14372       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14373                                   N0,
14374                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14375                                          getShiftAmountTy(N0.getValueType())));
14376       SDValue Add = DAG.getNode(ISD::ADD, DL,
14377                                 XType, N0, Shift);
14378       AddToWorklist(Shift.getNode());
14379       AddToWorklist(Add.getNode());
14380       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14381     }
14382   }
14383 
14384   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14385   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14386   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14387   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14388   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14389   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14390   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14391   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14392   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14393     SDValue ValueOnZero = N2;
14394     SDValue Count = N3;
14395     // If the condition is NE instead of E, swap the operands.
14396     if (CC == ISD::SETNE)
14397       std::swap(ValueOnZero, Count);
14398     // Check if the value on zero is a constant equal to the bits in the type.
14399     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14400       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14401         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14402         // legal, combine to just cttz.
14403         if ((Count.getOpcode() == ISD::CTTZ ||
14404              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14405             N0 == Count.getOperand(0) &&
14406             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14407           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14408         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14409         // legal, combine to just ctlz.
14410         if ((Count.getOpcode() == ISD::CTLZ ||
14411              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14412             N0 == Count.getOperand(0) &&
14413             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14414           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14415       }
14416     }
14417   }
14418 
14419   return SDValue();
14420 }
14421 
14422 /// This is a stub for TargetLowering::SimplifySetCC.
14423 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14424                                    SDValue N1, ISD::CondCode Cond,
14425                                    SDLoc DL, bool foldBooleans) {
14426   TargetLowering::DAGCombinerInfo
14427     DagCombineInfo(DAG, Level, false, this);
14428   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14429 }
14430 
14431 /// Given an ISD::SDIV node expressing a divide by constant, return
14432 /// a DAG expression to select that will generate the same value by multiplying
14433 /// by a magic number.
14434 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14435 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14436   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14437   if (!C)
14438     return SDValue();
14439 
14440   // Avoid division by zero.
14441   if (C->isNullValue())
14442     return SDValue();
14443 
14444   std::vector<SDNode*> Built;
14445   SDValue S =
14446       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14447 
14448   for (SDNode *N : Built)
14449     AddToWorklist(N);
14450   return S;
14451 }
14452 
14453 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14454 /// DAG expression that will generate the same value by right shifting.
14455 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14456   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14457   if (!C)
14458     return SDValue();
14459 
14460   // Avoid division by zero.
14461   if (C->isNullValue())
14462     return SDValue();
14463 
14464   std::vector<SDNode *> Built;
14465   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14466 
14467   for (SDNode *N : Built)
14468     AddToWorklist(N);
14469   return S;
14470 }
14471 
14472 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14473 /// expression that will generate the same value by multiplying by a magic
14474 /// number.
14475 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14476 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14477   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14478   if (!C)
14479     return SDValue();
14480 
14481   // Avoid division by zero.
14482   if (C->isNullValue())
14483     return SDValue();
14484 
14485   std::vector<SDNode*> Built;
14486   SDValue S =
14487       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14488 
14489   for (SDNode *N : Built)
14490     AddToWorklist(N);
14491   return S;
14492 }
14493 
14494 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14495   if (Level >= AfterLegalizeDAG)
14496     return SDValue();
14497 
14498   // Expose the DAG combiner to the target combiner implementations.
14499   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14500 
14501   unsigned Iterations = 0;
14502   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14503     if (Iterations) {
14504       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14505       // For the reciprocal, we need to find the zero of the function:
14506       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14507       //     =>
14508       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14509       //     does not require additional intermediate precision]
14510       EVT VT = Op.getValueType();
14511       SDLoc DL(Op);
14512       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14513 
14514       AddToWorklist(Est.getNode());
14515 
14516       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14517       for (unsigned i = 0; i < Iterations; ++i) {
14518         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14519         AddToWorklist(NewEst.getNode());
14520 
14521         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14522         AddToWorklist(NewEst.getNode());
14523 
14524         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14525         AddToWorklist(NewEst.getNode());
14526 
14527         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14528         AddToWorklist(Est.getNode());
14529       }
14530     }
14531     return Est;
14532   }
14533 
14534   return SDValue();
14535 }
14536 
14537 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14538 /// For the reciprocal sqrt, we need to find the zero of the function:
14539 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14540 ///     =>
14541 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14542 /// As a result, we precompute A/2 prior to the iteration loop.
14543 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14544                                           unsigned Iterations,
14545                                           SDNodeFlags *Flags) {
14546   EVT VT = Arg.getValueType();
14547   SDLoc DL(Arg);
14548   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14549 
14550   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14551   // this entire sequence requires only one FP constant.
14552   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14553   AddToWorklist(HalfArg.getNode());
14554 
14555   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14556   AddToWorklist(HalfArg.getNode());
14557 
14558   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14559   for (unsigned i = 0; i < Iterations; ++i) {
14560     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14561     AddToWorklist(NewEst.getNode());
14562 
14563     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14564     AddToWorklist(NewEst.getNode());
14565 
14566     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14567     AddToWorklist(NewEst.getNode());
14568 
14569     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14570     AddToWorklist(Est.getNode());
14571   }
14572   return Est;
14573 }
14574 
14575 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14576 /// For the reciprocal sqrt, we need to find the zero of the function:
14577 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14578 ///     =>
14579 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14580 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14581                                           unsigned Iterations,
14582                                           SDNodeFlags *Flags) {
14583   EVT VT = Arg.getValueType();
14584   SDLoc DL(Arg);
14585   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14586   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14587 
14588   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14589   for (unsigned i = 0; i < Iterations; ++i) {
14590     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14591     AddToWorklist(HalfEst.getNode());
14592 
14593     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14594     AddToWorklist(Est.getNode());
14595 
14596     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14597     AddToWorklist(Est.getNode());
14598 
14599     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14600     AddToWorklist(Est.getNode());
14601 
14602     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14603     AddToWorklist(Est.getNode());
14604   }
14605   return Est;
14606 }
14607 
14608 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14609   if (Level >= AfterLegalizeDAG)
14610     return SDValue();
14611 
14612   // Expose the DAG combiner to the target combiner implementations.
14613   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14614   unsigned Iterations = 0;
14615   bool UseOneConstNR = false;
14616   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14617     AddToWorklist(Est.getNode());
14618     if (Iterations) {
14619       Est = UseOneConstNR ?
14620         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14621         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14622     }
14623     return Est;
14624   }
14625 
14626   return SDValue();
14627 }
14628 
14629 /// Return true if base is a frame index, which is known not to alias with
14630 /// anything but itself.  Provides base object and offset as results.
14631 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14632                            const GlobalValue *&GV, const void *&CV) {
14633   // Assume it is a primitive operation.
14634   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14635 
14636   // If it's an adding a simple constant then integrate the offset.
14637   if (Base.getOpcode() == ISD::ADD) {
14638     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14639       Base = Base.getOperand(0);
14640       Offset += C->getZExtValue();
14641     }
14642   }
14643 
14644   // Return the underlying GlobalValue, and update the Offset.  Return false
14645   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14646   // by multiple nodes with different offsets.
14647   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14648     GV = G->getGlobal();
14649     Offset += G->getOffset();
14650     return false;
14651   }
14652 
14653   // Return the underlying Constant value, and update the Offset.  Return false
14654   // for ConstantSDNodes since the same constant pool entry may be represented
14655   // by multiple nodes with different offsets.
14656   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14657     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14658                                          : (const void *)C->getConstVal();
14659     Offset += C->getOffset();
14660     return false;
14661   }
14662   // If it's any of the following then it can't alias with anything but itself.
14663   return isa<FrameIndexSDNode>(Base);
14664 }
14665 
14666 /// Return true if there is any possibility that the two addresses overlap.
14667 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14668   // If they are the same then they must be aliases.
14669   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14670 
14671   // If they are both volatile then they cannot be reordered.
14672   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14673 
14674   // If one operation reads from invariant memory, and the other may store, they
14675   // cannot alias. These should really be checking the equivalent of mayWrite,
14676   // but it only matters for memory nodes other than load /store.
14677   if (Op0->isInvariant() && Op1->writeMem())
14678     return false;
14679 
14680   if (Op1->isInvariant() && Op0->writeMem())
14681     return false;
14682 
14683   // Gather base node and offset information.
14684   SDValue Base1, Base2;
14685   int64_t Offset1, Offset2;
14686   const GlobalValue *GV1, *GV2;
14687   const void *CV1, *CV2;
14688   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14689                                       Base1, Offset1, GV1, CV1);
14690   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14691                                       Base2, Offset2, GV2, CV2);
14692 
14693   // If they have a same base address then check to see if they overlap.
14694   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14695     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14696              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14697 
14698   // It is possible for different frame indices to alias each other, mostly
14699   // when tail call optimization reuses return address slots for arguments.
14700   // To catch this case, look up the actual index of frame indices to compute
14701   // the real alias relationship.
14702   if (isFrameIndex1 && isFrameIndex2) {
14703     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14704     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14705     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14706     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14707              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14708   }
14709 
14710   // Otherwise, if we know what the bases are, and they aren't identical, then
14711   // we know they cannot alias.
14712   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14713     return false;
14714 
14715   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14716   // compared to the size and offset of the access, we may be able to prove they
14717   // do not alias.  This check is conservative for now to catch cases created by
14718   // splitting vector types.
14719   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14720       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14721       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14722        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14723       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14724     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14725     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14726 
14727     // There is no overlap between these relatively aligned accesses of similar
14728     // size, return no alias.
14729     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14730         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14731       return false;
14732   }
14733 
14734   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14735                    ? CombinerGlobalAA
14736                    : DAG.getSubtarget().useAA();
14737 #ifndef NDEBUG
14738   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14739       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14740     UseAA = false;
14741 #endif
14742   if (UseAA &&
14743       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14744     // Use alias analysis information.
14745     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14746                                  Op1->getSrcValueOffset());
14747     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14748         Op0->getSrcValueOffset() - MinOffset;
14749     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14750         Op1->getSrcValueOffset() - MinOffset;
14751     AliasResult AAResult =
14752         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14753                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14754                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14755                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14756     if (AAResult == NoAlias)
14757       return false;
14758   }
14759 
14760   // Otherwise we have to assume they alias.
14761   return true;
14762 }
14763 
14764 /// Walk up chain skipping non-aliasing memory nodes,
14765 /// looking for aliasing nodes and adding them to the Aliases vector.
14766 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14767                                    SmallVectorImpl<SDValue> &Aliases) {
14768   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14769   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14770 
14771   // Get alias information for node.
14772   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14773 
14774   // Starting off.
14775   Chains.push_back(OriginalChain);
14776   unsigned Depth = 0;
14777 
14778   // Look at each chain and determine if it is an alias.  If so, add it to the
14779   // aliases list.  If not, then continue up the chain looking for the next
14780   // candidate.
14781   while (!Chains.empty()) {
14782     SDValue Chain = Chains.pop_back_val();
14783 
14784     // For TokenFactor nodes, look at each operand and only continue up the
14785     // chain until we reach the depth limit.
14786     //
14787     // FIXME: The depth check could be made to return the last non-aliasing
14788     // chain we found before we hit a tokenfactor rather than the original
14789     // chain.
14790     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14791       Aliases.clear();
14792       Aliases.push_back(OriginalChain);
14793       return;
14794     }
14795 
14796     // Don't bother if we've been before.
14797     if (!Visited.insert(Chain.getNode()).second)
14798       continue;
14799 
14800     switch (Chain.getOpcode()) {
14801     case ISD::EntryToken:
14802       // Entry token is ideal chain operand, but handled in FindBetterChain.
14803       break;
14804 
14805     case ISD::LOAD:
14806     case ISD::STORE: {
14807       // Get alias information for Chain.
14808       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14809           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14810 
14811       // If chain is alias then stop here.
14812       if (!(IsLoad && IsOpLoad) &&
14813           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14814         Aliases.push_back(Chain);
14815       } else {
14816         // Look further up the chain.
14817         Chains.push_back(Chain.getOperand(0));
14818         ++Depth;
14819       }
14820       break;
14821     }
14822 
14823     case ISD::TokenFactor:
14824       // We have to check each of the operands of the token factor for "small"
14825       // token factors, so we queue them up.  Adding the operands to the queue
14826       // (stack) in reverse order maintains the original order and increases the
14827       // likelihood that getNode will find a matching token factor (CSE.)
14828       if (Chain.getNumOperands() > 16) {
14829         Aliases.push_back(Chain);
14830         break;
14831       }
14832       for (unsigned n = Chain.getNumOperands(); n;)
14833         Chains.push_back(Chain.getOperand(--n));
14834       ++Depth;
14835       break;
14836 
14837     default:
14838       // For all other instructions we will just have to take what we can get.
14839       Aliases.push_back(Chain);
14840       break;
14841     }
14842   }
14843 }
14844 
14845 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14846 /// (aliasing node.)
14847 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14848   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14849 
14850   // Accumulate all the aliases to this node.
14851   GatherAllAliases(N, OldChain, Aliases);
14852 
14853   // If no operands then chain to entry token.
14854   if (Aliases.size() == 0)
14855     return DAG.getEntryNode();
14856 
14857   // If a single operand then chain to it.  We don't need to revisit it.
14858   if (Aliases.size() == 1)
14859     return Aliases[0];
14860 
14861   // Construct a custom tailored token factor.
14862   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14863 }
14864 
14865 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14866   // This holds the base pointer, index, and the offset in bytes from the base
14867   // pointer.
14868   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
14869 
14870   // We must have a base and an offset.
14871   if (!BasePtr.Base.getNode())
14872     return false;
14873 
14874   // Do not handle stores to undef base pointers.
14875   if (BasePtr.Base.isUndef())
14876     return false;
14877 
14878   SmallVector<StoreSDNode *, 8> ChainedStores;
14879   ChainedStores.push_back(St);
14880 
14881   // Walk up the chain and look for nodes with offsets from the same
14882   // base pointer. Stop when reaching an instruction with a different kind
14883   // or instruction which has a different base pointer.
14884   StoreSDNode *Index = St;
14885   while (Index) {
14886     // If the chain has more than one use, then we can't reorder the mem ops.
14887     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14888       break;
14889 
14890     if (Index->isVolatile() || Index->isIndexed())
14891       break;
14892 
14893     // Find the base pointer and offset for this memory node.
14894     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
14895 
14896     // Check that the base pointer is the same as the original one.
14897     if (!Ptr.equalBaseIndex(BasePtr))
14898       break;
14899 
14900     // Find the next memory operand in the chain. If the next operand in the
14901     // chain is a store then move up and continue the scan with the next
14902     // memory operand. If the next operand is a load save it and use alias
14903     // information to check if it interferes with anything.
14904     SDNode *NextInChain = Index->getChain().getNode();
14905     while (true) {
14906       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14907         // We found a store node. Use it for the next iteration.
14908         if (STn->isVolatile() || STn->isIndexed()) {
14909           Index = nullptr;
14910           break;
14911         }
14912         ChainedStores.push_back(STn);
14913         Index = STn;
14914         break;
14915       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14916         NextInChain = Ldn->getChain().getNode();
14917         continue;
14918       } else {
14919         Index = nullptr;
14920         break;
14921       }
14922     }
14923   }
14924 
14925   bool MadeChange = false;
14926   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14927 
14928   for (StoreSDNode *ChainedStore : ChainedStores) {
14929     SDValue Chain = ChainedStore->getChain();
14930     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14931 
14932     if (Chain != BetterChain) {
14933       MadeChange = true;
14934       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14935     }
14936   }
14937 
14938   // Do all replacements after finding the replacements to make to avoid making
14939   // the chains more complicated by introducing new TokenFactors.
14940   for (auto Replacement : BetterChains)
14941     replaceStoreChain(Replacement.first, Replacement.second);
14942 
14943   return MadeChange;
14944 }
14945 
14946 /// This is the entry point for the file.
14947 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14948                            CodeGenOpt::Level OptLevel) {
14949   /// This is the main entry point to this class.
14950   DAGCombiner(*this, AA, OptLevel).Run(Level);
14951 }
14952