bdcf5a2a89ece0a68e8186b29ed9bd63babf6907
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     /// Replaces all uses of the results of one DAG node with new values.
160     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161                       bool AddTo = true);
162
163     /// Replaces all uses of the results of one DAG node with new values.
164     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165       return CombineTo(N, &Res, 1, AddTo);
166     }
167
168     /// Replaces all uses of the results of one DAG node with new values.
169     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
170                       bool AddTo = true) {
171       SDValue To[] = { Res0, Res1 };
172       return CombineTo(N, To, 2, AddTo);
173     }
174
175     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176
177   private:
178
179     /// Check the specified integer node value to see if it can be simplified or
180     /// if things it uses can be simplified by bit propagation.
181     /// If so, return true.
182     bool SimplifyDemandedBits(SDValue Op) {
183       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184       APInt Demanded = APInt::getAllOnesValue(BitWidth);
185       return SimplifyDemandedBits(Op, Demanded);
186     }
187
188     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
189
190     bool CombineToPreIndexedLoadStore(SDNode *N);
191     bool CombineToPostIndexedLoadStore(SDNode *N);
192     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193     bool SliceUpLoad(SDNode *N);
194
195     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196     ///   load.
197     ///
198     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200     /// \param EltNo index of the vector element to load.
201     /// \param OriginalLoad load that EVE came from to be replaced.
202     /// \returns EVE on success SDValue() on failure.
203     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue PromoteIntBinOp(SDValue Op);
210     SDValue PromoteIntShiftOp(SDValue Op);
211     SDValue PromoteExtend(SDValue Op);
212     bool PromoteLoad(SDValue Op);
213
214     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216                          ISD::NodeType ExtType);
217
218     /// Call the node-specific routine that knows how to fold each
219     /// particular type of node. If that doesn't do anything, try the
220     /// target-specific DAG combines.
221     SDValue combine(SDNode *N);
222
223     // Visitation implementation - Implement dag node combining for different
224     // node types.  The semantics are as follows:
225     // Return Value:
226     //   SDValue.getNode() == 0 - No change was made
227     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
228     //   otherwise              - N should be replaced by the returned Operand.
229     //
230     SDValue visitTokenFactor(SDNode *N);
231     SDValue visitMERGE_VALUES(SDNode *N);
232     SDValue visitADD(SDNode *N);
233     SDValue visitSUB(SDNode *N);
234     SDValue visitADDC(SDNode *N);
235     SDValue visitSUBC(SDNode *N);
236     SDValue visitADDE(SDNode *N);
237     SDValue visitSUBE(SDNode *N);
238     SDValue visitMUL(SDNode *N);
239     SDValue useDivRem(SDNode *N);
240     SDValue visitSDIV(SDNode *N);
241     SDValue visitUDIV(SDNode *N);
242     SDValue visitREM(SDNode *N);
243     SDValue visitMULHU(SDNode *N);
244     SDValue visitMULHS(SDNode *N);
245     SDValue visitSMUL_LOHI(SDNode *N);
246     SDValue visitUMUL_LOHI(SDNode *N);
247     SDValue visitSMULO(SDNode *N);
248     SDValue visitUMULO(SDNode *N);
249     SDValue visitIMINMAX(SDNode *N);
250     SDValue visitAND(SDNode *N);
251     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitOR(SDNode *N);
253     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254     SDValue visitXOR(SDNode *N);
255     SDValue SimplifyVBinOp(SDNode *N);
256     SDValue visitSHL(SDNode *N);
257     SDValue visitSRA(SDNode *N);
258     SDValue visitSRL(SDNode *N);
259     SDValue visitRotate(SDNode *N);
260     SDValue visitBSWAP(SDNode *N);
261     SDValue visitCTLZ(SDNode *N);
262     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTTZ(SDNode *N);
264     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTPOP(SDNode *N);
266     SDValue visitSELECT(SDNode *N);
267     SDValue visitVSELECT(SDNode *N);
268     SDValue visitSELECT_CC(SDNode *N);
269     SDValue visitSETCC(SDNode *N);
270     SDValue visitSETCCE(SDNode *N);
271     SDValue visitSIGN_EXTEND(SDNode *N);
272     SDValue visitZERO_EXTEND(SDNode *N);
273     SDValue visitANY_EXTEND(SDNode *N);
274     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
275     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
276     SDValue visitTRUNCATE(SDNode *N);
277     SDValue visitBITCAST(SDNode *N);
278     SDValue visitBUILD_PAIR(SDNode *N);
279     SDValue visitFADD(SDNode *N);
280     SDValue visitFSUB(SDNode *N);
281     SDValue visitFMUL(SDNode *N);
282     SDValue visitFMA(SDNode *N);
283     SDValue visitFDIV(SDNode *N);
284     SDValue visitFREM(SDNode *N);
285     SDValue visitFSQRT(SDNode *N);
286     SDValue visitFCOPYSIGN(SDNode *N);
287     SDValue visitSINT_TO_FP(SDNode *N);
288     SDValue visitUINT_TO_FP(SDNode *N);
289     SDValue visitFP_TO_SINT(SDNode *N);
290     SDValue visitFP_TO_UINT(SDNode *N);
291     SDValue visitFP_ROUND(SDNode *N);
292     SDValue visitFP_ROUND_INREG(SDNode *N);
293     SDValue visitFP_EXTEND(SDNode *N);
294     SDValue visitFNEG(SDNode *N);
295     SDValue visitFABS(SDNode *N);
296     SDValue visitFCEIL(SDNode *N);
297     SDValue visitFTRUNC(SDNode *N);
298     SDValue visitFFLOOR(SDNode *N);
299     SDValue visitFMINNUM(SDNode *N);
300     SDValue visitFMAXNUM(SDNode *N);
301     SDValue visitBRCOND(SDNode *N);
302     SDValue visitBR_CC(SDNode *N);
303     SDValue visitLOAD(SDNode *N);
304
305     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
306     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
307
308     SDValue visitSTORE(SDNode *N);
309     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
310     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
311     SDValue visitBUILD_VECTOR(SDNode *N);
312     SDValue visitCONCAT_VECTORS(SDNode *N);
313     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
314     SDValue visitVECTOR_SHUFFLE(SDNode *N);
315     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
316     SDValue visitINSERT_SUBVECTOR(SDNode *N);
317     SDValue visitMLOAD(SDNode *N);
318     SDValue visitMSTORE(SDNode *N);
319     SDValue visitMGATHER(SDNode *N);
320     SDValue visitMSCATTER(SDNode *N);
321     SDValue visitFP_TO_FP16(SDNode *N);
322     SDValue visitFP16_TO_FP(SDNode *N);
323
324     SDValue visitFADDForFMACombine(SDNode *N);
325     SDValue visitFSUBForFMACombine(SDNode *N);
326     SDValue visitFMULForFMACombine(SDNode *N);
327
328     SDValue XformToShuffleWithZero(SDNode *N);
329     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
330
331     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
332
333     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
334     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
335     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
336     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
337                              SDValue N3, ISD::CondCode CC,
338                              bool NotExtCompare = false);
339     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
340                           SDLoc DL, bool foldBooleans = true);
341
342     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
343                            SDValue &CC) const;
344     bool isOneUseSetCC(SDValue N) const;
345
346     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
347                                          unsigned HiOp);
348     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
349     SDValue CombineExtLoad(SDNode *N);
350     SDValue combineRepeatedFPDivisors(SDNode *N);
351     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
352     SDValue BuildSDIV(SDNode *N);
353     SDValue BuildSDIVPow2(SDNode *N);
354     SDValue BuildUDIV(SDNode *N);
355     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
356     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
357     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
358                                  SDNodeFlags *Flags);
359     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
360                                  SDNodeFlags *Flags);
361     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
362                                bool DemandHighBits = true);
363     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
364     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
365                               SDValue InnerPos, SDValue InnerNeg,
366                               unsigned PosOpcode, unsigned NegOpcode,
367                               SDLoc DL);
368     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
369     SDValue ReduceLoadWidth(SDNode *N);
370     SDValue ReduceLoadOpStoreWidth(SDNode *N);
371     SDValue TransformFPLoadStorePair(SDNode *N);
372     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
373     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
374
375     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
376
377     /// Walk up chain skipping non-aliasing memory nodes,
378     /// looking for aliasing nodes and adding them to the Aliases vector.
379     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
380                           SmallVectorImpl<SDValue> &Aliases);
381
382     /// Return true if there is any possibility that the two addresses overlap.
383     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
384
385     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
386     /// chain (aliasing node.)
387     SDValue FindBetterChain(SDNode *N, SDValue Chain);
388
389     /// Do FindBetterChain for a store and any possibly adjacent stores on
390     /// consecutive chains.
391     bool findBetterNeighborChains(StoreSDNode *St);
392
393     /// Holds a pointer to an LSBaseSDNode as well as information on where it
394     /// is located in a sequence of memory operations connected by a chain.
395     struct MemOpLink {
396       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
397       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
398       // Ptr to the mem node.
399       LSBaseSDNode *MemNode;
400       // Offset from the base ptr.
401       int64_t OffsetFromBase;
402       // What is the sequence number of this mem node.
403       // Lowest mem operand in the DAG starts at zero.
404       unsigned SequenceNum;
405     };
406
407     /// This is a helper function for visitMUL to check the profitability
408     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
409     /// MulNode is the original multiply, AddNode is (add x, c1),
410     /// and ConstNode is c2.
411     bool isMulAddWithConstProfitable(SDNode *MulNode,
412                                      SDValue &AddNode,
413                                      SDValue &ConstNode);
414
415     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
416     /// constant build_vector of the stored constant values in Stores.
417     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
418                                          SDLoc SL,
419                                          ArrayRef<MemOpLink> Stores,
420                                          SmallVectorImpl<SDValue> &Chains,
421                                          EVT Ty) const;
422
423     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
424     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
425     /// the type of the loaded value to be extended.  LoadedVT returns the type
426     /// of the original loaded value.  NarrowLoad returns whether the load would
427     /// need to be narrowed in order to match.
428     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
429                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
430                           bool &NarrowLoad);
431
432     /// This is a helper function for MergeConsecutiveStores. When the source
433     /// elements of the consecutive stores are all constants or all extracted
434     /// vector elements, try to merge them into one larger store.
435     /// \return True if a merged store was created.
436     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
437                                          EVT MemVT, unsigned NumStores,
438                                          bool IsConstantSrc, bool UseVector);
439
440     /// This is a helper function for MergeConsecutiveStores.
441     /// Stores that may be merged are placed in StoreNodes.
442     /// Loads that may alias with those stores are placed in AliasLoadNodes.
443     void getStoreMergeAndAliasCandidates(
444         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
445         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
446
447     /// Merge consecutive store operations into a wide store.
448     /// This optimization uses wide integers or vectors when possible.
449     /// \return True if some memory operations were changed.
450     bool MergeConsecutiveStores(StoreSDNode *N);
451
452     /// \brief Try to transform a truncation where C is a constant:
453     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
454     ///
455     /// \p N needs to be a truncation and its first operand an AND. Other
456     /// requirements are checked by the function (e.g. that trunc is
457     /// single-use) and if missed an empty SDValue is returned.
458     SDValue distributeTruncateThroughAnd(SDNode *N);
459
460   public:
461     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
462         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
463           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
464       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
465     }
466
467     /// Runs the dag combiner on all nodes in the work list
468     void Run(CombineLevel AtLevel);
469
470     SelectionDAG &getDAG() const { return DAG; }
471
472     /// Returns a type large enough to hold any valid shift amount - before type
473     /// legalization these can be huge.
474     EVT getShiftAmountTy(EVT LHSTy) {
475       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
476       if (LHSTy.isVector())
477         return LHSTy;
478       auto &DL = DAG.getDataLayout();
479       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
480                         : TLI.getPointerTy(DL);
481     }
482
483     /// This method returns true if we are running before type legalization or
484     /// if the specified VT is legal.
485     bool isTypeLegal(const EVT &VT) {
486       if (!LegalTypes) return true;
487       return TLI.isTypeLegal(VT);
488     }
489
490     /// Convenience wrapper around TargetLowering::getSetCCResultType
491     EVT getSetCCResultType(EVT VT) const {
492       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
493     }
494   };
495 }
496
497
498 namespace {
499 /// This class is a DAGUpdateListener that removes any deleted
500 /// nodes from the worklist.
501 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
502   DAGCombiner &DC;
503 public:
504   explicit WorklistRemover(DAGCombiner &dc)
505     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
506
507   void NodeDeleted(SDNode *N, SDNode *E) override {
508     DC.removeFromWorklist(N);
509   }
510 };
511 }
512
513 //===----------------------------------------------------------------------===//
514 //  TargetLowering::DAGCombinerInfo implementation
515 //===----------------------------------------------------------------------===//
516
517 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
518   ((DAGCombiner*)DC)->AddToWorklist(N);
519 }
520
521 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
522   ((DAGCombiner*)DC)->removeFromWorklist(N);
523 }
524
525 SDValue TargetLowering::DAGCombinerInfo::
526 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
527   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
528 }
529
530 SDValue TargetLowering::DAGCombinerInfo::
531 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
532   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
533 }
534
535
536 SDValue TargetLowering::DAGCombinerInfo::
537 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
538   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
539 }
540
541 void TargetLowering::DAGCombinerInfo::
542 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
543   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
544 }
545
546 //===----------------------------------------------------------------------===//
547 // Helper Functions
548 //===----------------------------------------------------------------------===//
549
550 void DAGCombiner::deleteAndRecombine(SDNode *N) {
551   removeFromWorklist(N);
552
553   // If the operands of this node are only used by the node, they will now be
554   // dead. Make sure to re-visit them and recursively delete dead nodes.
555   for (const SDValue &Op : N->ops())
556     // For an operand generating multiple values, one of the values may
557     // become dead allowing further simplification (e.g. split index
558     // arithmetic from an indexed load).
559     if (Op->hasOneUse() || Op->getNumValues() > 1)
560       AddToWorklist(Op.getNode());
561
562   DAG.DeleteNode(N);
563 }
564
565 /// Return 1 if we can compute the negated form of the specified expression for
566 /// the same cost as the expression itself, or 2 if we can compute the negated
567 /// form more cheaply than the expression itself.
568 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
569                                const TargetLowering &TLI,
570                                const TargetOptions *Options,
571                                unsigned Depth = 0) {
572   // fneg is removable even if it has multiple uses.
573   if (Op.getOpcode() == ISD::FNEG) return 2;
574
575   // Don't allow anything with multiple uses.
576   if (!Op.hasOneUse()) return 0;
577
578   // Don't recurse exponentially.
579   if (Depth > 6) return 0;
580
581   switch (Op.getOpcode()) {
582   default: return false;
583   case ISD::ConstantFP:
584     // Don't invert constant FP values after legalize.  The negated constant
585     // isn't necessarily legal.
586     return LegalOperations ? 0 : 1;
587   case ISD::FADD:
588     // FIXME: determine better conditions for this xform.
589     if (!Options->UnsafeFPMath) return 0;
590
591     // After operation legalization, it might not be legal to create new FSUBs.
592     if (LegalOperations &&
593         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
594       return 0;
595
596     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
597     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
598                                     Options, Depth + 1))
599       return V;
600     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
601     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
602                               Depth + 1);
603   case ISD::FSUB:
604     // We can't turn -(A-B) into B-A when we honor signed zeros.
605     if (!Options->UnsafeFPMath) return 0;
606
607     // fold (fneg (fsub A, B)) -> (fsub B, A)
608     return 1;
609
610   case ISD::FMUL:
611   case ISD::FDIV:
612     if (Options->HonorSignDependentRoundingFPMath()) return 0;
613
614     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
615     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
616                                     Options, Depth + 1))
617       return V;
618
619     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
620                               Depth + 1);
621
622   case ISD::FP_EXTEND:
623   case ISD::FP_ROUND:
624   case ISD::FSIN:
625     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
626                               Depth + 1);
627   }
628 }
629
630 /// If isNegatibleForFree returns true, return the newly negated expression.
631 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
632                                     bool LegalOperations, unsigned Depth = 0) {
633   const TargetOptions &Options = DAG.getTarget().Options;
634   // fneg is removable even if it has multiple uses.
635   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
636
637   // Don't allow anything with multiple uses.
638   assert(Op.hasOneUse() && "Unknown reuse!");
639
640   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
641
642   const SDNodeFlags *Flags = Op.getNode()->getFlags();
643
644   switch (Op.getOpcode()) {
645   default: llvm_unreachable("Unknown code");
646   case ISD::ConstantFP: {
647     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
648     V.changeSign();
649     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
650   }
651   case ISD::FADD:
652     // FIXME: determine better conditions for this xform.
653     assert(Options.UnsafeFPMath);
654
655     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
656     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
657                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
658       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
659                          GetNegatedExpression(Op.getOperand(0), DAG,
660                                               LegalOperations, Depth+1),
661                          Op.getOperand(1), Flags);
662     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
663     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
664                        GetNegatedExpression(Op.getOperand(1), DAG,
665                                             LegalOperations, Depth+1),
666                        Op.getOperand(0), Flags);
667   case ISD::FSUB:
668     // We can't turn -(A-B) into B-A when we honor signed zeros.
669     assert(Options.UnsafeFPMath);
670
671     // fold (fneg (fsub 0, B)) -> B
672     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
673       if (N0CFP->isZero())
674         return Op.getOperand(1);
675
676     // fold (fneg (fsub A, B)) -> (fsub B, A)
677     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
678                        Op.getOperand(1), Op.getOperand(0), Flags);
679
680   case ISD::FMUL:
681   case ISD::FDIV:
682     assert(!Options.HonorSignDependentRoundingFPMath());
683
684     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
685     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
686                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
687       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
688                          GetNegatedExpression(Op.getOperand(0), DAG,
689                                               LegalOperations, Depth+1),
690                          Op.getOperand(1), Flags);
691
692     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
693     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
694                        Op.getOperand(0),
695                        GetNegatedExpression(Op.getOperand(1), DAG,
696                                             LegalOperations, Depth+1), Flags);
697
698   case ISD::FP_EXTEND:
699   case ISD::FSIN:
700     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
701                        GetNegatedExpression(Op.getOperand(0), DAG,
702                                             LegalOperations, Depth+1));
703   case ISD::FP_ROUND:
704       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
705                          GetNegatedExpression(Op.getOperand(0), DAG,
706                                               LegalOperations, Depth+1),
707                          Op.getOperand(1));
708   }
709 }
710
711 // Return true if this node is a setcc, or is a select_cc
712 // that selects between the target values used for true and false, making it
713 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
714 // the appropriate nodes based on the type of node we are checking. This
715 // simplifies life a bit for the callers.
716 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
717                                     SDValue &CC) const {
718   if (N.getOpcode() == ISD::SETCC) {
719     LHS = N.getOperand(0);
720     RHS = N.getOperand(1);
721     CC  = N.getOperand(2);
722     return true;
723   }
724
725   if (N.getOpcode() != ISD::SELECT_CC ||
726       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
727       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
728     return false;
729
730   if (TLI.getBooleanContents(N.getValueType()) ==
731       TargetLowering::UndefinedBooleanContent)
732     return false;
733
734   LHS = N.getOperand(0);
735   RHS = N.getOperand(1);
736   CC  = N.getOperand(4);
737   return true;
738 }
739
740 /// Return true if this is a SetCC-equivalent operation with only one use.
741 /// If this is true, it allows the users to invert the operation for free when
742 /// it is profitable to do so.
743 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
744   SDValue N0, N1, N2;
745   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
746     return true;
747   return false;
748 }
749
750 /// Returns true if N is a BUILD_VECTOR node whose
751 /// elements are all the same constant or undefined.
752 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
753   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
754   if (!C)
755     return false;
756
757   APInt SplatUndef;
758   unsigned SplatBitSize;
759   bool HasAnyUndefs;
760   EVT EltVT = N->getValueType(0).getVectorElementType();
761   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
762                              HasAnyUndefs) &&
763           EltVT.getSizeInBits() >= SplatBitSize);
764 }
765
766 // \brief Returns the SDNode if it is a constant integer BuildVector
767 // or constant integer.
768 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
769   if (isa<ConstantSDNode>(N))
770     return N.getNode();
771   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
772     return N.getNode();
773   return nullptr;
774 }
775
776 // \brief Returns the SDNode if it is a constant float BuildVector
777 // or constant float.
778 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
779   if (isa<ConstantFPSDNode>(N))
780     return N.getNode();
781   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
782     return N.getNode();
783   return nullptr;
784 }
785
786 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
787 // int.
788 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
789   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
790     return CN;
791
792   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
793     BitVector UndefElements;
794     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
795
796     // BuildVectors can truncate their operands. Ignore that case here.
797     // FIXME: We blindly ignore splats which include undef which is overly
798     // pessimistic.
799     if (CN && UndefElements.none() &&
800         CN->getValueType(0) == N.getValueType().getScalarType())
801       return CN;
802   }
803
804   return nullptr;
805 }
806
807 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
808 // float.
809 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
810   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
811     return CN;
812
813   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
814     BitVector UndefElements;
815     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
816
817     if (CN && UndefElements.none())
818       return CN;
819   }
820
821   return nullptr;
822 }
823
824 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
825                                     SDValue N0, SDValue N1) {
826   EVT VT = N0.getValueType();
827   if (N0.getOpcode() == Opc) {
828     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
829       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
830         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
831         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
832           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
833         return SDValue();
834       }
835       if (N0.hasOneUse()) {
836         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
837         // use
838         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
839         if (!OpNode.getNode())
840           return SDValue();
841         AddToWorklist(OpNode.getNode());
842         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
843       }
844     }
845   }
846
847   if (N1.getOpcode() == Opc) {
848     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
849       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
850         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
851         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
852           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
853         return SDValue();
854       }
855       if (N1.hasOneUse()) {
856         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
857         // use
858         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
859         if (!OpNode.getNode())
860           return SDValue();
861         AddToWorklist(OpNode.getNode());
862         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
863       }
864     }
865   }
866
867   return SDValue();
868 }
869
870 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
871                                bool AddTo) {
872   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
873   ++NodesCombined;
874   DEBUG(dbgs() << "\nReplacing.1 ";
875         N->dump(&DAG);
876         dbgs() << "\nWith: ";
877         To[0].getNode()->dump(&DAG);
878         dbgs() << " and " << NumTo-1 << " other values\n");
879   for (unsigned i = 0, e = NumTo; i != e; ++i)
880     assert((!To[i].getNode() ||
881             N->getValueType(i) == To[i].getValueType()) &&
882            "Cannot combine value to value of different type!");
883
884   WorklistRemover DeadNodes(*this);
885   DAG.ReplaceAllUsesWith(N, To);
886   if (AddTo) {
887     // Push the new nodes and any users onto the worklist
888     for (unsigned i = 0, e = NumTo; i != e; ++i) {
889       if (To[i].getNode()) {
890         AddToWorklist(To[i].getNode());
891         AddUsersToWorklist(To[i].getNode());
892       }
893     }
894   }
895
896   // Finally, if the node is now dead, remove it from the graph.  The node
897   // may not be dead if the replacement process recursively simplified to
898   // something else needing this node.
899   if (N->use_empty())
900     deleteAndRecombine(N);
901   return SDValue(N, 0);
902 }
903
904 void DAGCombiner::
905 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
906   // Replace all uses.  If any nodes become isomorphic to other nodes and
907   // are deleted, make sure to remove them from our worklist.
908   WorklistRemover DeadNodes(*this);
909   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
910
911   // Push the new node and any (possibly new) users onto the worklist.
912   AddToWorklist(TLO.New.getNode());
913   AddUsersToWorklist(TLO.New.getNode());
914
915   // Finally, if the node is now dead, remove it from the graph.  The node
916   // may not be dead if the replacement process recursively simplified to
917   // something else needing this node.
918   if (TLO.Old.getNode()->use_empty())
919     deleteAndRecombine(TLO.Old.getNode());
920 }
921
922 /// Check the specified integer node value to see if it can be simplified or if
923 /// things it uses can be simplified by bit propagation. If so, return true.
924 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
925   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
926   APInt KnownZero, KnownOne;
927
928   // XXX-disabled:
929   auto Opcode = Op.getOpcode();
930   if (Opcode == ISD::AND || Opcode == ISD::OR) {
931     auto* Op1 = Op.getOperand(0).getNode();
932     auto* Op2 = Op.getOperand(1).getNode();
933     auto* Op1C = dyn_cast<ConstantSDNode>(Op1);
934     auto* Op2C = dyn_cast<ConstantSDNode>(Op2);
935
936     // and X, 0
937     if (Opcode == ISD::AND && !Op1C && Op2C && Op2C->isNullValue()) {
938       return false;
939     }
940
941     // or (and X, 0), Y
942     if (Opcode == ISD::OR) {
943       if (Op1->getOpcode() == ISD::AND) {
944         auto* Op11 = Op1->getOperand(0).getNode();
945         auto* Op12 = Op1->getOperand(1).getNode();
946         auto* Op11C = dyn_cast<ConstantSDNode>(Op11);
947         auto* Op12C = dyn_cast<ConstantSDNode>(Op12);
948         if (!Op11C && Op12C && Op12C->isNullValue()) {
949           return false;
950         }
951       }
952       if (Op1->getOpcode() == ISD::TRUNCATE) {
953         // or (trunc (and %0, 0)), Y
954         auto* Op11 = Op1->getOperand(0).getNode();
955         if (Op11->getOpcode() == ISD::AND) {
956           auto* Op111 = Op11->getOperand(0).getNode();
957           auto* Op112 = Op11->getOperand(1).getNode();
958           auto* Op111C = dyn_cast<ConstantSDNode>(Op111);
959           auto* Op112C = dyn_cast<ConstantSDNode>(Op112);
960           if (!Op111C && Op112C && Op112C->isNullValue()) {
961             // or (and X, 0), Y
962             return false;
963           }
964         }
965       }
966     }
967   }
968
969   // trunc (and X, 0)
970   if (Opcode == ISD::TRUNCATE) {
971     auto* Op1 = Op.getOperand(0).getNode();
972     if (Op1->getOpcode() == ISD::AND) {
973       auto* Op11 = Op1->getOperand(0).getNode();
974       auto* Op12 = Op1->getOperand(1).getNode();
975       auto* Op11C = dyn_cast<ConstantSDNode>(Op11);
976       auto* Op12C = dyn_cast<ConstantSDNode>(Op12);
977       if (!Op11C && Op12C && Op12C->isNullValue()) {
978         return false;
979       }
980     }
981   }
982
983   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
984     return false;
985
986   // Revisit the node.
987   AddToWorklist(Op.getNode());
988
989   // Replace the old value with the new one.
990   ++NodesCombined;
991   DEBUG(dbgs() << "\nReplacing.2 ";
992         TLO.Old.getNode()->dump(&DAG);
993         dbgs() << "\nWith: ";
994         TLO.New.getNode()->dump(&DAG);
995         dbgs() << '\n');
996
997   CommitTargetLoweringOpt(TLO);
998   return true;
999 }
1000
1001 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1002   SDLoc dl(Load);
1003   EVT VT = Load->getValueType(0);
1004   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
1005
1006   DEBUG(dbgs() << "\nReplacing.9 ";
1007         Load->dump(&DAG);
1008         dbgs() << "\nWith: ";
1009         Trunc.getNode()->dump(&DAG);
1010         dbgs() << '\n');
1011   WorklistRemover DeadNodes(*this);
1012   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1013   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1014   deleteAndRecombine(Load);
1015   AddToWorklist(Trunc.getNode());
1016 }
1017
1018 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1019   Replace = false;
1020   SDLoc dl(Op);
1021   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
1022     EVT MemVT = LD->getMemoryVT();
1023     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1024       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1025                                                        : ISD::EXTLOAD)
1026       : LD->getExtensionType();
1027     Replace = true;
1028     return DAG.getExtLoad(ExtType, dl, PVT,
1029                           LD->getChain(), LD->getBasePtr(),
1030                           MemVT, LD->getMemOperand());
1031   }
1032
1033   unsigned Opc = Op.getOpcode();
1034   switch (Opc) {
1035   default: break;
1036   case ISD::AssertSext:
1037     return DAG.getNode(ISD::AssertSext, dl, PVT,
1038                        SExtPromoteOperand(Op.getOperand(0), PVT),
1039                        Op.getOperand(1));
1040   case ISD::AssertZext:
1041     return DAG.getNode(ISD::AssertZext, dl, PVT,
1042                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1043                        Op.getOperand(1));
1044   case ISD::Constant: {
1045     unsigned ExtOpc =
1046       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1047     return DAG.getNode(ExtOpc, dl, PVT, Op);
1048   }
1049   }
1050
1051   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1052     return SDValue();
1053   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1054 }
1055
1056 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1057   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1058     return SDValue();
1059   EVT OldVT = Op.getValueType();
1060   SDLoc dl(Op);
1061   bool Replace = false;
1062   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1063   if (!NewOp.getNode())
1064     return SDValue();
1065   AddToWorklist(NewOp.getNode());
1066
1067   if (Replace)
1068     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1069   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1070                      DAG.getValueType(OldVT));
1071 }
1072
1073 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1074   EVT OldVT = Op.getValueType();
1075   SDLoc dl(Op);
1076   bool Replace = false;
1077   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1078   if (!NewOp.getNode())
1079     return SDValue();
1080   AddToWorklist(NewOp.getNode());
1081
1082   if (Replace)
1083     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1084   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1085 }
1086
1087 /// Promote the specified integer binary operation if the target indicates it is
1088 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1089 /// i32 since i16 instructions are longer.
1090 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1091   if (!LegalOperations)
1092     return SDValue();
1093
1094   EVT VT = Op.getValueType();
1095   if (VT.isVector() || !VT.isInteger())
1096     return SDValue();
1097
1098   // If operation type is 'undesirable', e.g. i16 on x86, consider
1099   // promoting it.
1100   unsigned Opc = Op.getOpcode();
1101   if (TLI.isTypeDesirableForOp(Opc, VT))
1102     return SDValue();
1103
1104   EVT PVT = VT;
1105   // Consult target whether it is a good idea to promote this operation and
1106   // what's the right type to promote it to.
1107   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1108     assert(PVT != VT && "Don't know what type to promote to!");
1109
1110     bool Replace0 = false;
1111     SDValue N0 = Op.getOperand(0);
1112     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1113     if (!NN0.getNode())
1114       return SDValue();
1115
1116     bool Replace1 = false;
1117     SDValue N1 = Op.getOperand(1);
1118     SDValue NN1;
1119     if (N0 == N1)
1120       NN1 = NN0;
1121     else {
1122       NN1 = PromoteOperand(N1, PVT, Replace1);
1123       if (!NN1.getNode())
1124         return SDValue();
1125     }
1126
1127     AddToWorklist(NN0.getNode());
1128     if (NN1.getNode())
1129       AddToWorklist(NN1.getNode());
1130
1131     if (Replace0)
1132       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1133     if (Replace1)
1134       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1135
1136     DEBUG(dbgs() << "\nPromoting ";
1137           Op.getNode()->dump(&DAG));
1138     SDLoc dl(Op);
1139     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1140                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1141   }
1142   return SDValue();
1143 }
1144
1145 /// Promote the specified integer shift operation if the target indicates it is
1146 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1147 /// i32 since i16 instructions are longer.
1148 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1149   if (!LegalOperations)
1150     return SDValue();
1151
1152   EVT VT = Op.getValueType();
1153   if (VT.isVector() || !VT.isInteger())
1154     return SDValue();
1155
1156   // If operation type is 'undesirable', e.g. i16 on x86, consider
1157   // promoting it.
1158   unsigned Opc = Op.getOpcode();
1159   if (TLI.isTypeDesirableForOp(Opc, VT))
1160     return SDValue();
1161
1162   EVT PVT = VT;
1163   // Consult target whether it is a good idea to promote this operation and
1164   // what's the right type to promote it to.
1165   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1166     assert(PVT != VT && "Don't know what type to promote to!");
1167
1168     bool Replace = false;
1169     SDValue N0 = Op.getOperand(0);
1170     if (Opc == ISD::SRA)
1171       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1172     else if (Opc == ISD::SRL)
1173       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1174     else
1175       N0 = PromoteOperand(N0, PVT, Replace);
1176     if (!N0.getNode())
1177       return SDValue();
1178
1179     AddToWorklist(N0.getNode());
1180     if (Replace)
1181       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1182
1183     DEBUG(dbgs() << "\nPromoting ";
1184           Op.getNode()->dump(&DAG));
1185     SDLoc dl(Op);
1186     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1187                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1188   }
1189   return SDValue();
1190 }
1191
1192 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1193   if (!LegalOperations)
1194     return SDValue();
1195
1196   EVT VT = Op.getValueType();
1197   if (VT.isVector() || !VT.isInteger())
1198     return SDValue();
1199
1200   // If operation type is 'undesirable', e.g. i16 on x86, consider
1201   // promoting it.
1202   unsigned Opc = Op.getOpcode();
1203   if (TLI.isTypeDesirableForOp(Opc, VT))
1204     return SDValue();
1205
1206   EVT PVT = VT;
1207   // Consult target whether it is a good idea to promote this operation and
1208   // what's the right type to promote it to.
1209   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1210     assert(PVT != VT && "Don't know what type to promote to!");
1211     // fold (aext (aext x)) -> (aext x)
1212     // fold (aext (zext x)) -> (zext x)
1213     // fold (aext (sext x)) -> (sext x)
1214     DEBUG(dbgs() << "\nPromoting ";
1215           Op.getNode()->dump(&DAG));
1216     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1217   }
1218   return SDValue();
1219 }
1220
1221 bool DAGCombiner::PromoteLoad(SDValue Op) {
1222   if (!LegalOperations)
1223     return false;
1224
1225   EVT VT = Op.getValueType();
1226   if (VT.isVector() || !VT.isInteger())
1227     return false;
1228
1229   // If operation type is 'undesirable', e.g. i16 on x86, consider
1230   // promoting it.
1231   unsigned Opc = Op.getOpcode();
1232   if (TLI.isTypeDesirableForOp(Opc, VT))
1233     return false;
1234
1235   EVT PVT = VT;
1236   // Consult target whether it is a good idea to promote this operation and
1237   // what's the right type to promote it to.
1238   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1239     assert(PVT != VT && "Don't know what type to promote to!");
1240
1241     SDLoc dl(Op);
1242     SDNode *N = Op.getNode();
1243     LoadSDNode *LD = cast<LoadSDNode>(N);
1244     EVT MemVT = LD->getMemoryVT();
1245     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1246       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1247                                                        : ISD::EXTLOAD)
1248       : LD->getExtensionType();
1249     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1250                                    LD->getChain(), LD->getBasePtr(),
1251                                    MemVT, LD->getMemOperand());
1252     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1253
1254     DEBUG(dbgs() << "\nPromoting ";
1255           N->dump(&DAG);
1256           dbgs() << "\nTo: ";
1257           Result.getNode()->dump(&DAG);
1258           dbgs() << '\n');
1259     WorklistRemover DeadNodes(*this);
1260     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1262     deleteAndRecombine(N);
1263     AddToWorklist(Result.getNode());
1264     return true;
1265   }
1266   return false;
1267 }
1268
1269 /// \brief Recursively delete a node which has no uses and any operands for
1270 /// which it is the only use.
1271 ///
1272 /// Note that this both deletes the nodes and removes them from the worklist.
1273 /// It also adds any nodes who have had a user deleted to the worklist as they
1274 /// may now have only one use and subject to other combines.
1275 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1276   if (!N->use_empty())
1277     return false;
1278
1279   SmallSetVector<SDNode *, 16> Nodes;
1280   Nodes.insert(N);
1281   do {
1282     N = Nodes.pop_back_val();
1283     if (!N)
1284       continue;
1285
1286     if (N->use_empty()) {
1287       for (const SDValue &ChildN : N->op_values())
1288         Nodes.insert(ChildN.getNode());
1289
1290       removeFromWorklist(N);
1291       DAG.DeleteNode(N);
1292     } else {
1293       AddToWorklist(N);
1294     }
1295   } while (!Nodes.empty());
1296   return true;
1297 }
1298
1299 //===----------------------------------------------------------------------===//
1300 //  Main DAG Combiner implementation
1301 //===----------------------------------------------------------------------===//
1302
1303 void DAGCombiner::Run(CombineLevel AtLevel) {
1304   // set the instance variables, so that the various visit routines may use it.
1305   Level = AtLevel;
1306   LegalOperations = Level >= AfterLegalizeVectorOps;
1307   LegalTypes = Level >= AfterLegalizeTypes;
1308
1309   // Add all the dag nodes to the worklist.
1310   for (SDNode &Node : DAG.allnodes())
1311     AddToWorklist(&Node);
1312
1313   // Create a dummy node (which is not added to allnodes), that adds a reference
1314   // to the root node, preventing it from being deleted, and tracking any
1315   // changes of the root.
1316   HandleSDNode Dummy(DAG.getRoot());
1317
1318   // while the worklist isn't empty, find a node and
1319   // try and combine it.
1320   while (!WorklistMap.empty()) {
1321     SDNode *N;
1322     // The Worklist holds the SDNodes in order, but it may contain null entries.
1323     do {
1324       N = Worklist.pop_back_val();
1325     } while (!N);
1326
1327     bool GoodWorklistEntry = WorklistMap.erase(N);
1328     (void)GoodWorklistEntry;
1329     assert(GoodWorklistEntry &&
1330            "Found a worklist entry without a corresponding map entry!");
1331
1332     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1333     // N is deleted from the DAG, since they too may now be dead or may have a
1334     // reduced number of uses, allowing other xforms.
1335     if (recursivelyDeleteUnusedNodes(N))
1336       continue;
1337
1338     WorklistRemover DeadNodes(*this);
1339
1340     // If this combine is running after legalizing the DAG, re-legalize any
1341     // nodes pulled off the worklist.
1342     if (Level == AfterLegalizeDAG) {
1343       SmallSetVector<SDNode *, 16> UpdatedNodes;
1344       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1345
1346       for (SDNode *LN : UpdatedNodes) {
1347         AddToWorklist(LN);
1348         AddUsersToWorklist(LN);
1349       }
1350       if (!NIsValid)
1351         continue;
1352     }
1353
1354     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1355
1356     // Add any operands of the new node which have not yet been combined to the
1357     // worklist as well. Because the worklist uniques things already, this
1358     // won't repeatedly process the same operand.
1359     CombinedNodes.insert(N);
1360     for (const SDValue &ChildN : N->op_values())
1361       if (!CombinedNodes.count(ChildN.getNode()))
1362         AddToWorklist(ChildN.getNode());
1363
1364     SDValue RV = combine(N);
1365
1366     if (!RV.getNode())
1367       continue;
1368
1369     ++NodesCombined;
1370
1371     // If we get back the same node we passed in, rather than a new node or
1372     // zero, we know that the node must have defined multiple values and
1373     // CombineTo was used.  Since CombineTo takes care of the worklist
1374     // mechanics for us, we have no work to do in this case.
1375     if (RV.getNode() == N)
1376       continue;
1377
1378     assert(N->getOpcode() != ISD::DELETED_NODE &&
1379            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1380            "Node was deleted but visit returned new node!");
1381
1382     DEBUG(dbgs() << " ... into: ";
1383           RV.getNode()->dump(&DAG));
1384
1385     // Transfer debug value.
1386     DAG.TransferDbgValues(SDValue(N, 0), RV);
1387     if (N->getNumValues() == RV.getNode()->getNumValues())
1388       DAG.ReplaceAllUsesWith(N, RV.getNode());
1389     else {
1390       assert(N->getValueType(0) == RV.getValueType() &&
1391              N->getNumValues() == 1 && "Type mismatch");
1392       SDValue OpV = RV;
1393       DAG.ReplaceAllUsesWith(N, &OpV);
1394     }
1395
1396     // Push the new node and any users onto the worklist
1397     AddToWorklist(RV.getNode());
1398     AddUsersToWorklist(RV.getNode());
1399
1400     // Finally, if the node is now dead, remove it from the graph.  The node
1401     // may not be dead if the replacement process recursively simplified to
1402     // something else needing this node. This will also take care of adding any
1403     // operands which have lost a user to the worklist.
1404     recursivelyDeleteUnusedNodes(N);
1405   }
1406
1407   // If the root changed (e.g. it was a dead load, update the root).
1408   DAG.setRoot(Dummy.getValue());
1409   DAG.RemoveDeadNodes();
1410 }
1411
1412 SDValue DAGCombiner::visit(SDNode *N) {
1413   switch (N->getOpcode()) {
1414   default: break;
1415   case ISD::TokenFactor:        return visitTokenFactor(N);
1416   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1417   case ISD::ADD:                return visitADD(N);
1418   case ISD::SUB:                return visitSUB(N);
1419   case ISD::ADDC:               return visitADDC(N);
1420   case ISD::SUBC:               return visitSUBC(N);
1421   case ISD::ADDE:               return visitADDE(N);
1422   case ISD::SUBE:               return visitSUBE(N);
1423   case ISD::MUL:                return visitMUL(N);
1424   case ISD::SDIV:               return visitSDIV(N);
1425   case ISD::UDIV:               return visitUDIV(N);
1426   case ISD::SREM:
1427   case ISD::UREM:               return visitREM(N);
1428   case ISD::MULHU:              return visitMULHU(N);
1429   case ISD::MULHS:              return visitMULHS(N);
1430   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1431   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1432   case ISD::SMULO:              return visitSMULO(N);
1433   case ISD::UMULO:              return visitUMULO(N);
1434   case ISD::SMIN:
1435   case ISD::SMAX:
1436   case ISD::UMIN:
1437   case ISD::UMAX:               return visitIMINMAX(N);
1438   case ISD::AND:                return visitAND(N);
1439   case ISD::OR:                 return visitOR(N);
1440   case ISD::XOR:                return visitXOR(N);
1441   case ISD::SHL:                return visitSHL(N);
1442   case ISD::SRA:                return visitSRA(N);
1443   case ISD::SRL:                return visitSRL(N);
1444   case ISD::ROTR:
1445   case ISD::ROTL:               return visitRotate(N);
1446   case ISD::BSWAP:              return visitBSWAP(N);
1447   case ISD::CTLZ:               return visitCTLZ(N);
1448   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1449   case ISD::CTTZ:               return visitCTTZ(N);
1450   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1451   case ISD::CTPOP:              return visitCTPOP(N);
1452   case ISD::SELECT:             return visitSELECT(N);
1453   case ISD::VSELECT:            return visitVSELECT(N);
1454   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1455   case ISD::SETCC:              return visitSETCC(N);
1456   case ISD::SETCCE:             return visitSETCCE(N);
1457   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1458   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1459   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1460   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1461   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1462   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1463   case ISD::BITCAST:            return visitBITCAST(N);
1464   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1465   case ISD::FADD:               return visitFADD(N);
1466   case ISD::FSUB:               return visitFSUB(N);
1467   case ISD::FMUL:               return visitFMUL(N);
1468   case ISD::FMA:                return visitFMA(N);
1469   case ISD::FDIV:               return visitFDIV(N);
1470   case ISD::FREM:               return visitFREM(N);
1471   case ISD::FSQRT:              return visitFSQRT(N);
1472   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1473   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1474   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1475   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1476   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1477   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1478   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1479   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1480   case ISD::FNEG:               return visitFNEG(N);
1481   case ISD::FABS:               return visitFABS(N);
1482   case ISD::FFLOOR:             return visitFFLOOR(N);
1483   case ISD::FMINNUM:            return visitFMINNUM(N);
1484   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1485   case ISD::FCEIL:              return visitFCEIL(N);
1486   case ISD::FTRUNC:             return visitFTRUNC(N);
1487   case ISD::BRCOND:             return visitBRCOND(N);
1488   case ISD::BR_CC:              return visitBR_CC(N);
1489   case ISD::LOAD:               return visitLOAD(N);
1490   case ISD::STORE:              return visitSTORE(N);
1491   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1492   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1493   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1494   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1495   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1496   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1497   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1498   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1499   case ISD::MGATHER:            return visitMGATHER(N);
1500   case ISD::MLOAD:              return visitMLOAD(N);
1501   case ISD::MSCATTER:           return visitMSCATTER(N);
1502   case ISD::MSTORE:             return visitMSTORE(N);
1503   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1504   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1505   }
1506   return SDValue();
1507 }
1508
1509 SDValue DAGCombiner::combine(SDNode *N) {
1510   SDValue RV = visit(N);
1511
1512   // If nothing happened, try a target-specific DAG combine.
1513   if (!RV.getNode()) {
1514     assert(N->getOpcode() != ISD::DELETED_NODE &&
1515            "Node was deleted but visit returned NULL!");
1516
1517     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1518         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1519
1520       // Expose the DAG combiner to the target combiner impls.
1521       TargetLowering::DAGCombinerInfo
1522         DagCombineInfo(DAG, Level, false, this);
1523
1524       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1525     }
1526   }
1527
1528   // If nothing happened still, try promoting the operation.
1529   if (!RV.getNode()) {
1530     switch (N->getOpcode()) {
1531     default: break;
1532     case ISD::ADD:
1533     case ISD::SUB:
1534     case ISD::MUL:
1535     case ISD::AND:
1536     case ISD::OR:
1537     case ISD::XOR:
1538       RV = PromoteIntBinOp(SDValue(N, 0));
1539       break;
1540     case ISD::SHL:
1541     case ISD::SRA:
1542     case ISD::SRL:
1543       RV = PromoteIntShiftOp(SDValue(N, 0));
1544       break;
1545     case ISD::SIGN_EXTEND:
1546     case ISD::ZERO_EXTEND:
1547     case ISD::ANY_EXTEND:
1548       RV = PromoteExtend(SDValue(N, 0));
1549       break;
1550     case ISD::LOAD:
1551       if (PromoteLoad(SDValue(N, 0)))
1552         RV = SDValue(N, 0);
1553       break;
1554     }
1555   }
1556
1557   // If N is a commutative binary node, try commuting it to enable more
1558   // sdisel CSE.
1559   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1560       N->getNumValues() == 1) {
1561     SDValue N0 = N->getOperand(0);
1562     SDValue N1 = N->getOperand(1);
1563
1564     // Constant operands are canonicalized to RHS.
1565     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1566       SDValue Ops[] = {N1, N0};
1567       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1568                                             N->getFlags());
1569       if (CSENode)
1570         return SDValue(CSENode, 0);
1571     }
1572   }
1573
1574   return RV;
1575 }
1576
1577 /// Given a node, return its input chain if it has one, otherwise return a null
1578 /// sd operand.
1579 static SDValue getInputChainForNode(SDNode *N) {
1580   if (unsigned NumOps = N->getNumOperands()) {
1581     if (N->getOperand(0).getValueType() == MVT::Other)
1582       return N->getOperand(0);
1583     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1584       return N->getOperand(NumOps-1);
1585     for (unsigned i = 1; i < NumOps-1; ++i)
1586       if (N->getOperand(i).getValueType() == MVT::Other)
1587         return N->getOperand(i);
1588   }
1589   return SDValue();
1590 }
1591
1592 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1593   // If N has two operands, where one has an input chain equal to the other,
1594   // the 'other' chain is redundant.
1595   if (N->getNumOperands() == 2) {
1596     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1597       return N->getOperand(0);
1598     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1599       return N->getOperand(1);
1600   }
1601
1602   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1603   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1604   SmallPtrSet<SDNode*, 16> SeenOps;
1605   bool Changed = false;             // If we should replace this token factor.
1606
1607   // Start out with this token factor.
1608   TFs.push_back(N);
1609
1610   // Iterate through token factors.  The TFs grows when new token factors are
1611   // encountered.
1612   for (unsigned i = 0; i < TFs.size(); ++i) {
1613     SDNode *TF = TFs[i];
1614
1615     // Check each of the operands.
1616     for (const SDValue &Op : TF->op_values()) {
1617
1618       switch (Op.getOpcode()) {
1619       case ISD::EntryToken:
1620         // Entry tokens don't need to be added to the list. They are
1621         // redundant.
1622         Changed = true;
1623         break;
1624
1625       case ISD::TokenFactor:
1626         if (Op.hasOneUse() &&
1627             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1628           // Queue up for processing.
1629           TFs.push_back(Op.getNode());
1630           // Clean up in case the token factor is removed.
1631           AddToWorklist(Op.getNode());
1632           Changed = true;
1633           break;
1634         }
1635         // Fall thru
1636
1637       default:
1638         // Only add if it isn't already in the list.
1639         if (SeenOps.insert(Op.getNode()).second)
1640           Ops.push_back(Op);
1641         else
1642           Changed = true;
1643         break;
1644       }
1645     }
1646   }
1647
1648   SDValue Result;
1649
1650   // If we've changed things around then replace token factor.
1651   if (Changed) {
1652     if (Ops.empty()) {
1653       // The entry token is the only possible outcome.
1654       Result = DAG.getEntryNode();
1655     } else {
1656       // New and improved token factor.
1657       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1658     }
1659
1660     // Add users to worklist if AA is enabled, since it may introduce
1661     // a lot of new chained token factors while removing memory deps.
1662     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1663       : DAG.getSubtarget().useAA();
1664     return CombineTo(N, Result, UseAA /*add to worklist*/);
1665   }
1666
1667   return Result;
1668 }
1669
1670 /// MERGE_VALUES can always be eliminated.
1671 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1672   WorklistRemover DeadNodes(*this);
1673   // Replacing results may cause a different MERGE_VALUES to suddenly
1674   // be CSE'd with N, and carry its uses with it. Iterate until no
1675   // uses remain, to ensure that the node can be safely deleted.
1676   // First add the users of this node to the work list so that they
1677   // can be tried again once they have new operands.
1678   AddUsersToWorklist(N);
1679   do {
1680     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1681       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1682   } while (!N->use_empty());
1683   deleteAndRecombine(N);
1684   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1685 }
1686
1687 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1688 /// ContantSDNode pointer else nullptr.
1689 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1690   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1691   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1692 }
1693
1694 SDValue DAGCombiner::visitADD(SDNode *N) {
1695   SDValue N0 = N->getOperand(0);
1696   SDValue N1 = N->getOperand(1);
1697   EVT VT = N0.getValueType();
1698
1699   // fold vector ops
1700   if (VT.isVector()) {
1701     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1702       return FoldedVOp;
1703
1704     // fold (add x, 0) -> x, vector edition
1705     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1706       return N0;
1707     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1708       return N1;
1709   }
1710
1711   // fold (add x, undef) -> undef
1712   if (N0.getOpcode() == ISD::UNDEF)
1713     return N0;
1714   if (N1.getOpcode() == ISD::UNDEF)
1715     return N1;
1716   // fold (add c1, c2) -> c1+c2
1717   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1718   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1719   if (N0C && N1C)
1720     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1721   // canonicalize constant to RHS
1722   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1723      !isConstantIntBuildVectorOrConstantInt(N1))
1724     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1725   // fold (add x, 0) -> x
1726   if (isNullConstant(N1))
1727     return N0;
1728   // fold (add Sym, c) -> Sym+c
1729   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1730     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1731         GA->getOpcode() == ISD::GlobalAddress)
1732       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1733                                   GA->getOffset() +
1734                                     (uint64_t)N1C->getSExtValue());
1735   // fold ((c1-A)+c2) -> (c1+c2)-A
1736   if (N1C && N0.getOpcode() == ISD::SUB)
1737     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1738       SDLoc DL(N);
1739       return DAG.getNode(ISD::SUB, DL, VT,
1740                          DAG.getConstant(N1C->getAPIntValue()+
1741                                          N0C->getAPIntValue(), DL, VT),
1742                          N0.getOperand(1));
1743     }
1744   // reassociate add
1745   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1746     return RADD;
1747   // fold ((0-A) + B) -> B-A
1748   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1749     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1750   // fold (A + (0-B)) -> A-B
1751   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1752     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1753   // fold (A+(B-A)) -> B
1754   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1755     return N1.getOperand(0);
1756   // fold ((B-A)+A) -> B
1757   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1758     return N0.getOperand(0);
1759   // fold (A+(B-(A+C))) to (B-C)
1760   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1761       N0 == N1.getOperand(1).getOperand(0))
1762     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1763                        N1.getOperand(1).getOperand(1));
1764   // fold (A+(B-(C+A))) to (B-C)
1765   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1766       N0 == N1.getOperand(1).getOperand(1))
1767     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1768                        N1.getOperand(1).getOperand(0));
1769   // fold (A+((B-A)+or-C)) to (B+or-C)
1770   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1771       N1.getOperand(0).getOpcode() == ISD::SUB &&
1772       N0 == N1.getOperand(0).getOperand(1))
1773     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1774                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1775
1776   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1777   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1778     SDValue N00 = N0.getOperand(0);
1779     SDValue N01 = N0.getOperand(1);
1780     SDValue N10 = N1.getOperand(0);
1781     SDValue N11 = N1.getOperand(1);
1782
1783     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1784       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1785                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1786                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1787   }
1788
1789   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1790     return SDValue(N, 0);
1791
1792   // fold (a+b) -> (a|b) iff a and b share no bits.
1793   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1794       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1795     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1796
1797   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1798   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1799       isNullConstant(N1.getOperand(0).getOperand(0)))
1800     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1801                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1802                                    N1.getOperand(0).getOperand(1),
1803                                    N1.getOperand(1)));
1804   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1805       isNullConstant(N0.getOperand(0).getOperand(0)))
1806     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1807                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1808                                    N0.getOperand(0).getOperand(1),
1809                                    N0.getOperand(1)));
1810
1811   if (N1.getOpcode() == ISD::AND) {
1812     SDValue AndOp0 = N1.getOperand(0);
1813     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1814     unsigned DestBits = VT.getScalarType().getSizeInBits();
1815
1816     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1817     // and similar xforms where the inner op is either ~0 or 0.
1818     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1819       SDLoc DL(N);
1820       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1821     }
1822   }
1823
1824   // add (sext i1), X -> sub X, (zext i1)
1825   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1826       N0.getOperand(0).getValueType() == MVT::i1 &&
1827       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1828     SDLoc DL(N);
1829     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1830     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1831   }
1832
1833   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1834   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1835     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1836     if (TN->getVT() == MVT::i1) {
1837       SDLoc DL(N);
1838       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1839                                  DAG.getConstant(1, DL, VT));
1840       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1841     }
1842   }
1843
1844   return SDValue();
1845 }
1846
1847 SDValue DAGCombiner::visitADDC(SDNode *N) {
1848   SDValue N0 = N->getOperand(0);
1849   SDValue N1 = N->getOperand(1);
1850   EVT VT = N0.getValueType();
1851
1852   // If the flag result is dead, turn this into an ADD.
1853   if (!N->hasAnyUseOfValue(1))
1854     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1855                      DAG.getNode(ISD::CARRY_FALSE,
1856                                  SDLoc(N), MVT::Glue));
1857
1858   // canonicalize constant to RHS.
1859   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1860   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1861   if (N0C && !N1C)
1862     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1863
1864   // fold (addc x, 0) -> x + no carry out
1865   if (isNullConstant(N1))
1866     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1867                                         SDLoc(N), MVT::Glue));
1868
1869   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1870   APInt LHSZero, LHSOne;
1871   APInt RHSZero, RHSOne;
1872   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1873
1874   if (LHSZero.getBoolValue()) {
1875     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1876
1877     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1878     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1879     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1880       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1881                        DAG.getNode(ISD::CARRY_FALSE,
1882                                    SDLoc(N), MVT::Glue));
1883   }
1884
1885   return SDValue();
1886 }
1887
1888 SDValue DAGCombiner::visitADDE(SDNode *N) {
1889   SDValue N0 = N->getOperand(0);
1890   SDValue N1 = N->getOperand(1);
1891   SDValue CarryIn = N->getOperand(2);
1892
1893   // canonicalize constant to RHS
1894   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1895   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1896   if (N0C && !N1C)
1897     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1898                        N1, N0, CarryIn);
1899
1900   // fold (adde x, y, false) -> (addc x, y)
1901   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1902     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1903
1904   return SDValue();
1905 }
1906
1907 // Since it may not be valid to emit a fold to zero for vector initializers
1908 // check if we can before folding.
1909 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1910                              SelectionDAG &DAG,
1911                              bool LegalOperations, bool LegalTypes) {
1912   if (!VT.isVector())
1913     return DAG.getConstant(0, DL, VT);
1914   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1915     return DAG.getConstant(0, DL, VT);
1916   return SDValue();
1917 }
1918
1919 SDValue DAGCombiner::visitSUB(SDNode *N) {
1920   SDValue N0 = N->getOperand(0);
1921   SDValue N1 = N->getOperand(1);
1922   EVT VT = N0.getValueType();
1923
1924   // fold vector ops
1925   if (VT.isVector()) {
1926     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1927       return FoldedVOp;
1928
1929     // fold (sub x, 0) -> x, vector edition
1930     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1931       return N0;
1932   }
1933
1934   // fold (sub x, x) -> 0
1935   // FIXME: Refactor this and xor and other similar operations together.
1936   if (N0 == N1)
1937     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1938   // fold (sub c1, c2) -> c1-c2
1939   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1940   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1941   if (N0C && N1C)
1942     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1943   // fold (sub x, c) -> (add x, -c)
1944   if (N1C) {
1945     SDLoc DL(N);
1946     return DAG.getNode(ISD::ADD, DL, VT, N0,
1947                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1948   }
1949   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1950   if (isAllOnesConstant(N0))
1951     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1952   // fold A-(A-B) -> B
1953   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1954     return N1.getOperand(1);
1955   // fold (A+B)-A -> B
1956   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1957     return N0.getOperand(1);
1958   // fold (A+B)-B -> A
1959   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1960     return N0.getOperand(0);
1961   // fold C2-(A+C1) -> (C2-C1)-A
1962   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1963     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1964   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1965     SDLoc DL(N);
1966     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1967                                    DL, VT);
1968     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1969                        N1.getOperand(0));
1970   }
1971   // fold ((A+(B+or-C))-B) -> A+or-C
1972   if (N0.getOpcode() == ISD::ADD &&
1973       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1974        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1975       N0.getOperand(1).getOperand(0) == N1)
1976     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1977                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1978   // fold ((A+(C+B))-B) -> A+C
1979   if (N0.getOpcode() == ISD::ADD &&
1980       N0.getOperand(1).getOpcode() == ISD::ADD &&
1981       N0.getOperand(1).getOperand(1) == N1)
1982     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1983                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1984   // fold ((A-(B-C))-C) -> A-B
1985   if (N0.getOpcode() == ISD::SUB &&
1986       N0.getOperand(1).getOpcode() == ISD::SUB &&
1987       N0.getOperand(1).getOperand(1) == N1)
1988     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1990
1991   // If either operand of a sub is undef, the result is undef
1992   if (N0.getOpcode() == ISD::UNDEF)
1993     return N0;
1994   if (N1.getOpcode() == ISD::UNDEF)
1995     return N1;
1996
1997   // If the relocation model supports it, consider symbol offsets.
1998   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1999     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2000       // fold (sub Sym, c) -> Sym-c
2001       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2002         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2003                                     GA->getOffset() -
2004                                       (uint64_t)N1C->getSExtValue());
2005       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2006       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2007         if (GA->getGlobal() == GB->getGlobal())
2008           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2009                                  SDLoc(N), VT);
2010     }
2011
2012   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2013   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2014     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2015     if (TN->getVT() == MVT::i1) {
2016       SDLoc DL(N);
2017       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2018                                  DAG.getConstant(1, DL, VT));
2019       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2020     }
2021   }
2022
2023   return SDValue();
2024 }
2025
2026 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2027   SDValue N0 = N->getOperand(0);
2028   SDValue N1 = N->getOperand(1);
2029   EVT VT = N0.getValueType();
2030   SDLoc DL(N);
2031
2032   // If the flag result is dead, turn this into an SUB.
2033   if (!N->hasAnyUseOfValue(1))
2034     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2035                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2036
2037   // fold (subc x, x) -> 0 + no borrow
2038   if (N0 == N1)
2039     return CombineTo(N, DAG.getConstant(0, DL, VT),
2040                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2041
2042   // fold (subc x, 0) -> x + no borrow
2043   if (isNullConstant(N1))
2044     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2045
2046   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2047   if (isAllOnesConstant(N0))
2048     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2049                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2050
2051   return SDValue();
2052 }
2053
2054 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2055   SDValue N0 = N->getOperand(0);
2056   SDValue N1 = N->getOperand(1);
2057   SDValue CarryIn = N->getOperand(2);
2058
2059   // fold (sube x, y, false) -> (subc x, y)
2060   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2061     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2062
2063   return SDValue();
2064 }
2065
2066 SDValue DAGCombiner::visitMUL(SDNode *N) {
2067   SDValue N0 = N->getOperand(0);
2068   SDValue N1 = N->getOperand(1);
2069   EVT VT = N0.getValueType();
2070
2071   // fold (mul x, undef) -> 0
2072   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2073     return DAG.getConstant(0, SDLoc(N), VT);
2074
2075   bool N0IsConst = false;
2076   bool N1IsConst = false;
2077   bool N1IsOpaqueConst = false;
2078   bool N0IsOpaqueConst = false;
2079   APInt ConstValue0, ConstValue1;
2080   // fold vector ops
2081   if (VT.isVector()) {
2082     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2083       return FoldedVOp;
2084
2085     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2086     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2087   } else {
2088     N0IsConst = isa<ConstantSDNode>(N0);
2089     if (N0IsConst) {
2090       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2091       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2092     }
2093     N1IsConst = isa<ConstantSDNode>(N1);
2094     if (N1IsConst) {
2095       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2096       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2097     }
2098   }
2099
2100   // fold (mul c1, c2) -> c1*c2
2101   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2102     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2103                                       N0.getNode(), N1.getNode());
2104
2105   // canonicalize constant to RHS (vector doesn't have to splat)
2106   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2107      !isConstantIntBuildVectorOrConstantInt(N1))
2108     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2109   // fold (mul x, 0) -> 0
2110   if (N1IsConst && ConstValue1 == 0)
2111     return N1;
2112   // We require a splat of the entire scalar bit width for non-contiguous
2113   // bit patterns.
2114   bool IsFullSplat =
2115     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2116   // fold (mul x, 1) -> x
2117   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2118     return N0;
2119   // fold (mul x, -1) -> 0-x
2120   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2121     SDLoc DL(N);
2122     return DAG.getNode(ISD::SUB, DL, VT,
2123                        DAG.getConstant(0, DL, VT), N0);
2124   }
2125   // fold (mul x, (1 << c)) -> x << c
2126   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2127       IsFullSplat) {
2128     SDLoc DL(N);
2129     return DAG.getNode(ISD::SHL, DL, VT, N0,
2130                        DAG.getConstant(ConstValue1.logBase2(), DL,
2131                                        getShiftAmountTy(N0.getValueType())));
2132   }
2133   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2134   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2135       IsFullSplat) {
2136     unsigned Log2Val = (-ConstValue1).logBase2();
2137     SDLoc DL(N);
2138     // FIXME: If the input is something that is easily negated (e.g. a
2139     // single-use add), we should put the negate there.
2140     return DAG.getNode(ISD::SUB, DL, VT,
2141                        DAG.getConstant(0, DL, VT),
2142                        DAG.getNode(ISD::SHL, DL, VT, N0,
2143                             DAG.getConstant(Log2Val, DL,
2144                                       getShiftAmountTy(N0.getValueType()))));
2145   }
2146
2147   APInt Val;
2148   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2149   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2150       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2151                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2152     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2153                              N1, N0.getOperand(1));
2154     AddToWorklist(C3.getNode());
2155     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2156                        N0.getOperand(0), C3);
2157   }
2158
2159   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2160   // use.
2161   {
2162     SDValue Sh(nullptr,0), Y(nullptr,0);
2163     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2164     if (N0.getOpcode() == ISD::SHL &&
2165         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2166                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2167         N0.getNode()->hasOneUse()) {
2168       Sh = N0; Y = N1;
2169     } else if (N1.getOpcode() == ISD::SHL &&
2170                isa<ConstantSDNode>(N1.getOperand(1)) &&
2171                N1.getNode()->hasOneUse()) {
2172       Sh = N1; Y = N0;
2173     }
2174
2175     if (Sh.getNode()) {
2176       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2177                                 Sh.getOperand(0), Y);
2178       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2179                          Mul, Sh.getOperand(1));
2180     }
2181   }
2182
2183   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2184   if (isConstantIntBuildVectorOrConstantInt(N1) &&
2185       N0.getOpcode() == ISD::ADD &&
2186       isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2187       isMulAddWithConstProfitable(N, N0, N1))
2188       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2189                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2190                                      N0.getOperand(0), N1),
2191                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2192                                      N0.getOperand(1), N1));
2193
2194   // reassociate mul
2195   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2196     return RMUL;
2197
2198   return SDValue();
2199 }
2200
2201 /// Return true if divmod libcall is available.
2202 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2203                                      const TargetLowering &TLI) {
2204   RTLIB::Libcall LC;
2205   switch (Node->getSimpleValueType(0).SimpleTy) {
2206   default: return false; // No libcall for vector types.
2207   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2208   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2209   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2210   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2211   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2212   }
2213
2214   return TLI.getLibcallName(LC) != nullptr;
2215 }
2216
2217 /// Issue divrem if both quotient and remainder are needed.
2218 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2219   if (Node->use_empty())
2220     return SDValue(); // This is a dead node, leave it alone.
2221
2222   EVT VT = Node->getValueType(0);
2223   if (!TLI.isTypeLegal(VT))
2224     return SDValue();
2225
2226   unsigned Opcode = Node->getOpcode();
2227   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2228
2229   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2230   // If DIVREM is going to get expanded into a libcall,
2231   // but there is no libcall available, then don't combine.
2232   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2233       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2234     return SDValue();
2235
2236   // If div is legal, it's better to do the normal expansion
2237   unsigned OtherOpcode = 0;
2238   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2239     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2240     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2241       return SDValue();
2242   } else {
2243     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2244     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2245       return SDValue();
2246   }
2247
2248   SDValue Op0 = Node->getOperand(0);
2249   SDValue Op1 = Node->getOperand(1);
2250   SDValue combined;
2251   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2252          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2253     SDNode *User = *UI;
2254     if (User == Node || User->use_empty())
2255       continue;
2256     // Convert the other matching node(s), too;
2257     // otherwise, the DIVREM may get target-legalized into something
2258     // target-specific that we won't be able to recognize.
2259     unsigned UserOpc = User->getOpcode();
2260     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2261         User->getOperand(0) == Op0 &&
2262         User->getOperand(1) == Op1) {
2263       if (!combined) {
2264         if (UserOpc == OtherOpcode) {
2265           SDVTList VTs = DAG.getVTList(VT, VT);
2266           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2267         } else if (UserOpc == DivRemOpc) {
2268           combined = SDValue(User, 0);
2269         } else {
2270           assert(UserOpc == Opcode);
2271           continue;
2272         }
2273       }
2274       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2275         CombineTo(User, combined);
2276       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2277         CombineTo(User, combined.getValue(1));
2278     }
2279   }
2280   return combined;
2281 }
2282
2283 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2284   SDValue N0 = N->getOperand(0);
2285   SDValue N1 = N->getOperand(1);
2286   EVT VT = N->getValueType(0);
2287
2288   // fold vector ops
2289   if (VT.isVector())
2290     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2291       return FoldedVOp;
2292
2293   SDLoc DL(N);
2294
2295   // fold (sdiv c1, c2) -> c1/c2
2296   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2297   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2298   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2299     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2300   // fold (sdiv X, 1) -> X
2301   if (N1C && N1C->isOne())
2302     return N0;
2303   // fold (sdiv X, -1) -> 0-X
2304   if (N1C && N1C->isAllOnesValue())
2305     return DAG.getNode(ISD::SUB, DL, VT,
2306                        DAG.getConstant(0, DL, VT), N0);
2307
2308   // If we know the sign bits of both operands are zero, strength reduce to a
2309   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2310   if (!VT.isVector()) {
2311     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2312       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2313   }
2314
2315   // fold (sdiv X, pow2) -> simple ops after legalize
2316   // FIXME: We check for the exact bit here because the generic lowering gives
2317   // better results in that case. The target-specific lowering should learn how
2318   // to handle exact sdivs efficiently.
2319   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2320       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2321       (N1C->getAPIntValue().isPowerOf2() ||
2322        (-N1C->getAPIntValue()).isPowerOf2())) {
2323     // Target-specific implementation of sdiv x, pow2.
2324     if (SDValue Res = BuildSDIVPow2(N))
2325       return Res;
2326
2327     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2328
2329     // Splat the sign bit into the register
2330     SDValue SGN =
2331         DAG.getNode(ISD::SRA, DL, VT, N0,
2332                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2333                                     getShiftAmountTy(N0.getValueType())));
2334     AddToWorklist(SGN.getNode());
2335
2336     // Add (N0 < 0) ? abs2 - 1 : 0;
2337     SDValue SRL =
2338         DAG.getNode(ISD::SRL, DL, VT, SGN,
2339                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2340                                     getShiftAmountTy(SGN.getValueType())));
2341     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2342     AddToWorklist(SRL.getNode());
2343     AddToWorklist(ADD.getNode());    // Divide by pow2
2344     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2345                   DAG.getConstant(lg2, DL,
2346                                   getShiftAmountTy(ADD.getValueType())));
2347
2348     // If we're dividing by a positive value, we're done.  Otherwise, we must
2349     // negate the result.
2350     if (N1C->getAPIntValue().isNonNegative())
2351       return SRA;
2352
2353     AddToWorklist(SRA.getNode());
2354     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2355   }
2356
2357   // If integer divide is expensive and we satisfy the requirements, emit an
2358   // alternate sequence.  Targets may check function attributes for size/speed
2359   // trade-offs.
2360   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2361   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2362     if (SDValue Op = BuildSDIV(N))
2363       return Op;
2364
2365   // sdiv, srem -> sdivrem
2366   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2367   // Otherwise, we break the simplification logic in visitREM().
2368   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2369     if (SDValue DivRem = useDivRem(N))
2370         return DivRem;
2371
2372   // undef / X -> 0
2373   if (N0.getOpcode() == ISD::UNDEF)
2374     return DAG.getConstant(0, DL, VT);
2375   // X / undef -> undef
2376   if (N1.getOpcode() == ISD::UNDEF)
2377     return N1;
2378
2379   return SDValue();
2380 }
2381
2382 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2383   SDValue N0 = N->getOperand(0);
2384   SDValue N1 = N->getOperand(1);
2385   EVT VT = N->getValueType(0);
2386
2387   // fold vector ops
2388   if (VT.isVector())
2389     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2390       return FoldedVOp;
2391
2392   SDLoc DL(N);
2393
2394   // fold (udiv c1, c2) -> c1/c2
2395   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2396   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2397   if (N0C && N1C)
2398     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2399                                                     N0C, N1C))
2400       return Folded;
2401   // fold (udiv x, (1 << c)) -> x >>u c
2402   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2403     return DAG.getNode(ISD::SRL, DL, VT, N0,
2404                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2405                                        getShiftAmountTy(N0.getValueType())));
2406
2407   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2408   if (N1.getOpcode() == ISD::SHL) {
2409     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2410       if (SHC->getAPIntValue().isPowerOf2()) {
2411         EVT ADDVT = N1.getOperand(1).getValueType();
2412         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2413                                   N1.getOperand(1),
2414                                   DAG.getConstant(SHC->getAPIntValue()
2415                                                                   .logBase2(),
2416                                                   DL, ADDVT));
2417         AddToWorklist(Add.getNode());
2418         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2419       }
2420     }
2421   }
2422
2423   // fold (udiv x, c) -> alternate
2424   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2425   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2426     if (SDValue Op = BuildUDIV(N))
2427       return Op;
2428
2429   // sdiv, srem -> sdivrem
2430   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2431   // Otherwise, we break the simplification logic in visitREM().
2432   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2433     if (SDValue DivRem = useDivRem(N))
2434         return DivRem;
2435
2436   // undef / X -> 0
2437   if (N0.getOpcode() == ISD::UNDEF)
2438     return DAG.getConstant(0, DL, VT);
2439   // X / undef -> undef
2440   if (N1.getOpcode() == ISD::UNDEF)
2441     return N1;
2442
2443   return SDValue();
2444 }
2445
2446 // handles ISD::SREM and ISD::UREM
2447 SDValue DAGCombiner::visitREM(SDNode *N) {
2448   unsigned Opcode = N->getOpcode();
2449   SDValue N0 = N->getOperand(0);
2450   SDValue N1 = N->getOperand(1);
2451   EVT VT = N->getValueType(0);
2452   bool isSigned = (Opcode == ISD::SREM);
2453   SDLoc DL(N);
2454
2455   // fold (rem c1, c2) -> c1%c2
2456   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2457   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2458   if (N0C && N1C)
2459     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2460       return Folded;
2461
2462   if (isSigned) {
2463     // If we know the sign bits of both operands are zero, strength reduce to a
2464     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2465     if (!VT.isVector()) {
2466       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2467         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2468     }
2469   } else {
2470     // fold (urem x, pow2) -> (and x, pow2-1)
2471     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2472         N1C->getAPIntValue().isPowerOf2()) {
2473       return DAG.getNode(ISD::AND, DL, VT, N0,
2474                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2475     }
2476     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2477     if (N1.getOpcode() == ISD::SHL) {
2478       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2479         if (SHC->getAPIntValue().isPowerOf2()) {
2480           SDValue Add =
2481             DAG.getNode(ISD::ADD, DL, VT, N1,
2482                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2483                                  VT));
2484           AddToWorklist(Add.getNode());
2485           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2486         }
2487       }
2488     }
2489   }
2490
2491   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2492
2493   // If X/C can be simplified by the division-by-constant logic, lower
2494   // X%C to the equivalent of X-X/C*C.
2495   // To avoid mangling nodes, this simplification requires that the combine()
2496   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2497   // against this by skipping the simplification if isIntDivCheap().  When
2498   // div is not cheap, combine will not return a DIVREM.  Regardless,
2499   // checking cheapness here makes sense since the simplification results in
2500   // fatter code.
2501   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2502     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2503     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2504     AddToWorklist(Div.getNode());
2505     SDValue OptimizedDiv = combine(Div.getNode());
2506     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2507       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2508              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2509       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2510       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2511       AddToWorklist(Mul.getNode());
2512       return Sub;
2513     }
2514   }
2515
2516   // sdiv, srem -> sdivrem
2517   if (SDValue DivRem = useDivRem(N))
2518     return DivRem.getValue(1);
2519
2520   // undef % X -> 0
2521   if (N0.getOpcode() == ISD::UNDEF)
2522     return DAG.getConstant(0, DL, VT);
2523   // X % undef -> undef
2524   if (N1.getOpcode() == ISD::UNDEF)
2525     return N1;
2526
2527   return SDValue();
2528 }
2529
2530 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2531   SDValue N0 = N->getOperand(0);
2532   SDValue N1 = N->getOperand(1);
2533   EVT VT = N->getValueType(0);
2534   SDLoc DL(N);
2535
2536   // fold (mulhs x, 0) -> 0
2537   if (isNullConstant(N1))
2538     return N1;
2539   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2540   if (isOneConstant(N1)) {
2541     SDLoc DL(N);
2542     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2543                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2544                                        DL,
2545                                        getShiftAmountTy(N0.getValueType())));
2546   }
2547   // fold (mulhs x, undef) -> 0
2548   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2549     return DAG.getConstant(0, SDLoc(N), VT);
2550
2551   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2552   // plus a shift.
2553   if (VT.isSimple() && !VT.isVector()) {
2554     MVT Simple = VT.getSimpleVT();
2555     unsigned SimpleSize = Simple.getSizeInBits();
2556     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2557     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2558       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2559       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2560       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2561       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2562             DAG.getConstant(SimpleSize, DL,
2563                             getShiftAmountTy(N1.getValueType())));
2564       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2565     }
2566   }
2567
2568   return SDValue();
2569 }
2570
2571 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2572   SDValue N0 = N->getOperand(0);
2573   SDValue N1 = N->getOperand(1);
2574   EVT VT = N->getValueType(0);
2575   SDLoc DL(N);
2576
2577   // fold (mulhu x, 0) -> 0
2578   if (isNullConstant(N1))
2579     return N1;
2580   // fold (mulhu x, 1) -> 0
2581   if (isOneConstant(N1))
2582     return DAG.getConstant(0, DL, N0.getValueType());
2583   // fold (mulhu x, undef) -> 0
2584   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2585     return DAG.getConstant(0, DL, VT);
2586
2587   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2588   // plus a shift.
2589   if (VT.isSimple() && !VT.isVector()) {
2590     MVT Simple = VT.getSimpleVT();
2591     unsigned SimpleSize = Simple.getSizeInBits();
2592     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2593     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2594       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2595       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2596       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2597       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2598             DAG.getConstant(SimpleSize, DL,
2599                             getShiftAmountTy(N1.getValueType())));
2600       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2601     }
2602   }
2603
2604   return SDValue();
2605 }
2606
2607 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2608 /// give the opcodes for the two computations that are being performed. Return
2609 /// true if a simplification was made.
2610 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2611                                                 unsigned HiOp) {
2612   // If the high half is not needed, just compute the low half.
2613   bool HiExists = N->hasAnyUseOfValue(1);
2614   if (!HiExists &&
2615       (!LegalOperations ||
2616        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2617     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2618     return CombineTo(N, Res, Res);
2619   }
2620
2621   // If the low half is not needed, just compute the high half.
2622   bool LoExists = N->hasAnyUseOfValue(0);
2623   if (!LoExists &&
2624       (!LegalOperations ||
2625        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2626     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2627     return CombineTo(N, Res, Res);
2628   }
2629
2630   // If both halves are used, return as it is.
2631   if (LoExists && HiExists)
2632     return SDValue();
2633
2634   // If the two computed results can be simplified separately, separate them.
2635   if (LoExists) {
2636     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2637     AddToWorklist(Lo.getNode());
2638     SDValue LoOpt = combine(Lo.getNode());
2639     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2640         (!LegalOperations ||
2641          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2642       return CombineTo(N, LoOpt, LoOpt);
2643   }
2644
2645   if (HiExists) {
2646     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2647     AddToWorklist(Hi.getNode());
2648     SDValue HiOpt = combine(Hi.getNode());
2649     if (HiOpt.getNode() && HiOpt != Hi &&
2650         (!LegalOperations ||
2651          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2652       return CombineTo(N, HiOpt, HiOpt);
2653   }
2654
2655   return SDValue();
2656 }
2657
2658 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2659   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2660     return Res;
2661
2662   EVT VT = N->getValueType(0);
2663   SDLoc DL(N);
2664
2665   // If the type is twice as wide is legal, transform the mulhu to a wider
2666   // multiply plus a shift.
2667   if (VT.isSimple() && !VT.isVector()) {
2668     MVT Simple = VT.getSimpleVT();
2669     unsigned SimpleSize = Simple.getSizeInBits();
2670     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2671     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2672       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2673       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2674       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2675       // Compute the high part as N1.
2676       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2677             DAG.getConstant(SimpleSize, DL,
2678                             getShiftAmountTy(Lo.getValueType())));
2679       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2680       // Compute the low part as N0.
2681       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2682       return CombineTo(N, Lo, Hi);
2683     }
2684   }
2685
2686   return SDValue();
2687 }
2688
2689 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2690   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2691     return Res;
2692
2693   EVT VT = N->getValueType(0);
2694   SDLoc DL(N);
2695
2696   // If the type is twice as wide is legal, transform the mulhu to a wider
2697   // multiply plus a shift.
2698   if (VT.isSimple() && !VT.isVector()) {
2699     MVT Simple = VT.getSimpleVT();
2700     unsigned SimpleSize = Simple.getSizeInBits();
2701     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2702     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2703       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2704       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2705       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2706       // Compute the high part as N1.
2707       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2708             DAG.getConstant(SimpleSize, DL,
2709                             getShiftAmountTy(Lo.getValueType())));
2710       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2711       // Compute the low part as N0.
2712       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2713       return CombineTo(N, Lo, Hi);
2714     }
2715   }
2716
2717   return SDValue();
2718 }
2719
2720 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2721   // (smulo x, 2) -> (saddo x, x)
2722   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2723     if (C2->getAPIntValue() == 2)
2724       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2725                          N->getOperand(0), N->getOperand(0));
2726
2727   return SDValue();
2728 }
2729
2730 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2731   // (umulo x, 2) -> (uaddo x, x)
2732   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2733     if (C2->getAPIntValue() == 2)
2734       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2735                          N->getOperand(0), N->getOperand(0));
2736
2737   return SDValue();
2738 }
2739
2740 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2741   SDValue N0 = N->getOperand(0);
2742   SDValue N1 = N->getOperand(1);
2743   EVT VT = N0.getValueType();
2744
2745   // fold vector ops
2746   if (VT.isVector())
2747     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2748       return FoldedVOp;
2749
2750   // fold (add c1, c2) -> c1+c2
2751   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2752   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2753   if (N0C && N1C)
2754     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2755
2756   // canonicalize constant to RHS
2757   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2758      !isConstantIntBuildVectorOrConstantInt(N1))
2759     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2760
2761   return SDValue();
2762 }
2763
2764 /// If this is a binary operator with two operands of the same opcode, try to
2765 /// simplify it.
2766 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2767   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2768   EVT VT = N0.getValueType();
2769   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2770
2771   // Bail early if none of these transforms apply.
2772   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2773
2774   // For each of OP in AND/OR/XOR:
2775   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2776   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2777   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2778   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2779   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2780   //
2781   // do not sink logical op inside of a vector extend, since it may combine
2782   // into a vsetcc.
2783   EVT Op0VT = N0.getOperand(0).getValueType();
2784   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2785        N0.getOpcode() == ISD::SIGN_EXTEND ||
2786        N0.getOpcode() == ISD::BSWAP ||
2787        // Avoid infinite looping with PromoteIntBinOp.
2788        (N0.getOpcode() == ISD::ANY_EXTEND &&
2789         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2790        (N0.getOpcode() == ISD::TRUNCATE &&
2791         (!TLI.isZExtFree(VT, Op0VT) ||
2792          !TLI.isTruncateFree(Op0VT, VT)) &&
2793         TLI.isTypeLegal(Op0VT))) &&
2794       !VT.isVector() &&
2795       Op0VT == N1.getOperand(0).getValueType() &&
2796       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2797     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2798                                  N0.getOperand(0).getValueType(),
2799                                  N0.getOperand(0), N1.getOperand(0));
2800     AddToWorklist(ORNode.getNode());
2801     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2802   }
2803
2804   // For each of OP in SHL/SRL/SRA/AND...
2805   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2806   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2807   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2808   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2809        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2810       N0.getOperand(1) == N1.getOperand(1)) {
2811     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2812                                  N0.getOperand(0).getValueType(),
2813                                  N0.getOperand(0), N1.getOperand(0));
2814     AddToWorklist(ORNode.getNode());
2815     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2816                        ORNode, N0.getOperand(1));
2817   }
2818
2819   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2820   // Only perform this optimization after type legalization and before
2821   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2822   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2823   // we don't want to undo this promotion.
2824   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2825   // on scalars.
2826   if ((N0.getOpcode() == ISD::BITCAST ||
2827        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2828       Level == AfterLegalizeTypes) {
2829     SDValue In0 = N0.getOperand(0);
2830     SDValue In1 = N1.getOperand(0);
2831     EVT In0Ty = In0.getValueType();
2832     EVT In1Ty = In1.getValueType();
2833     SDLoc DL(N);
2834     // If both incoming values are integers, and the original types are the
2835     // same.
2836     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2837       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2838       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2839       AddToWorklist(Op.getNode());
2840       return BC;
2841     }
2842   }
2843
2844   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2845   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2846   // If both shuffles use the same mask, and both shuffle within a single
2847   // vector, then it is worthwhile to move the swizzle after the operation.
2848   // The type-legalizer generates this pattern when loading illegal
2849   // vector types from memory. In many cases this allows additional shuffle
2850   // optimizations.
2851   // There are other cases where moving the shuffle after the xor/and/or
2852   // is profitable even if shuffles don't perform a swizzle.
2853   // If both shuffles use the same mask, and both shuffles have the same first
2854   // or second operand, then it might still be profitable to move the shuffle
2855   // after the xor/and/or operation.
2856   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2857     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2858     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2859
2860     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2861            "Inputs to shuffles are not the same type");
2862
2863     // Check that both shuffles use the same mask. The masks are known to be of
2864     // the same length because the result vector type is the same.
2865     // Check also that shuffles have only one use to avoid introducing extra
2866     // instructions.
2867     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2868         SVN0->getMask().equals(SVN1->getMask())) {
2869       SDValue ShOp = N0->getOperand(1);
2870
2871       // Don't try to fold this node if it requires introducing a
2872       // build vector of all zeros that might be illegal at this stage.
2873       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2874         if (!LegalTypes)
2875           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2876         else
2877           ShOp = SDValue();
2878       }
2879
2880       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2881       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2882       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2883       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2884         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2885                                       N0->getOperand(0), N1->getOperand(0));
2886         AddToWorklist(NewNode.getNode());
2887         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2888                                     &SVN0->getMask()[0]);
2889       }
2890
2891       // Don't try to fold this node if it requires introducing a
2892       // build vector of all zeros that might be illegal at this stage.
2893       ShOp = N0->getOperand(0);
2894       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2895         if (!LegalTypes)
2896           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2897         else
2898           ShOp = SDValue();
2899       }
2900
2901       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2902       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2903       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2904       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2905         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2906                                       N0->getOperand(1), N1->getOperand(1));
2907         AddToWorklist(NewNode.getNode());
2908         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2909                                     &SVN0->getMask()[0]);
2910       }
2911     }
2912   }
2913
2914   return SDValue();
2915 }
2916
2917 /// This contains all DAGCombine rules which reduce two values combined by
2918 /// an And operation to a single value. This makes them reusable in the context
2919 /// of visitSELECT(). Rules involving constants are not included as
2920 /// visitSELECT() already handles those cases.
2921 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2922                                   SDNode *LocReference) {
2923   EVT VT = N1.getValueType();
2924
2925   // fold (and x, undef) -> 0
2926   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2927     return DAG.getConstant(0, SDLoc(LocReference), VT);
2928   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2929   SDValue LL, LR, RL, RR, CC0, CC1;
2930   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2931     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2932     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2933
2934     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2935         LL.getValueType().isInteger()) {
2936       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2937       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2938         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2939                                      LR.getValueType(), LL, RL);
2940         AddToWorklist(ORNode.getNode());
2941         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2942       }
2943       if (isAllOnesConstant(LR)) {
2944         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2945         if (Op1 == ISD::SETEQ) {
2946           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2947                                         LR.getValueType(), LL, RL);
2948           AddToWorklist(ANDNode.getNode());
2949           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2950         }
2951         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2952         if (Op1 == ISD::SETGT) {
2953           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2954                                        LR.getValueType(), LL, RL);
2955           AddToWorklist(ORNode.getNode());
2956           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2957         }
2958       }
2959     }
2960     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2961     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2962         Op0 == Op1 && LL.getValueType().isInteger() &&
2963       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2964                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2965       SDLoc DL(N0);
2966       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2967                                     LL, DAG.getConstant(1, DL,
2968                                                         LL.getValueType()));
2969       AddToWorklist(ADDNode.getNode());
2970       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2971                           DAG.getConstant(2, DL, LL.getValueType()),
2972                           ISD::SETUGE);
2973     }
2974     // canonicalize equivalent to ll == rl
2975     if (LL == RR && LR == RL) {
2976       Op1 = ISD::getSetCCSwappedOperands(Op1);
2977       std::swap(RL, RR);
2978     }
2979     if (LL == RL && LR == RR) {
2980       bool isInteger = LL.getValueType().isInteger();
2981       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2982       if (Result != ISD::SETCC_INVALID &&
2983           (!LegalOperations ||
2984            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2985             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2986         EVT CCVT = getSetCCResultType(LL.getValueType());
2987         if (N0.getValueType() == CCVT ||
2988             (!LegalOperations && N0.getValueType() == MVT::i1))
2989           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2990                               LL, LR, Result);
2991       }
2992     }
2993   }
2994
2995   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2996       VT.getSizeInBits() <= 64) {
2997     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2998       APInt ADDC = ADDI->getAPIntValue();
2999       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3000         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3001         // immediate for an add, but it is legal if its top c2 bits are set,
3002         // transform the ADD so the immediate doesn't need to be materialized
3003         // in a register.
3004         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3005           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3006                                              SRLI->getZExtValue());
3007           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3008             ADDC |= Mask;
3009             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3010               SDLoc DL(N0);
3011               SDValue NewAdd =
3012                 DAG.getNode(ISD::ADD, DL, VT,
3013                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3014               CombineTo(N0.getNode(), NewAdd);
3015               // Return N so it doesn't get rechecked!
3016               return SDValue(LocReference, 0);
3017             }
3018           }
3019         }
3020       }
3021     }
3022   }
3023
3024   return SDValue();
3025 }
3026
3027 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3028                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3029                                    bool &NarrowLoad) {
3030   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3031
3032   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3033     return false;
3034
3035   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036   LoadedVT = LoadN->getMemoryVT();
3037
3038   if (ExtVT == LoadedVT &&
3039       (!LegalOperations ||
3040        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3041     // ZEXTLOAD will match without needing to change the size of the value being
3042     // loaded.
3043     NarrowLoad = false;
3044     return true;
3045   }
3046
3047   // Do not change the width of a volatile load.
3048   if (LoadN->isVolatile())
3049     return false;
3050
3051   // Do not generate loads of non-round integer types since these can
3052   // be expensive (and would be wrong if the type is not byte sized).
3053   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3054     return false;
3055
3056   if (LegalOperations &&
3057       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3058     return false;
3059
3060   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3061     return false;
3062
3063   NarrowLoad = true;
3064   return true;
3065 }
3066
3067 SDValue DAGCombiner::visitAND(SDNode *N) {
3068   SDValue N0 = N->getOperand(0);
3069   SDValue N1 = N->getOperand(1);
3070   EVT VT = N1.getValueType();
3071
3072   // fold vector ops
3073   if (VT.isVector()) {
3074     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3075       return FoldedVOp;
3076
3077     // fold (and x, 0) -> 0, vector edition
3078     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3079       // do not return N0, because undef node may exist in N0
3080       return DAG.getConstant(
3081           APInt::getNullValue(
3082               N0.getValueType().getScalarType().getSizeInBits()),
3083           SDLoc(N), N0.getValueType());
3084     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3085       // do not return N1, because undef node may exist in N1
3086       return DAG.getConstant(
3087           APInt::getNullValue(
3088               N1.getValueType().getScalarType().getSizeInBits()),
3089           SDLoc(N), N1.getValueType());
3090
3091     // fold (and x, -1) -> x, vector edition
3092     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3093       return N1;
3094     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3095       return N0;
3096   }
3097
3098   // fold (and c1, c2) -> c1&c2
3099   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3100   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3101
3102   // XXX-disabled: (and x, 0) should not be folded.
3103   // (and (and x, 0), y) shouldn't either.
3104   if (!N0C && N1C->isNullValue()) {
3105     return SDValue();
3106   }
3107   if (!N0C) {
3108     if (N0.getOpcode() == ISD::AND) {
3109       auto* N01 = N0.getOperand(1).getNode();
3110       auto* N01C = dyn_cast<ConstantSDNode>(N01);
3111       if (N01C && N01C->isNullValue()) {
3112         return SDValue();
3113       }
3114     }
3115   }
3116
3117   if (N0C && N1C && !N1C->isOpaque())
3118     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3119   // canonicalize constant to RHS
3120   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3121      !isConstantIntBuildVectorOrConstantInt(N1))
3122     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3123   // fold (and x, -1) -> x
3124   if (isAllOnesConstant(N1))
3125     return N0;
3126   // if (and x, c) is known to be zero, return 0
3127   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3128   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3129                                    APInt::getAllOnesValue(BitWidth)))
3130     return DAG.getConstant(0, SDLoc(N), VT);
3131   // reassociate and
3132   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3133     return RAND;
3134   // fold (and (or x, C), D) -> D if (C & D) == D
3135   if (N1C && N0.getOpcode() == ISD::OR)
3136     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3137       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3138         return N1;
3139   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3140   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3141     SDValue N0Op0 = N0.getOperand(0);
3142     APInt Mask = ~N1C->getAPIntValue();
3143     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3144     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3145       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3146                                  N0.getValueType(), N0Op0);
3147
3148       // Replace uses of the AND with uses of the Zero extend node.
3149       CombineTo(N, Zext);
3150
3151       // We actually want to replace all uses of the any_extend with the
3152       // zero_extend, to avoid duplicating things.  This will later cause this
3153       // AND to be folded.
3154       CombineTo(N0.getNode(), Zext);
3155       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3156     }
3157   }
3158   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3159   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3160   // already be zero by virtue of the width of the base type of the load.
3161   //
3162   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3163   // more cases.
3164   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3165        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3166       N0.getOpcode() == ISD::LOAD) {
3167     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3168                                          N0 : N0.getOperand(0) );
3169
3170     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3171     // This can be a pure constant or a vector splat, in which case we treat the
3172     // vector as a scalar and use the splat value.
3173     APInt Constant = APInt::getNullValue(1);
3174     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3175       Constant = C->getAPIntValue();
3176     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3177       APInt SplatValue, SplatUndef;
3178       unsigned SplatBitSize;
3179       bool HasAnyUndefs;
3180       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3181                                              SplatBitSize, HasAnyUndefs);
3182       if (IsSplat) {
3183         // Undef bits can contribute to a possible optimisation if set, so
3184         // set them.
3185         SplatValue |= SplatUndef;
3186
3187         // The splat value may be something like "0x00FFFFFF", which means 0 for
3188         // the first vector value and FF for the rest, repeating. We need a mask
3189         // that will apply equally to all members of the vector, so AND all the
3190         // lanes of the constant together.
3191         EVT VT = Vector->getValueType(0);
3192         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3193
3194         // If the splat value has been compressed to a bitlength lower
3195         // than the size of the vector lane, we need to re-expand it to
3196         // the lane size.
3197         if (BitWidth > SplatBitSize)
3198           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3199                SplatBitSize < BitWidth;
3200                SplatBitSize = SplatBitSize * 2)
3201             SplatValue |= SplatValue.shl(SplatBitSize);
3202
3203         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3204         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3205         if (SplatBitSize % BitWidth == 0) {
3206           Constant = APInt::getAllOnesValue(BitWidth);
3207           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3208             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3209         }
3210       }
3211     }
3212
3213     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3214     // actually legal and isn't going to get expanded, else this is a false
3215     // optimisation.
3216     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3217                                                     Load->getValueType(0),
3218                                                     Load->getMemoryVT());
3219
3220     // Resize the constant to the same size as the original memory access before
3221     // extension. If it is still the AllOnesValue then this AND is completely
3222     // unneeded.
3223     Constant =
3224       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3225
3226     bool B;
3227     switch (Load->getExtensionType()) {
3228     default: B = false; break;
3229     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3230     case ISD::ZEXTLOAD:
3231     case ISD::NON_EXTLOAD: B = true; break;
3232     }
3233
3234     if (B && Constant.isAllOnesValue()) {
3235       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3236       // preserve semantics once we get rid of the AND.
3237       SDValue NewLoad(Load, 0);
3238       if (Load->getExtensionType() == ISD::EXTLOAD) {
3239         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3240                               Load->getValueType(0), SDLoc(Load),
3241                               Load->getChain(), Load->getBasePtr(),
3242                               Load->getOffset(), Load->getMemoryVT(),
3243                               Load->getMemOperand());
3244         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3245         if (Load->getNumValues() == 3) {
3246           // PRE/POST_INC loads have 3 values.
3247           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3248                            NewLoad.getValue(2) };
3249           CombineTo(Load, To, 3, true);
3250         } else {
3251           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3252         }
3253       }
3254
3255       // Fold the AND away, taking care not to fold to the old load node if we
3256       // replaced it.
3257       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3258
3259       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3260     }
3261   }
3262
3263   // fold (and (load x), 255) -> (zextload x, i8)
3264   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3265   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3266   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3267               (N0.getOpcode() == ISD::ANY_EXTEND &&
3268                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3269     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3270     LoadSDNode *LN0 = HasAnyExt
3271       ? cast<LoadSDNode>(N0.getOperand(0))
3272       : cast<LoadSDNode>(N0);
3273     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3274         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3275       auto NarrowLoad = false;
3276       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3277       EVT ExtVT, LoadedVT;
3278       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3279                            NarrowLoad)) {
3280         if (!NarrowLoad) {
3281           SDValue NewLoad =
3282             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3283                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3284                            LN0->getMemOperand());
3285           AddToWorklist(N);
3286           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3287           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3288         } else {
3289           EVT PtrType = LN0->getOperand(1).getValueType();
3290
3291           unsigned Alignment = LN0->getAlignment();
3292           SDValue NewPtr = LN0->getBasePtr();
3293
3294           // For big endian targets, we need to add an offset to the pointer
3295           // to load the correct bytes.  For little endian systems, we merely
3296           // need to read fewer bytes from the same pointer.
3297           if (DAG.getDataLayout().isBigEndian()) {
3298             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3299             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3300             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3301             SDLoc DL(LN0);
3302             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3303                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3304             Alignment = MinAlign(Alignment, PtrOff);
3305           }
3306
3307           AddToWorklist(NewPtr.getNode());
3308
3309           SDValue Load =
3310             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3311                            LN0->getChain(), NewPtr,
3312                            LN0->getPointerInfo(),
3313                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3314                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3315           AddToWorklist(N);
3316           CombineTo(LN0, Load, Load.getValue(1));
3317           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3318         }
3319       }
3320     }
3321   }
3322
3323   if (SDValue Combined = visitANDLike(N0, N1, N))
3324     return Combined;
3325
3326   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3327   if (N0.getOpcode() == N1.getOpcode())
3328     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3329       return Tmp;
3330
3331   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3332   // fold (and (sra)) -> (and (srl)) when possible.
3333   if (!VT.isVector() &&
3334       SimplifyDemandedBits(SDValue(N, 0)))
3335     return SDValue(N, 0);
3336
3337   // fold (zext_inreg (extload x)) -> (zextload x)
3338   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3339     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3340     EVT MemVT = LN0->getMemoryVT();
3341     // If we zero all the possible extended bits, then we can turn this into
3342     // a zextload if we are running before legalize or the operation is legal.
3343     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3344     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3345                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3346         ((!LegalOperations && !LN0->isVolatile()) ||
3347          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3348       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3349                                        LN0->getChain(), LN0->getBasePtr(),
3350                                        MemVT, LN0->getMemOperand());
3351       AddToWorklist(N);
3352       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3353       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3354     }
3355   }
3356   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3357   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3358       N0.hasOneUse()) {
3359     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3360     EVT MemVT = LN0->getMemoryVT();
3361     // If we zero all the possible extended bits, then we can turn this into
3362     // a zextload if we are running before legalize or the operation is legal.
3363     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3364     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3365                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3366         ((!LegalOperations && !LN0->isVolatile()) ||
3367          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3368       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3369                                        LN0->getChain(), LN0->getBasePtr(),
3370                                        MemVT, LN0->getMemOperand());
3371       AddToWorklist(N);
3372       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3373       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3374     }
3375   }
3376   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3377   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3378     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3379                                        N0.getOperand(1), false);
3380     if (BSwap.getNode())
3381       return BSwap;
3382   }
3383
3384   return SDValue();
3385 }
3386
3387 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3388 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3389                                         bool DemandHighBits) {
3390   if (!LegalOperations)
3391     return SDValue();
3392
3393   EVT VT = N->getValueType(0);
3394   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3395     return SDValue();
3396   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3397     return SDValue();
3398
3399   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3400   bool LookPassAnd0 = false;
3401   bool LookPassAnd1 = false;
3402   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3403       std::swap(N0, N1);
3404   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3405       std::swap(N0, N1);
3406   if (N0.getOpcode() == ISD::AND) {
3407     if (!N0.getNode()->hasOneUse())
3408       return SDValue();
3409     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3410     if (!N01C || N01C->getZExtValue() != 0xFF00)
3411       return SDValue();
3412     N0 = N0.getOperand(0);
3413     LookPassAnd0 = true;
3414   }
3415
3416   if (N1.getOpcode() == ISD::AND) {
3417     if (!N1.getNode()->hasOneUse())
3418       return SDValue();
3419     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3420     if (!N11C || N11C->getZExtValue() != 0xFF)
3421       return SDValue();
3422     N1 = N1.getOperand(0);
3423     LookPassAnd1 = true;
3424   }
3425
3426   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3427     std::swap(N0, N1);
3428   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3429     return SDValue();
3430   if (!N0.getNode()->hasOneUse() ||
3431       !N1.getNode()->hasOneUse())
3432     return SDValue();
3433
3434   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3435   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3436   if (!N01C || !N11C)
3437     return SDValue();
3438   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3439     return SDValue();
3440
3441   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3442   SDValue N00 = N0->getOperand(0);
3443   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3444     if (!N00.getNode()->hasOneUse())
3445       return SDValue();
3446     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3447     if (!N001C || N001C->getZExtValue() != 0xFF)
3448       return SDValue();
3449     N00 = N00.getOperand(0);
3450     LookPassAnd0 = true;
3451   }
3452
3453   SDValue N10 = N1->getOperand(0);
3454   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3455     if (!N10.getNode()->hasOneUse())
3456       return SDValue();
3457     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3458     if (!N101C || N101C->getZExtValue() != 0xFF00)
3459       return SDValue();
3460     N10 = N10.getOperand(0);
3461     LookPassAnd1 = true;
3462   }
3463
3464   if (N00 != N10)
3465     return SDValue();
3466
3467   // Make sure everything beyond the low halfword gets set to zero since the SRL
3468   // 16 will clear the top bits.
3469   unsigned OpSizeInBits = VT.getSizeInBits();
3470   if (DemandHighBits && OpSizeInBits > 16) {
3471     // If the left-shift isn't masked out then the only way this is a bswap is
3472     // if all bits beyond the low 8 are 0. In that case the entire pattern
3473     // reduces to a left shift anyway: leave it for other parts of the combiner.
3474     if (!LookPassAnd0)
3475       return SDValue();
3476
3477     // However, if the right shift isn't masked out then it might be because
3478     // it's not needed. See if we can spot that too.
3479     if (!LookPassAnd1 &&
3480         !DAG.MaskedValueIsZero(
3481             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3482       return SDValue();
3483   }
3484
3485   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3486   if (OpSizeInBits > 16) {
3487     SDLoc DL(N);
3488     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3489                       DAG.getConstant(OpSizeInBits - 16, DL,
3490                                       getShiftAmountTy(VT)));
3491   }
3492   return Res;
3493 }
3494
3495 /// Return true if the specified node is an element that makes up a 32-bit
3496 /// packed halfword byteswap.
3497 /// ((x & 0x000000ff) << 8) |
3498 /// ((x & 0x0000ff00) >> 8) |
3499 /// ((x & 0x00ff0000) << 8) |
3500 /// ((x & 0xff000000) >> 8)
3501 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3502   if (!N.getNode()->hasOneUse())
3503     return false;
3504
3505   unsigned Opc = N.getOpcode();
3506   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3507     return false;
3508
3509   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3510   if (!N1C)
3511     return false;
3512
3513   unsigned Num;
3514   switch (N1C->getZExtValue()) {
3515   default:
3516     return false;
3517   case 0xFF:       Num = 0; break;
3518   case 0xFF00:     Num = 1; break;
3519   case 0xFF0000:   Num = 2; break;
3520   case 0xFF000000: Num = 3; break;
3521   }
3522
3523   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3524   SDValue N0 = N.getOperand(0);
3525   if (Opc == ISD::AND) {
3526     if (Num == 0 || Num == 2) {
3527       // (x >> 8) & 0xff
3528       // (x >> 8) & 0xff0000
3529       if (N0.getOpcode() != ISD::SRL)
3530         return false;
3531       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3532       if (!C || C->getZExtValue() != 8)
3533         return false;
3534     } else {
3535       // (x << 8) & 0xff00
3536       // (x << 8) & 0xff000000
3537       if (N0.getOpcode() != ISD::SHL)
3538         return false;
3539       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3540       if (!C || C->getZExtValue() != 8)
3541         return false;
3542     }
3543   } else if (Opc == ISD::SHL) {
3544     // (x & 0xff) << 8
3545     // (x & 0xff0000) << 8
3546     if (Num != 0 && Num != 2)
3547       return false;
3548     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3549     if (!C || C->getZExtValue() != 8)
3550       return false;
3551   } else { // Opc == ISD::SRL
3552     // (x & 0xff00) >> 8
3553     // (x & 0xff000000) >> 8
3554     if (Num != 1 && Num != 3)
3555       return false;
3556     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3557     if (!C || C->getZExtValue() != 8)
3558       return false;
3559   }
3560
3561   if (Parts[Num])
3562     return false;
3563
3564   Parts[Num] = N0.getOperand(0).getNode();
3565   return true;
3566 }
3567
3568 /// Match a 32-bit packed halfword bswap. That is
3569 /// ((x & 0x000000ff) << 8) |
3570 /// ((x & 0x0000ff00) >> 8) |
3571 /// ((x & 0x00ff0000) << 8) |
3572 /// ((x & 0xff000000) >> 8)
3573 /// => (rotl (bswap x), 16)
3574 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3575   if (!LegalOperations)
3576     return SDValue();
3577
3578   EVT VT = N->getValueType(0);
3579   if (VT != MVT::i32)
3580     return SDValue();
3581   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3582     return SDValue();
3583
3584   // Look for either
3585   // (or (or (and), (and)), (or (and), (and)))
3586   // (or (or (or (and), (and)), (and)), (and))
3587   if (N0.getOpcode() != ISD::OR)
3588     return SDValue();
3589   SDValue N00 = N0.getOperand(0);
3590   SDValue N01 = N0.getOperand(1);
3591   SDNode *Parts[4] = {};
3592
3593   if (N1.getOpcode() == ISD::OR &&
3594       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3595     // (or (or (and), (and)), (or (and), (and)))
3596     SDValue N000 = N00.getOperand(0);
3597     if (!isBSwapHWordElement(N000, Parts))
3598       return SDValue();
3599
3600     SDValue N001 = N00.getOperand(1);
3601     if (!isBSwapHWordElement(N001, Parts))
3602       return SDValue();
3603     SDValue N010 = N01.getOperand(0);
3604     if (!isBSwapHWordElement(N010, Parts))
3605       return SDValue();
3606     SDValue N011 = N01.getOperand(1);
3607     if (!isBSwapHWordElement(N011, Parts))
3608       return SDValue();
3609   } else {
3610     // (or (or (or (and), (and)), (and)), (and))
3611     if (!isBSwapHWordElement(N1, Parts))
3612       return SDValue();
3613     if (!isBSwapHWordElement(N01, Parts))
3614       return SDValue();
3615     if (N00.getOpcode() != ISD::OR)
3616       return SDValue();
3617     SDValue N000 = N00.getOperand(0);
3618     if (!isBSwapHWordElement(N000, Parts))
3619       return SDValue();
3620     SDValue N001 = N00.getOperand(1);
3621     if (!isBSwapHWordElement(N001, Parts))
3622       return SDValue();
3623   }
3624
3625   // Make sure the parts are all coming from the same node.
3626   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3627     return SDValue();
3628
3629   SDLoc DL(N);
3630   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3631                               SDValue(Parts[0], 0));
3632
3633   // Result of the bswap should be rotated by 16. If it's not legal, then
3634   // do  (x << 16) | (x >> 16).
3635   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3636   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3637     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3638   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3639     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3640   return DAG.getNode(ISD::OR, DL, VT,
3641                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3642                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3643 }
3644
3645 /// This contains all DAGCombine rules which reduce two values combined by
3646 /// an Or operation to a single value \see visitANDLike().
3647 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3648   EVT VT = N1.getValueType();
3649   // fold (or x, undef) -> -1
3650   if (!LegalOperations &&
3651       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3652     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3653     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3654                            SDLoc(LocReference), VT);
3655   }
3656   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3657   SDValue LL, LR, RL, RR, CC0, CC1;
3658   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3659     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3660     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3661
3662     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3663       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3664       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3665       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3666         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3667                                      LR.getValueType(), LL, RL);
3668         AddToWorklist(ORNode.getNode());
3669         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3670       }
3671       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3672       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3673       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3674         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3675                                       LR.getValueType(), LL, RL);
3676         AddToWorklist(ANDNode.getNode());
3677         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3678       }
3679     }
3680     // canonicalize equivalent to ll == rl
3681     if (LL == RR && LR == RL) {
3682       Op1 = ISD::getSetCCSwappedOperands(Op1);
3683       std::swap(RL, RR);
3684     }
3685     if (LL == RL && LR == RR) {
3686       bool isInteger = LL.getValueType().isInteger();
3687       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3688       if (Result != ISD::SETCC_INVALID &&
3689           (!LegalOperations ||
3690            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3691             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3692         EVT CCVT = getSetCCResultType(LL.getValueType());
3693         if (N0.getValueType() == CCVT ||
3694             (!LegalOperations && N0.getValueType() == MVT::i1))
3695           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3696                               LL, LR, Result);
3697       }
3698     }
3699   }
3700
3701   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3702   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3703       // Don't increase # computations.
3704       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3705     // We can only do this xform if we know that bits from X that are set in C2
3706     // but not in C1 are already zero.  Likewise for Y.
3707     if (const ConstantSDNode *N0O1C =
3708         getAsNonOpaqueConstant(N0.getOperand(1))) {
3709       if (const ConstantSDNode *N1O1C =
3710           getAsNonOpaqueConstant(N1.getOperand(1))) {
3711         // We can only do this xform if we know that bits from X that are set in
3712         // C2 but not in C1 are already zero.  Likewise for Y.
3713         const APInt &LHSMask = N0O1C->getAPIntValue();
3714         const APInt &RHSMask = N1O1C->getAPIntValue();
3715
3716         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3717             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3718           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3719                                   N0.getOperand(0), N1.getOperand(0));
3720           SDLoc DL(LocReference);
3721           return DAG.getNode(ISD::AND, DL, VT, X,
3722                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3723         }
3724       }
3725     }
3726   }
3727
3728   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3729   if (N0.getOpcode() == ISD::AND &&
3730       N1.getOpcode() == ISD::AND &&
3731       N0.getOperand(0) == N1.getOperand(0) &&
3732       // Don't increase # computations.
3733       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3734     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3735                             N0.getOperand(1), N1.getOperand(1));
3736     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3737   }
3738
3739   return SDValue();
3740 }
3741
3742 SDValue DAGCombiner::visitOR(SDNode *N) {
3743   SDValue N0 = N->getOperand(0);
3744   SDValue N1 = N->getOperand(1);
3745   EVT VT = N1.getValueType();
3746
3747   // fold vector ops
3748   if (VT.isVector()) {
3749     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3750       return FoldedVOp;
3751
3752     // fold (or x, 0) -> x, vector edition
3753     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3754       return N1;
3755     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3756       return N0;
3757
3758     // fold (or x, -1) -> -1, vector edition
3759     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3760       // do not return N0, because undef node may exist in N0
3761       return DAG.getConstant(
3762           APInt::getAllOnesValue(
3763               N0.getValueType().getScalarType().getSizeInBits()),
3764           SDLoc(N), N0.getValueType());
3765     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3766       // do not return N1, because undef node may exist in N1
3767       return DAG.getConstant(
3768           APInt::getAllOnesValue(
3769               N1.getValueType().getScalarType().getSizeInBits()),
3770           SDLoc(N), N1.getValueType());
3771
3772     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3773     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3774     // Do this only if the resulting shuffle is legal.
3775     if (isa<ShuffleVectorSDNode>(N0) &&
3776         isa<ShuffleVectorSDNode>(N1) &&
3777         // Avoid folding a node with illegal type.
3778         TLI.isTypeLegal(VT) &&
3779         N0->getOperand(1) == N1->getOperand(1) &&
3780         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3781       bool CanFold = true;
3782       unsigned NumElts = VT.getVectorNumElements();
3783       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3784       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3785       // We construct two shuffle masks:
3786       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3787       // and N1 as the second operand.
3788       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3789       // and N0 as the second operand.
3790       // We do this because OR is commutable and therefore there might be
3791       // two ways to fold this node into a shuffle.
3792       SmallVector<int,4> Mask1;
3793       SmallVector<int,4> Mask2;
3794
3795       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3796         int M0 = SV0->getMaskElt(i);
3797         int M1 = SV1->getMaskElt(i);
3798
3799         // Both shuffle indexes are undef. Propagate Undef.
3800         if (M0 < 0 && M1 < 0) {
3801           Mask1.push_back(M0);
3802           Mask2.push_back(M0);
3803           continue;
3804         }
3805
3806         if (M0 < 0 || M1 < 0 ||
3807             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3808             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3809           CanFold = false;
3810           break;
3811         }
3812
3813         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3814         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3815       }
3816
3817       if (CanFold) {
3818         // Fold this sequence only if the resulting shuffle is 'legal'.
3819         if (TLI.isShuffleMaskLegal(Mask1, VT))
3820           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3821                                       N1->getOperand(0), &Mask1[0]);
3822         if (TLI.isShuffleMaskLegal(Mask2, VT))
3823           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3824                                       N0->getOperand(0), &Mask2[0]);
3825       }
3826     }
3827   }
3828
3829   // fold (or c1, c2) -> c1|c2
3830   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3831   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3832   if (N0C && N1C && !N1C->isOpaque())
3833     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3834   // canonicalize constant to RHS
3835   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3836      !isConstantIntBuildVectorOrConstantInt(N1))
3837     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3838   // fold (or x, 0) -> x
3839   if (isNullConstant(N1))
3840     return N0;
3841   // fold (or x, -1) -> -1
3842   if (isAllOnesConstant(N1))
3843     return N1;
3844   // fold (or x, c) -> c iff (x & ~c) == 0
3845   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3846     return N1;
3847
3848   if (SDValue Combined = visitORLike(N0, N1, N))
3849     return Combined;
3850
3851   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3852   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3853     return BSwap;
3854   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3855     return BSwap;
3856
3857   // reassociate or
3858   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3859     return ROR;
3860   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3861   // iff (c1 & c2) == 0.
3862   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3863              isa<ConstantSDNode>(N0.getOperand(1))) {
3864     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3865     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3866       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3867                                                    N1C, C1))
3868         return DAG.getNode(
3869             ISD::AND, SDLoc(N), VT,
3870             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3871       return SDValue();
3872     }
3873   }
3874   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3875   if (N0.getOpcode() == N1.getOpcode())
3876     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3877       return Tmp;
3878
3879   // See if this is some rotate idiom.
3880   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3881     return SDValue(Rot, 0);
3882
3883   // Simplify the operands using demanded-bits information.
3884   if (!VT.isVector() &&
3885       SimplifyDemandedBits(SDValue(N, 0)))
3886     return SDValue(N, 0);
3887
3888   return SDValue();
3889 }
3890
3891 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3892 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3893   if (Op.getOpcode() == ISD::AND) {
3894     if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3895       Mask = Op.getOperand(1);
3896       Op = Op.getOperand(0);
3897     } else {
3898       return false;
3899     }
3900   }
3901
3902   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3903     Shift = Op;
3904     return true;
3905   }
3906
3907   return false;
3908 }
3909
3910 // Return true if we can prove that, whenever Neg and Pos are both in the
3911 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3912 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3913 //
3914 //     (or (shift1 X, Neg), (shift2 X, Pos))
3915 //
3916 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3917 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3918 // to consider shift amounts with defined behavior.
3919 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3920   // If EltSize is a power of 2 then:
3921   //
3922   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3923   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3924   //
3925   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3926   // for the stronger condition:
3927   //
3928   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3929   //
3930   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3931   // we can just replace Neg with Neg' for the rest of the function.
3932   //
3933   // In other cases we check for the even stronger condition:
3934   //
3935   //     Neg == EltSize - Pos                                    [B]
3936   //
3937   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3938   // behavior if Pos == 0 (and consequently Neg == EltSize).
3939   //
3940   // We could actually use [A] whenever EltSize is a power of 2, but the
3941   // only extra cases that it would match are those uninteresting ones
3942   // where Neg and Pos are never in range at the same time.  E.g. for
3943   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3944   // as well as (sub 32, Pos), but:
3945   //
3946   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3947   //
3948   // always invokes undefined behavior for 32-bit X.
3949   //
3950   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3951   unsigned MaskLoBits = 0;
3952   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3953     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3954       if (NegC->getAPIntValue() == EltSize - 1) {
3955         Neg = Neg.getOperand(0);
3956         MaskLoBits = Log2_64(EltSize);
3957       }
3958     }
3959   }
3960
3961   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3962   if (Neg.getOpcode() != ISD::SUB)
3963     return false;
3964   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3965   if (!NegC)
3966     return false;
3967   SDValue NegOp1 = Neg.getOperand(1);
3968
3969   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3970   // Pos'.  The truncation is redundant for the purpose of the equality.
3971   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3972     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3973       if (PosC->getAPIntValue() == EltSize - 1)
3974         Pos = Pos.getOperand(0);
3975
3976   // The condition we need is now:
3977   //
3978   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3979   //
3980   // If NegOp1 == Pos then we need:
3981   //
3982   //              EltSize & Mask == NegC & Mask
3983   //
3984   // (because "x & Mask" is a truncation and distributes through subtraction).
3985   APInt Width;
3986   if (Pos == NegOp1)
3987     Width = NegC->getAPIntValue();
3988
3989   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3990   // Then the condition we want to prove becomes:
3991   //
3992   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3993   //
3994   // which, again because "x & Mask" is a truncation, becomes:
3995   //
3996   //                NegC & Mask == (EltSize - PosC) & Mask
3997   //             EltSize & Mask == (NegC + PosC) & Mask
3998   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3999     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4000       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4001     else
4002       return false;
4003   } else
4004     return false;
4005
4006   // Now we just need to check that EltSize & Mask == Width & Mask.
4007   if (MaskLoBits)
4008     // EltSize & Mask is 0 since Mask is EltSize - 1.
4009     return Width.getLoBits(MaskLoBits) == 0;
4010   return Width == EltSize;
4011 }
4012
4013 // A subroutine of MatchRotate used once we have found an OR of two opposite
4014 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4015 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4016 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4017 // Neg with outer conversions stripped away.
4018 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4019                                        SDValue Neg, SDValue InnerPos,
4020                                        SDValue InnerNeg, unsigned PosOpcode,
4021                                        unsigned NegOpcode, SDLoc DL) {
4022   // fold (or (shl x, (*ext y)),
4023   //          (srl x, (*ext (sub 32, y)))) ->
4024   //   (rotl x, y) or (rotr x, (sub 32, y))
4025   //
4026   // fold (or (shl x, (*ext (sub 32, y))),
4027   //          (srl x, (*ext y))) ->
4028   //   (rotr x, y) or (rotl x, (sub 32, y))
4029   EVT VT = Shifted.getValueType();
4030   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4031     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4032     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4033                        HasPos ? Pos : Neg).getNode();
4034   }
4035
4036   return nullptr;
4037 }
4038
4039 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4040 // idioms for rotate, and if the target supports rotation instructions, generate
4041 // a rot[lr].
4042 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
4043   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4044   EVT VT = LHS.getValueType();
4045   if (!TLI.isTypeLegal(VT)) return nullptr;
4046
4047   // The target must have at least one rotate flavor.
4048   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4049   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4050   if (!HasROTL && !HasROTR) return nullptr;
4051
4052   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4053   SDValue LHSShift;   // The shift.
4054   SDValue LHSMask;    // AND value if any.
4055   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4056     return nullptr; // Not part of a rotate.
4057
4058   SDValue RHSShift;   // The shift.
4059   SDValue RHSMask;    // AND value if any.
4060   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4061     return nullptr; // Not part of a rotate.
4062
4063   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4064     return nullptr;   // Not shifting the same value.
4065
4066   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4067     return nullptr;   // Shifts must disagree.
4068
4069   // Canonicalize shl to left side in a shl/srl pair.
4070   if (RHSShift.getOpcode() == ISD::SHL) {
4071     std::swap(LHS, RHS);
4072     std::swap(LHSShift, RHSShift);
4073     std::swap(LHSMask, RHSMask);
4074   }
4075
4076   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4077   SDValue LHSShiftArg = LHSShift.getOperand(0);
4078   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4079   SDValue RHSShiftArg = RHSShift.getOperand(0);
4080   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4081
4082   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4083   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4084   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4085     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4086     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4087     if ((LShVal + RShVal) != EltSizeInBits)
4088       return nullptr;
4089
4090     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4091                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4092
4093     // If there is an AND of either shifted operand, apply it to the result.
4094     if (LHSMask.getNode() || RHSMask.getNode()) {
4095       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4096       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4097
4098       if (LHSMask.getNode()) {
4099         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4100         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4101                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4102                                        DAG.getConstant(RHSBits, DL, VT)));
4103       }
4104       if (RHSMask.getNode()) {
4105         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4106         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4107                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4108                                        DAG.getConstant(LHSBits, DL, VT)));
4109       }
4110
4111       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4112     }
4113
4114     return Rot.getNode();
4115   }
4116
4117   // If there is a mask here, and we have a variable shift, we can't be sure
4118   // that we're masking out the right stuff.
4119   if (LHSMask.getNode() || RHSMask.getNode())
4120     return nullptr;
4121
4122   // If the shift amount is sign/zext/any-extended just peel it off.
4123   SDValue LExtOp0 = LHSShiftAmt;
4124   SDValue RExtOp0 = RHSShiftAmt;
4125   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4126        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4127        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4128        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4129       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4130        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4131        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4132        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4133     LExtOp0 = LHSShiftAmt.getOperand(0);
4134     RExtOp0 = RHSShiftAmt.getOperand(0);
4135   }
4136
4137   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4138                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4139   if (TryL)
4140     return TryL;
4141
4142   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4143                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4144   if (TryR)
4145     return TryR;
4146
4147   return nullptr;
4148 }
4149
4150 SDValue DAGCombiner::visitXOR(SDNode *N) {
4151   SDValue N0 = N->getOperand(0);
4152   SDValue N1 = N->getOperand(1);
4153   EVT VT = N0.getValueType();
4154
4155   // fold vector ops
4156   if (VT.isVector()) {
4157     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4158       return FoldedVOp;
4159
4160     // fold (xor x, 0) -> x, vector edition
4161     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4162       return N1;
4163     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4164       return N0;
4165   }
4166
4167   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4168   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4169     return DAG.getConstant(0, SDLoc(N), VT);
4170   // fold (xor x, undef) -> undef
4171   if (N0.getOpcode() == ISD::UNDEF)
4172     return N0;
4173   if (N1.getOpcode() == ISD::UNDEF)
4174     return N1;
4175   // fold (xor c1, c2) -> c1^c2
4176   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4177   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4178   if (N0C && N1C)
4179     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4180   // canonicalize constant to RHS
4181   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4182      !isConstantIntBuildVectorOrConstantInt(N1))
4183     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4184   // fold (xor x, 0) -> x
4185   if (isNullConstant(N1))
4186     return N0;
4187   // reassociate xor
4188   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4189     return RXOR;
4190
4191   // fold !(x cc y) -> (x !cc y)
4192   SDValue LHS, RHS, CC;
4193   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4194     bool isInt = LHS.getValueType().isInteger();
4195     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4196                                                isInt);
4197
4198     if (!LegalOperations ||
4199         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4200       switch (N0.getOpcode()) {
4201       default:
4202         llvm_unreachable("Unhandled SetCC Equivalent!");
4203       case ISD::SETCC:
4204         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4205       case ISD::SELECT_CC:
4206         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4207                                N0.getOperand(3), NotCC);
4208       }
4209     }
4210   }
4211
4212   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4213   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4214       N0.getNode()->hasOneUse() &&
4215       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4216     SDValue V = N0.getOperand(0);
4217     SDLoc DL(N0);
4218     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4219                     DAG.getConstant(1, DL, V.getValueType()));
4220     AddToWorklist(V.getNode());
4221     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4222   }
4223
4224   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4225   if (isOneConstant(N1) && VT == MVT::i1 &&
4226       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4227     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4228     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4229       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4230       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4231       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4232       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4233       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4234     }
4235   }
4236   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4237   if (isAllOnesConstant(N1) &&
4238       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4239     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4240     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4241       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4242       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4243       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4244       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4245       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4246     }
4247   }
4248   // fold (xor (and x, y), y) -> (and (not x), y)
4249   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4250       N0->getOperand(1) == N1) {
4251     SDValue X = N0->getOperand(0);
4252     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4253     AddToWorklist(NotX.getNode());
4254     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4255   }
4256   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4257   if (N1C && N0.getOpcode() == ISD::XOR) {
4258     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4259       SDLoc DL(N);
4260       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4261                          DAG.getConstant(N1C->getAPIntValue() ^
4262                                          N00C->getAPIntValue(), DL, VT));
4263     }
4264     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4265       SDLoc DL(N);
4266       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4267                          DAG.getConstant(N1C->getAPIntValue() ^
4268                                          N01C->getAPIntValue(), DL, VT));
4269     }
4270   }
4271   // fold (xor x, x) -> 0
4272   if (N0 == N1)
4273     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4274
4275   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4276   // Here is a concrete example of this equivalence:
4277   // i16   x ==  14
4278   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4279   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4280   //
4281   // =>
4282   //
4283   // i16     ~1      == 0b1111111111111110
4284   // i16 rol(~1, 14) == 0b1011111111111111
4285   //
4286   // Some additional tips to help conceptualize this transform:
4287   // - Try to see the operation as placing a single zero in a value of all ones.
4288   // - There exists no value for x which would allow the result to contain zero.
4289   // - Values of x larger than the bitwidth are undefined and do not require a
4290   //   consistent result.
4291   // - Pushing the zero left requires shifting one bits in from the right.
4292   // A rotate left of ~1 is a nice way of achieving the desired result.
4293   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4294       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4295     SDLoc DL(N);
4296     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4297                        N0.getOperand(1));
4298   }
4299
4300   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4301   if (N0.getOpcode() == N1.getOpcode())
4302     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4303       return Tmp;
4304
4305   // Simplify the expression using non-local knowledge.
4306   if (!VT.isVector() &&
4307       SimplifyDemandedBits(SDValue(N, 0)))
4308     return SDValue(N, 0);
4309
4310   return SDValue();
4311 }
4312
4313 /// Handle transforms common to the three shifts, when the shift amount is a
4314 /// constant.
4315 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4316   SDNode *LHS = N->getOperand(0).getNode();
4317   if (!LHS->hasOneUse()) return SDValue();
4318
4319   // We want to pull some binops through shifts, so that we have (and (shift))
4320   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4321   // thing happens with address calculations, so it's important to canonicalize
4322   // it.
4323   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4324
4325   switch (LHS->getOpcode()) {
4326   default: return SDValue();
4327   case ISD::OR:
4328   case ISD::XOR:
4329     HighBitSet = false; // We can only transform sra if the high bit is clear.
4330     break;
4331   case ISD::AND:
4332     HighBitSet = true;  // We can only transform sra if the high bit is set.
4333     break;
4334   case ISD::ADD:
4335     if (N->getOpcode() != ISD::SHL)
4336       return SDValue(); // only shl(add) not sr[al](add).
4337     HighBitSet = false; // We can only transform sra if the high bit is clear.
4338     break;
4339   }
4340
4341   // We require the RHS of the binop to be a constant and not opaque as well.
4342   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4343   if (!BinOpCst) return SDValue();
4344
4345   // FIXME: disable this unless the input to the binop is a shift by a constant.
4346   // If it is not a shift, it pessimizes some common cases like:
4347   //
4348   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4349   //    int bar(int *X, int i) { return X[i & 255]; }
4350   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4351   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4352        BinOpLHSVal->getOpcode() != ISD::SRA &&
4353        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4354       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4355     return SDValue();
4356
4357   EVT VT = N->getValueType(0);
4358
4359   // If this is a signed shift right, and the high bit is modified by the
4360   // logical operation, do not perform the transformation. The highBitSet
4361   // boolean indicates the value of the high bit of the constant which would
4362   // cause it to be modified for this operation.
4363   if (N->getOpcode() == ISD::SRA) {
4364     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4365     if (BinOpRHSSignSet != HighBitSet)
4366       return SDValue();
4367   }
4368
4369   if (!TLI.isDesirableToCommuteWithShift(LHS))
4370     return SDValue();
4371
4372   // Fold the constants, shifting the binop RHS by the shift amount.
4373   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4374                                N->getValueType(0),
4375                                LHS->getOperand(1), N->getOperand(1));
4376   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4377
4378   // Create the new shift.
4379   SDValue NewShift = DAG.getNode(N->getOpcode(),
4380                                  SDLoc(LHS->getOperand(0)),
4381                                  VT, LHS->getOperand(0), N->getOperand(1));
4382
4383   // Create the new binop.
4384   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4385 }
4386
4387 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4388   assert(N->getOpcode() == ISD::TRUNCATE);
4389   assert(N->getOperand(0).getOpcode() == ISD::AND);
4390
4391   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4392   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4393     SDValue N01 = N->getOperand(0).getOperand(1);
4394
4395     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4396       if (!N01C->isOpaque()) {
4397         EVT TruncVT = N->getValueType(0);
4398         SDValue N00 = N->getOperand(0).getOperand(0);
4399         APInt TruncC = N01C->getAPIntValue();
4400         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4401         SDLoc DL(N);
4402
4403         return DAG.getNode(ISD::AND, DL, TruncVT,
4404                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4405                            DAG.getConstant(TruncC, DL, TruncVT));
4406       }
4407     }
4408   }
4409
4410   return SDValue();
4411 }
4412
4413 SDValue DAGCombiner::visitRotate(SDNode *N) {
4414   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4415   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4416       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4417     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4418     if (NewOp1.getNode())
4419       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4420                          N->getOperand(0), NewOp1);
4421   }
4422   return SDValue();
4423 }
4424
4425 SDValue DAGCombiner::visitSHL(SDNode *N) {
4426   SDValue N0 = N->getOperand(0);
4427   SDValue N1 = N->getOperand(1);
4428   EVT VT = N0.getValueType();
4429   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4430
4431   // fold vector ops
4432   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4433   if (VT.isVector()) {
4434     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4435       return FoldedVOp;
4436
4437     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4438     // If setcc produces all-one true value then:
4439     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4440     if (N1CV && N1CV->isConstant()) {
4441       if (N0.getOpcode() == ISD::AND) {
4442         SDValue N00 = N0->getOperand(0);
4443         SDValue N01 = N0->getOperand(1);
4444         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4445
4446         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4447             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4448                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4449           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4450                                                      N01CV, N1CV))
4451             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4452         }
4453       } else {
4454         N1C = isConstOrConstSplat(N1);
4455       }
4456     }
4457   }
4458
4459   // fold (shl c1, c2) -> c1<<c2
4460   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4461   if (N0C && N1C && !N1C->isOpaque())
4462     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4463   // fold (shl 0, x) -> 0
4464   if (isNullConstant(N0))
4465     return N0;
4466   // fold (shl x, c >= size(x)) -> undef
4467   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4468     return DAG.getUNDEF(VT);
4469   // fold (shl x, 0) -> x
4470   if (N1C && N1C->isNullValue())
4471     return N0;
4472   // fold (shl undef, x) -> 0
4473   if (N0.getOpcode() == ISD::UNDEF)
4474     return DAG.getConstant(0, SDLoc(N), VT);
4475   // if (shl x, c) is known to be zero, return 0
4476   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4477                             APInt::getAllOnesValue(OpSizeInBits)))
4478     return DAG.getConstant(0, SDLoc(N), VT);
4479   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4480   if (N1.getOpcode() == ISD::TRUNCATE &&
4481       N1.getOperand(0).getOpcode() == ISD::AND) {
4482     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4483     if (NewOp1.getNode())
4484       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4485   }
4486
4487   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4488     return SDValue(N, 0);
4489
4490   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4491   if (N1C && N0.getOpcode() == ISD::SHL) {
4492     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4493       uint64_t c1 = N0C1->getZExtValue();
4494       uint64_t c2 = N1C->getZExtValue();
4495       SDLoc DL(N);
4496       if (c1 + c2 >= OpSizeInBits)
4497         return DAG.getConstant(0, DL, VT);
4498       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4499                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4500     }
4501   }
4502
4503   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4504   // For this to be valid, the second form must not preserve any of the bits
4505   // that are shifted out by the inner shift in the first form.  This means
4506   // the outer shift size must be >= the number of bits added by the ext.
4507   // As a corollary, we don't care what kind of ext it is.
4508   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4509               N0.getOpcode() == ISD::ANY_EXTEND ||
4510               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4511       N0.getOperand(0).getOpcode() == ISD::SHL) {
4512     SDValue N0Op0 = N0.getOperand(0);
4513     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4514       uint64_t c1 = N0Op0C1->getZExtValue();
4515       uint64_t c2 = N1C->getZExtValue();
4516       EVT InnerShiftVT = N0Op0.getValueType();
4517       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4518       if (c2 >= OpSizeInBits - InnerShiftSize) {
4519         SDLoc DL(N0);
4520         if (c1 + c2 >= OpSizeInBits)
4521           return DAG.getConstant(0, DL, VT);
4522         return DAG.getNode(ISD::SHL, DL, VT,
4523                            DAG.getNode(N0.getOpcode(), DL, VT,
4524                                        N0Op0->getOperand(0)),
4525                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4526       }
4527     }
4528   }
4529
4530   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4531   // Only fold this if the inner zext has no other uses to avoid increasing
4532   // the total number of instructions.
4533   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4534       N0.getOperand(0).getOpcode() == ISD::SRL) {
4535     SDValue N0Op0 = N0.getOperand(0);
4536     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4537       uint64_t c1 = N0Op0C1->getZExtValue();
4538       if (c1 < VT.getScalarSizeInBits()) {
4539         uint64_t c2 = N1C->getZExtValue();
4540         if (c1 == c2) {
4541           SDValue NewOp0 = N0.getOperand(0);
4542           EVT CountVT = NewOp0.getOperand(1).getValueType();
4543           SDLoc DL(N);
4544           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4545                                        NewOp0,
4546                                        DAG.getConstant(c2, DL, CountVT));
4547           AddToWorklist(NewSHL.getNode());
4548           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4549         }
4550       }
4551     }
4552   }
4553
4554   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4555   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4556   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4557       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4558     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4559       uint64_t C1 = N0C1->getZExtValue();
4560       uint64_t C2 = N1C->getZExtValue();
4561       SDLoc DL(N);
4562       if (C1 <= C2)
4563         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4564                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4565       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4566                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4567     }
4568   }
4569
4570   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4571   //                               (and (srl x, (sub c1, c2), MASK)
4572   // Only fold this if the inner shift has no other uses -- if it does, folding
4573   // this will increase the total number of instructions.
4574   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4575     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4576       uint64_t c1 = N0C1->getZExtValue();
4577       if (c1 < OpSizeInBits) {
4578         uint64_t c2 = N1C->getZExtValue();
4579         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4580         SDValue Shift;
4581         if (c2 > c1) {
4582           Mask = Mask.shl(c2 - c1);
4583           SDLoc DL(N);
4584           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4585                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4586         } else {
4587           Mask = Mask.lshr(c1 - c2);
4588           SDLoc DL(N);
4589           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4590                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4591         }
4592         SDLoc DL(N0);
4593         return DAG.getNode(ISD::AND, DL, VT, Shift,
4594                            DAG.getConstant(Mask, DL, VT));
4595       }
4596     }
4597   }
4598   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4599   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4600     unsigned BitSize = VT.getScalarSizeInBits();
4601     SDLoc DL(N);
4602     SDValue HiBitsMask =
4603       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4604                                             BitSize - N1C->getZExtValue()),
4605                       DL, VT);
4606     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4607                        HiBitsMask);
4608   }
4609
4610   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4611   // Variant of version done on multiply, except mul by a power of 2 is turned
4612   // into a shift.
4613   APInt Val;
4614   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4615       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4616        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4617     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4618     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4619     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4620   }
4621
4622   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4623   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4624     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4625       if (SDValue Folded =
4626               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4627         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4628     }
4629   }
4630
4631   if (N1C && !N1C->isOpaque())
4632     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4633       return NewSHL;
4634
4635   return SDValue();
4636 }
4637
4638 SDValue DAGCombiner::visitSRA(SDNode *N) {
4639   SDValue N0 = N->getOperand(0);
4640   SDValue N1 = N->getOperand(1);
4641   EVT VT = N0.getValueType();
4642   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4643
4644   // fold vector ops
4645   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4646   if (VT.isVector()) {
4647     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4648       return FoldedVOp;
4649
4650     N1C = isConstOrConstSplat(N1);
4651   }
4652
4653   // fold (sra c1, c2) -> (sra c1, c2)
4654   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4655   if (N0C && N1C && !N1C->isOpaque())
4656     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4657   // fold (sra 0, x) -> 0
4658   if (isNullConstant(N0))
4659     return N0;
4660   // fold (sra -1, x) -> -1
4661   if (isAllOnesConstant(N0))
4662     return N0;
4663   // fold (sra x, (setge c, size(x))) -> undef
4664   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4665     return DAG.getUNDEF(VT);
4666   // fold (sra x, 0) -> x
4667   if (N1C && N1C->isNullValue())
4668     return N0;
4669   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4670   // sext_inreg.
4671   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4672     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4673     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4674     if (VT.isVector())
4675       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4676                                ExtVT, VT.getVectorNumElements());
4677     if ((!LegalOperations ||
4678          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4679       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4680                          N0.getOperand(0), DAG.getValueType(ExtVT));
4681   }
4682
4683   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4684   if (N1C && N0.getOpcode() == ISD::SRA) {
4685     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4686       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4687       if (Sum >= OpSizeInBits)
4688         Sum = OpSizeInBits - 1;
4689       SDLoc DL(N);
4690       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4691                          DAG.getConstant(Sum, DL, N1.getValueType()));
4692     }
4693   }
4694
4695   // fold (sra (shl X, m), (sub result_size, n))
4696   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4697   // result_size - n != m.
4698   // If truncate is free for the target sext(shl) is likely to result in better
4699   // code.
4700   if (N0.getOpcode() == ISD::SHL && N1C) {
4701     // Get the two constanst of the shifts, CN0 = m, CN = n.
4702     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4703     if (N01C) {
4704       LLVMContext &Ctx = *DAG.getContext();
4705       // Determine what the truncate's result bitsize and type would be.
4706       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4707
4708       if (VT.isVector())
4709         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4710
4711       // Determine the residual right-shift amount.
4712       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4713
4714       // If the shift is not a no-op (in which case this should be just a sign
4715       // extend already), the truncated to type is legal, sign_extend is legal
4716       // on that type, and the truncate to that type is both legal and free,
4717       // perform the transform.
4718       if ((ShiftAmt > 0) &&
4719           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4720           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4721           TLI.isTruncateFree(VT, TruncVT)) {
4722
4723         SDLoc DL(N);
4724         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4725             getShiftAmountTy(N0.getOperand(0).getValueType()));
4726         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4727                                     N0.getOperand(0), Amt);
4728         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4729                                     Shift);
4730         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4731                            N->getValueType(0), Trunc);
4732       }
4733     }
4734   }
4735
4736   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4737   if (N1.getOpcode() == ISD::TRUNCATE &&
4738       N1.getOperand(0).getOpcode() == ISD::AND) {
4739     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4740     if (NewOp1.getNode())
4741       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4742   }
4743
4744   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4745   //      if c1 is equal to the number of bits the trunc removes
4746   if (N0.getOpcode() == ISD::TRUNCATE &&
4747       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4748        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4749       N0.getOperand(0).hasOneUse() &&
4750       N0.getOperand(0).getOperand(1).hasOneUse() &&
4751       N1C) {
4752     SDValue N0Op0 = N0.getOperand(0);
4753     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4754       unsigned LargeShiftVal = LargeShift->getZExtValue();
4755       EVT LargeVT = N0Op0.getValueType();
4756
4757       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4758         SDLoc DL(N);
4759         SDValue Amt =
4760           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4761                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4762         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4763                                   N0Op0.getOperand(0), Amt);
4764         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4765       }
4766     }
4767   }
4768
4769   // Simplify, based on bits shifted out of the LHS.
4770   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4771     return SDValue(N, 0);
4772
4773
4774   // If the sign bit is known to be zero, switch this to a SRL.
4775   if (DAG.SignBitIsZero(N0))
4776     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4777
4778   if (N1C && !N1C->isOpaque())
4779     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4780       return NewSRA;
4781
4782   return SDValue();
4783 }
4784
4785 SDValue DAGCombiner::visitSRL(SDNode *N) {
4786   SDValue N0 = N->getOperand(0);
4787   SDValue N1 = N->getOperand(1);
4788   EVT VT = N0.getValueType();
4789   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4790
4791   // fold vector ops
4792   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4793   if (VT.isVector()) {
4794     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4795       return FoldedVOp;
4796
4797     N1C = isConstOrConstSplat(N1);
4798   }
4799
4800   // fold (srl c1, c2) -> c1 >>u c2
4801   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4802   if (N0C && N1C && !N1C->isOpaque())
4803     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4804   // fold (srl 0, x) -> 0
4805   if (isNullConstant(N0))
4806     return N0;
4807   // fold (srl x, c >= size(x)) -> undef
4808   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4809     return DAG.getUNDEF(VT);
4810   // fold (srl x, 0) -> x
4811   if (N1C && N1C->isNullValue())
4812     return N0;
4813   // if (srl x, c) is known to be zero, return 0
4814   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4815                                    APInt::getAllOnesValue(OpSizeInBits)))
4816     return DAG.getConstant(0, SDLoc(N), VT);
4817
4818   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4819   if (N1C && N0.getOpcode() == ISD::SRL) {
4820     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4821       uint64_t c1 = N01C->getZExtValue();
4822       uint64_t c2 = N1C->getZExtValue();
4823       SDLoc DL(N);
4824       if (c1 + c2 >= OpSizeInBits)
4825         return DAG.getConstant(0, DL, VT);
4826       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4827                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4828     }
4829   }
4830
4831   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4832   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4833       N0.getOperand(0).getOpcode() == ISD::SRL &&
4834       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4835     uint64_t c1 =
4836       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4837     uint64_t c2 = N1C->getZExtValue();
4838     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4839     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4840     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4841     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4842     if (c1 + OpSizeInBits == InnerShiftSize) {
4843       SDLoc DL(N0);
4844       if (c1 + c2 >= InnerShiftSize)
4845         return DAG.getConstant(0, DL, VT);
4846       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4847                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4848                                      N0.getOperand(0)->getOperand(0),
4849                                      DAG.getConstant(c1 + c2, DL,
4850                                                      ShiftCountVT)));
4851     }
4852   }
4853
4854   // fold (srl (shl x, c), c) -> (and x, cst2)
4855   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4856     unsigned BitSize = N0.getScalarValueSizeInBits();
4857     if (BitSize <= 64) {
4858       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4859       SDLoc DL(N);
4860       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4861                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4862     }
4863   }
4864
4865   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4866   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4867     // Shifting in all undef bits?
4868     EVT SmallVT = N0.getOperand(0).getValueType();
4869     unsigned BitSize = SmallVT.getScalarSizeInBits();
4870     if (N1C->getZExtValue() >= BitSize)
4871       return DAG.getUNDEF(VT);
4872
4873     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4874       uint64_t ShiftAmt = N1C->getZExtValue();
4875       SDLoc DL0(N0);
4876       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4877                                        N0.getOperand(0),
4878                           DAG.getConstant(ShiftAmt, DL0,
4879                                           getShiftAmountTy(SmallVT)));
4880       AddToWorklist(SmallShift.getNode());
4881       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4882       SDLoc DL(N);
4883       return DAG.getNode(ISD::AND, DL, VT,
4884                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4885                          DAG.getConstant(Mask, DL, VT));
4886     }
4887   }
4888
4889   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4890   // bit, which is unmodified by sra.
4891   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4892     if (N0.getOpcode() == ISD::SRA)
4893       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4894   }
4895
4896   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4897   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4898       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4899     APInt KnownZero, KnownOne;
4900     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4901
4902     // If any of the input bits are KnownOne, then the input couldn't be all
4903     // zeros, thus the result of the srl will always be zero.
4904     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4905
4906     // If all of the bits input the to ctlz node are known to be zero, then
4907     // the result of the ctlz is "32" and the result of the shift is one.
4908     APInt UnknownBits = ~KnownZero;
4909     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4910
4911     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4912     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4913       // Okay, we know that only that the single bit specified by UnknownBits
4914       // could be set on input to the CTLZ node. If this bit is set, the SRL
4915       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4916       // to an SRL/XOR pair, which is likely to simplify more.
4917       unsigned ShAmt = UnknownBits.countTrailingZeros();
4918       SDValue Op = N0.getOperand(0);
4919
4920       if (ShAmt) {
4921         SDLoc DL(N0);
4922         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4923                   DAG.getConstant(ShAmt, DL,
4924                                   getShiftAmountTy(Op.getValueType())));
4925         AddToWorklist(Op.getNode());
4926       }
4927
4928       SDLoc DL(N);
4929       return DAG.getNode(ISD::XOR, DL, VT,
4930                          Op, DAG.getConstant(1, DL, VT));
4931     }
4932   }
4933
4934   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4935   if (N1.getOpcode() == ISD::TRUNCATE &&
4936       N1.getOperand(0).getOpcode() == ISD::AND) {
4937     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4938       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4939   }
4940
4941   // fold operands of srl based on knowledge that the low bits are not
4942   // demanded.
4943   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4944     return SDValue(N, 0);
4945
4946   if (N1C && !N1C->isOpaque())
4947     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4948       return NewSRL;
4949
4950   // Attempt to convert a srl of a load into a narrower zero-extending load.
4951   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4952     return NarrowLoad;
4953
4954   // Here is a common situation. We want to optimize:
4955   //
4956   //   %a = ...
4957   //   %b = and i32 %a, 2
4958   //   %c = srl i32 %b, 1
4959   //   brcond i32 %c ...
4960   //
4961   // into
4962   //
4963   //   %a = ...
4964   //   %b = and %a, 2
4965   //   %c = setcc eq %b, 0
4966   //   brcond %c ...
4967   //
4968   // However when after the source operand of SRL is optimized into AND, the SRL
4969   // itself may not be optimized further. Look for it and add the BRCOND into
4970   // the worklist.
4971   if (N->hasOneUse()) {
4972     SDNode *Use = *N->use_begin();
4973     if (Use->getOpcode() == ISD::BRCOND)
4974       AddToWorklist(Use);
4975     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4976       // Also look pass the truncate.
4977       Use = *Use->use_begin();
4978       if (Use->getOpcode() == ISD::BRCOND)
4979         AddToWorklist(Use);
4980     }
4981   }
4982
4983   return SDValue();
4984 }
4985
4986 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4987   SDValue N0 = N->getOperand(0);
4988   EVT VT = N->getValueType(0);
4989
4990   // fold (bswap c1) -> c2
4991   if (isConstantIntBuildVectorOrConstantInt(N0))
4992     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4993   // fold (bswap (bswap x)) -> x
4994   if (N0.getOpcode() == ISD::BSWAP)
4995     return N0->getOperand(0);
4996   return SDValue();
4997 }
4998
4999 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5000   SDValue N0 = N->getOperand(0);
5001   EVT VT = N->getValueType(0);
5002
5003   // fold (ctlz c1) -> c2
5004   if (isConstantIntBuildVectorOrConstantInt(N0))
5005     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5006   return SDValue();
5007 }
5008
5009 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5010   SDValue N0 = N->getOperand(0);
5011   EVT VT = N->getValueType(0);
5012
5013   // fold (ctlz_zero_undef c1) -> c2
5014   if (isConstantIntBuildVectorOrConstantInt(N0))
5015     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5016   return SDValue();
5017 }
5018
5019 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5020   SDValue N0 = N->getOperand(0);
5021   EVT VT = N->getValueType(0);
5022
5023   // fold (cttz c1) -> c2
5024   if (isConstantIntBuildVectorOrConstantInt(N0))
5025     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5026   return SDValue();
5027 }
5028
5029 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5030   SDValue N0 = N->getOperand(0);
5031   EVT VT = N->getValueType(0);
5032
5033   // fold (cttz_zero_undef c1) -> c2
5034   if (isConstantIntBuildVectorOrConstantInt(N0))
5035     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5036   return SDValue();
5037 }
5038
5039 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5040   SDValue N0 = N->getOperand(0);
5041   EVT VT = N->getValueType(0);
5042
5043   // fold (ctpop c1) -> c2
5044   if (isConstantIntBuildVectorOrConstantInt(N0))
5045     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5046   return SDValue();
5047 }
5048
5049
5050 /// \brief Generate Min/Max node
5051 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5052                                    SDValue True, SDValue False,
5053                                    ISD::CondCode CC, const TargetLowering &TLI,
5054                                    SelectionDAG &DAG) {
5055   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5056     return SDValue();
5057
5058   switch (CC) {
5059   case ISD::SETOLT:
5060   case ISD::SETOLE:
5061   case ISD::SETLT:
5062   case ISD::SETLE:
5063   case ISD::SETULT:
5064   case ISD::SETULE: {
5065     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5066     if (TLI.isOperationLegal(Opcode, VT))
5067       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5068     return SDValue();
5069   }
5070   case ISD::SETOGT:
5071   case ISD::SETOGE:
5072   case ISD::SETGT:
5073   case ISD::SETGE:
5074   case ISD::SETUGT:
5075   case ISD::SETUGE: {
5076     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5077     if (TLI.isOperationLegal(Opcode, VT))
5078       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5079     return SDValue();
5080   }
5081   default:
5082     return SDValue();
5083   }
5084 }
5085
5086 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5087   SDValue N0 = N->getOperand(0);
5088   SDValue N1 = N->getOperand(1);
5089   SDValue N2 = N->getOperand(2);
5090   EVT VT = N->getValueType(0);
5091   EVT VT0 = N0.getValueType();
5092
5093   // fold (select C, X, X) -> X
5094   if (N1 == N2)
5095     return N1;
5096   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5097     // fold (select true, X, Y) -> X
5098     // fold (select false, X, Y) -> Y
5099     return !N0C->isNullValue() ? N1 : N2;
5100   }
5101   // fold (select C, 1, X) -> (or C, X)
5102   if (VT == MVT::i1 && isOneConstant(N1))
5103     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5104   // fold (select C, 0, 1) -> (xor C, 1)
5105   // We can't do this reliably if integer based booleans have different contents
5106   // to floating point based booleans. This is because we can't tell whether we
5107   // have an integer-based boolean or a floating-point-based boolean unless we
5108   // can find the SETCC that produced it and inspect its operands. This is
5109   // fairly easy if C is the SETCC node, but it can potentially be
5110   // undiscoverable (or not reasonably discoverable). For example, it could be
5111   // in another basic block or it could require searching a complicated
5112   // expression.
5113   if (VT.isInteger() &&
5114       (VT0 == MVT::i1 || (VT0.isInteger() &&
5115                           TLI.getBooleanContents(false, false) ==
5116                               TLI.getBooleanContents(false, true) &&
5117                           TLI.getBooleanContents(false, false) ==
5118                               TargetLowering::ZeroOrOneBooleanContent)) &&
5119       isNullConstant(N1) && isOneConstant(N2)) {
5120     SDValue XORNode;
5121     if (VT == VT0) {
5122       SDLoc DL(N);
5123       return DAG.getNode(ISD::XOR, DL, VT0,
5124                          N0, DAG.getConstant(1, DL, VT0));
5125     }
5126     SDLoc DL0(N0);
5127     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5128                           N0, DAG.getConstant(1, DL0, VT0));
5129     AddToWorklist(XORNode.getNode());
5130     if (VT.bitsGT(VT0))
5131       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5132     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5133   }
5134   // fold (select C, 0, X) -> (and (not C), X)
5135   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5136     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5137     AddToWorklist(NOTNode.getNode());
5138     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5139   }
5140   // fold (select C, X, 1) -> (or (not C), X)
5141   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5142     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5143     AddToWorklist(NOTNode.getNode());
5144     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5145   }
5146   // fold (select C, X, 0) -> (and C, X)
5147   if (VT == MVT::i1 && isNullConstant(N2))
5148     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5149   // fold (select X, X, Y) -> (or X, Y)
5150   // fold (select X, 1, Y) -> (or X, Y)
5151   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5152     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5153   // fold (select X, Y, X) -> (and X, Y)
5154   // fold (select X, Y, 0) -> (and X, Y)
5155   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5156     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5157
5158   // If we can fold this based on the true/false value, do so.
5159   if (SimplifySelectOps(N, N1, N2))
5160     return SDValue(N, 0);  // Don't revisit N.
5161
5162   if (VT0 == MVT::i1) {
5163     // The code in this block deals with the following 2 equivalences:
5164     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5165     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5166     // The target can specify its prefered form with the
5167     // shouldNormalizeToSelectSequence() callback. However we always transform
5168     // to the right anyway if we find the inner select exists in the DAG anyway
5169     // and we always transform to the left side if we know that we can further
5170     // optimize the combination of the conditions.
5171     bool normalizeToSequence
5172       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5173     // select (and Cond0, Cond1), X, Y
5174     //   -> select Cond0, (select Cond1, X, Y), Y
5175     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5176       SDValue Cond0 = N0->getOperand(0);
5177       SDValue Cond1 = N0->getOperand(1);
5178       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5179                                         N1.getValueType(), Cond1, N1, N2);
5180       if (normalizeToSequence || !InnerSelect.use_empty())
5181         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5182                            InnerSelect, N2);
5183     }
5184     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5185     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5186       SDValue Cond0 = N0->getOperand(0);
5187       SDValue Cond1 = N0->getOperand(1);
5188       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5189                                         N1.getValueType(), Cond1, N1, N2);
5190       if (normalizeToSequence || !InnerSelect.use_empty())
5191         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5192                            InnerSelect);
5193     }
5194
5195     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5196     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5197       SDValue N1_0 = N1->getOperand(0);
5198       SDValue N1_1 = N1->getOperand(1);
5199       SDValue N1_2 = N1->getOperand(2);
5200       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5201         // Create the actual and node if we can generate good code for it.
5202         if (!normalizeToSequence) {
5203           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5204                                     N0, N1_0);
5205           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5206                              N1_1, N2);
5207         }
5208         // Otherwise see if we can optimize the "and" to a better pattern.
5209         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5210           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5211                              N1_1, N2);
5212       }
5213     }
5214     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5215     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5216       SDValue N2_0 = N2->getOperand(0);
5217       SDValue N2_1 = N2->getOperand(1);
5218       SDValue N2_2 = N2->getOperand(2);
5219       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5220         // Create the actual or node if we can generate good code for it.
5221         if (!normalizeToSequence) {
5222           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5223                                    N0, N2_0);
5224           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5225                              N1, N2_2);
5226         }
5227         // Otherwise see if we can optimize to a better pattern.
5228         if (SDValue Combined = visitORLike(N0, N2_0, N))
5229           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5230                              N1, N2_2);
5231       }
5232     }
5233   }
5234
5235   // fold selects based on a setcc into other things, such as min/max/abs
5236   if (N0.getOpcode() == ISD::SETCC) {
5237     // select x, y (fcmp lt x, y) -> fminnum x, y
5238     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5239     //
5240     // This is OK if we don't care about what happens if either operand is a
5241     // NaN.
5242     //
5243
5244     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5245     // no signed zeros as well as no nans.
5246     const TargetOptions &Options = DAG.getTarget().Options;
5247     if (Options.UnsafeFPMath &&
5248         VT.isFloatingPoint() && N0.hasOneUse() &&
5249         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5250       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5251
5252       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5253                                                 N0.getOperand(1), N1, N2, CC,
5254                                                 TLI, DAG))
5255         return FMinMax;
5256     }
5257
5258     if ((!LegalOperations &&
5259          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5260         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5261       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5262                          N0.getOperand(0), N0.getOperand(1),
5263                          N1, N2, N0.getOperand(2));
5264     return SimplifySelect(SDLoc(N), N0, N1, N2);
5265   }
5266
5267   return SDValue();
5268 }
5269
5270 static
5271 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5272   SDLoc DL(N);
5273   EVT LoVT, HiVT;
5274   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5275
5276   // Split the inputs.
5277   SDValue Lo, Hi, LL, LH, RL, RH;
5278   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5279   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5280
5281   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5282   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5283
5284   return std::make_pair(Lo, Hi);
5285 }
5286
5287 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5288 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5289 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5290   SDLoc dl(N);
5291   SDValue Cond = N->getOperand(0);
5292   SDValue LHS = N->getOperand(1);
5293   SDValue RHS = N->getOperand(2);
5294   EVT VT = N->getValueType(0);
5295   int NumElems = VT.getVectorNumElements();
5296   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5297          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5298          Cond.getOpcode() == ISD::BUILD_VECTOR);
5299
5300   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5301   // binary ones here.
5302   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5303     return SDValue();
5304
5305   // We're sure we have an even number of elements due to the
5306   // concat_vectors we have as arguments to vselect.
5307   // Skip BV elements until we find one that's not an UNDEF
5308   // After we find an UNDEF element, keep looping until we get to half the
5309   // length of the BV and see if all the non-undef nodes are the same.
5310   ConstantSDNode *BottomHalf = nullptr;
5311   for (int i = 0; i < NumElems / 2; ++i) {
5312     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5313       continue;
5314
5315     if (BottomHalf == nullptr)
5316       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5317     else if (Cond->getOperand(i).getNode() != BottomHalf)
5318       return SDValue();
5319   }
5320
5321   // Do the same for the second half of the BuildVector
5322   ConstantSDNode *TopHalf = nullptr;
5323   for (int i = NumElems / 2; i < NumElems; ++i) {
5324     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5325       continue;
5326
5327     if (TopHalf == nullptr)
5328       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5329     else if (Cond->getOperand(i).getNode() != TopHalf)
5330       return SDValue();
5331   }
5332
5333   assert(TopHalf && BottomHalf &&
5334          "One half of the selector was all UNDEFs and the other was all the "
5335          "same value. This should have been addressed before this function.");
5336   return DAG.getNode(
5337       ISD::CONCAT_VECTORS, dl, VT,
5338       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5339       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5340 }
5341
5342 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5343
5344   if (Level >= AfterLegalizeTypes)
5345     return SDValue();
5346
5347   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5348   SDValue Mask = MSC->getMask();
5349   SDValue Data  = MSC->getValue();
5350   SDLoc DL(N);
5351
5352   // If the MSCATTER data type requires splitting and the mask is provided by a
5353   // SETCC, then split both nodes and its operands before legalization. This
5354   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5355   // and enables future optimizations (e.g. min/max pattern matching on X86).
5356   if (Mask.getOpcode() != ISD::SETCC)
5357     return SDValue();
5358
5359   // Check if any splitting is required.
5360   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5361       TargetLowering::TypeSplitVector)
5362     return SDValue();
5363   SDValue MaskLo, MaskHi, Lo, Hi;
5364   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5365
5366   EVT LoVT, HiVT;
5367   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5368
5369   SDValue Chain = MSC->getChain();
5370
5371   EVT MemoryVT = MSC->getMemoryVT();
5372   unsigned Alignment = MSC->getOriginalAlignment();
5373
5374   EVT LoMemVT, HiMemVT;
5375   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5376
5377   SDValue DataLo, DataHi;
5378   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5379
5380   SDValue BasePtr = MSC->getBasePtr();
5381   SDValue IndexLo, IndexHi;
5382   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5383
5384   MachineMemOperand *MMO = DAG.getMachineFunction().
5385     getMachineMemOperand(MSC->getPointerInfo(),
5386                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5387                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5388
5389   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5390   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5391                             DL, OpsLo, MMO);
5392
5393   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5394   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5395                             DL, OpsHi, MMO);
5396
5397   AddToWorklist(Lo.getNode());
5398   AddToWorklist(Hi.getNode());
5399
5400   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5401 }
5402
5403 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5404
5405   if (Level >= AfterLegalizeTypes)
5406     return SDValue();
5407
5408   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5409   SDValue Mask = MST->getMask();
5410   SDValue Data  = MST->getValue();
5411   SDLoc DL(N);
5412
5413   // If the MSTORE data type requires splitting and the mask is provided by a
5414   // SETCC, then split both nodes and its operands before legalization. This
5415   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5416   // and enables future optimizations (e.g. min/max pattern matching on X86).
5417   if (Mask.getOpcode() == ISD::SETCC) {
5418
5419     // Check if any splitting is required.
5420     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5421         TargetLowering::TypeSplitVector)
5422       return SDValue();
5423
5424     SDValue MaskLo, MaskHi, Lo, Hi;
5425     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5426
5427     EVT LoVT, HiVT;
5428     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5429
5430     SDValue Chain = MST->getChain();
5431     SDValue Ptr   = MST->getBasePtr();
5432
5433     EVT MemoryVT = MST->getMemoryVT();
5434     unsigned Alignment = MST->getOriginalAlignment();
5435
5436     // if Alignment is equal to the vector size,
5437     // take the half of it for the second part
5438     unsigned SecondHalfAlignment =
5439       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5440          Alignment/2 : Alignment;
5441
5442     EVT LoMemVT, HiMemVT;
5443     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5444
5445     SDValue DataLo, DataHi;
5446     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5447
5448     MachineMemOperand *MMO = DAG.getMachineFunction().
5449       getMachineMemOperand(MST->getPointerInfo(),
5450                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5451                            Alignment, MST->getAAInfo(), MST->getRanges());
5452
5453     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5454                             MST->isTruncatingStore());
5455
5456     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5457     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5458                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5459
5460     MMO = DAG.getMachineFunction().
5461       getMachineMemOperand(MST->getPointerInfo(),
5462                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5463                            SecondHalfAlignment, MST->getAAInfo(),
5464                            MST->getRanges());
5465
5466     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5467                             MST->isTruncatingStore());
5468
5469     AddToWorklist(Lo.getNode());
5470     AddToWorklist(Hi.getNode());
5471
5472     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5473   }
5474   return SDValue();
5475 }
5476
5477 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5478
5479   if (Level >= AfterLegalizeTypes)
5480     return SDValue();
5481
5482   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5483   SDValue Mask = MGT->getMask();
5484   SDLoc DL(N);
5485
5486   // If the MGATHER result requires splitting and the mask is provided by a
5487   // SETCC, then split both nodes and its operands before legalization. This
5488   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5489   // and enables future optimizations (e.g. min/max pattern matching on X86).
5490
5491   if (Mask.getOpcode() != ISD::SETCC)
5492     return SDValue();
5493
5494   EVT VT = N->getValueType(0);
5495
5496   // Check if any splitting is required.
5497   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5498       TargetLowering::TypeSplitVector)
5499     return SDValue();
5500
5501   SDValue MaskLo, MaskHi, Lo, Hi;
5502   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5503
5504   SDValue Src0 = MGT->getValue();
5505   SDValue Src0Lo, Src0Hi;
5506   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5507
5508   EVT LoVT, HiVT;
5509   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5510
5511   SDValue Chain = MGT->getChain();
5512   EVT MemoryVT = MGT->getMemoryVT();
5513   unsigned Alignment = MGT->getOriginalAlignment();
5514
5515   EVT LoMemVT, HiMemVT;
5516   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5517
5518   SDValue BasePtr = MGT->getBasePtr();
5519   SDValue Index = MGT->getIndex();
5520   SDValue IndexLo, IndexHi;
5521   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5522
5523   MachineMemOperand *MMO = DAG.getMachineFunction().
5524     getMachineMemOperand(MGT->getPointerInfo(),
5525                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5526                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5527
5528   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5529   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5530                             MMO);
5531
5532   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5533   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5534                             MMO);
5535
5536   AddToWorklist(Lo.getNode());
5537   AddToWorklist(Hi.getNode());
5538
5539   // Build a factor node to remember that this load is independent of the
5540   // other one.
5541   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5542                       Hi.getValue(1));
5543
5544   // Legalized the chain result - switch anything that used the old chain to
5545   // use the new one.
5546   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5547
5548   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5549
5550   SDValue RetOps[] = { GatherRes, Chain };
5551   return DAG.getMergeValues(RetOps, DL);
5552 }
5553
5554 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5555
5556   if (Level >= AfterLegalizeTypes)
5557     return SDValue();
5558
5559   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5560   SDValue Mask = MLD->getMask();
5561   SDLoc DL(N);
5562
5563   // If the MLOAD result requires splitting and the mask is provided by a
5564   // SETCC, then split both nodes and its operands before legalization. This
5565   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5566   // and enables future optimizations (e.g. min/max pattern matching on X86).
5567
5568   if (Mask.getOpcode() == ISD::SETCC) {
5569     EVT VT = N->getValueType(0);
5570
5571     // Check if any splitting is required.
5572     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5573         TargetLowering::TypeSplitVector)
5574       return SDValue();
5575
5576     SDValue MaskLo, MaskHi, Lo, Hi;
5577     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5578
5579     SDValue Src0 = MLD->getSrc0();
5580     SDValue Src0Lo, Src0Hi;
5581     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5582
5583     EVT LoVT, HiVT;
5584     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5585
5586     SDValue Chain = MLD->getChain();
5587     SDValue Ptr   = MLD->getBasePtr();
5588     EVT MemoryVT = MLD->getMemoryVT();
5589     unsigned Alignment = MLD->getOriginalAlignment();
5590
5591     // if Alignment is equal to the vector size,
5592     // take the half of it for the second part
5593     unsigned SecondHalfAlignment =
5594       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5595          Alignment/2 : Alignment;
5596
5597     EVT LoMemVT, HiMemVT;
5598     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5599
5600     MachineMemOperand *MMO = DAG.getMachineFunction().
5601     getMachineMemOperand(MLD->getPointerInfo(),
5602                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5603                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5604
5605     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5606                            ISD::NON_EXTLOAD);
5607
5608     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5609     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5610                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5611
5612     MMO = DAG.getMachineFunction().
5613     getMachineMemOperand(MLD->getPointerInfo(),
5614                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5615                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5616
5617     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5618                            ISD::NON_EXTLOAD);
5619
5620     AddToWorklist(Lo.getNode());
5621     AddToWorklist(Hi.getNode());
5622
5623     // Build a factor node to remember that this load is independent of the
5624     // other one.
5625     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5626                         Hi.getValue(1));
5627
5628     // Legalized the chain result - switch anything that used the old chain to
5629     // use the new one.
5630     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5631
5632     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5633
5634     SDValue RetOps[] = { LoadRes, Chain };
5635     return DAG.getMergeValues(RetOps, DL);
5636   }
5637   return SDValue();
5638 }
5639
5640 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5641   SDValue N0 = N->getOperand(0);
5642   SDValue N1 = N->getOperand(1);
5643   SDValue N2 = N->getOperand(2);
5644   SDLoc DL(N);
5645
5646   // Canonicalize integer abs.
5647   // vselect (setg[te] X,  0),  X, -X ->
5648   // vselect (setgt    X, -1),  X, -X ->
5649   // vselect (setl[te] X,  0), -X,  X ->
5650   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5651   if (N0.getOpcode() == ISD::SETCC) {
5652     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5653     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5654     bool isAbs = false;
5655     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5656
5657     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5658          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5659         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5660       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5661     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5662              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5663       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5664
5665     if (isAbs) {
5666       EVT VT = LHS.getValueType();
5667       SDValue Shift = DAG.getNode(
5668           ISD::SRA, DL, VT, LHS,
5669           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5670       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5671       AddToWorklist(Shift.getNode());
5672       AddToWorklist(Add.getNode());
5673       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5674     }
5675   }
5676
5677   if (SimplifySelectOps(N, N1, N2))
5678     return SDValue(N, 0);  // Don't revisit N.
5679
5680   // If the VSELECT result requires splitting and the mask is provided by a
5681   // SETCC, then split both nodes and its operands before legalization. This
5682   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5683   // and enables future optimizations (e.g. min/max pattern matching on X86).
5684   if (N0.getOpcode() == ISD::SETCC) {
5685     EVT VT = N->getValueType(0);
5686
5687     // Check if any splitting is required.
5688     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5689         TargetLowering::TypeSplitVector)
5690       return SDValue();
5691
5692     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5693     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5694     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5695     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5696
5697     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5698     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5699
5700     // Add the new VSELECT nodes to the work list in case they need to be split
5701     // again.
5702     AddToWorklist(Lo.getNode());
5703     AddToWorklist(Hi.getNode());
5704
5705     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5706   }
5707
5708   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5709   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5710     return N1;
5711   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5712   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5713     return N2;
5714
5715   // The ConvertSelectToConcatVector function is assuming both the above
5716   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5717   // and addressed.
5718   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5719       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5720       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5721     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5722       return CV;
5723   }
5724
5725   return SDValue();
5726 }
5727
5728 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5729   SDValue N0 = N->getOperand(0);
5730   SDValue N1 = N->getOperand(1);
5731   SDValue N2 = N->getOperand(2);
5732   SDValue N3 = N->getOperand(3);
5733   SDValue N4 = N->getOperand(4);
5734   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5735
5736   // fold select_cc lhs, rhs, x, x, cc -> x
5737   if (N2 == N3)
5738     return N2;
5739
5740   // Determine if the condition we're dealing with is constant
5741   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5742                               N0, N1, CC, SDLoc(N), false);
5743   if (SCC.getNode()) {
5744     AddToWorklist(SCC.getNode());
5745
5746     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5747       if (!SCCC->isNullValue())
5748         return N2;    // cond always true -> true val
5749       else
5750         return N3;    // cond always false -> false val
5751     } else if (SCC->getOpcode() == ISD::UNDEF) {
5752       // When the condition is UNDEF, just return the first operand. This is
5753       // coherent the DAG creation, no setcc node is created in this case
5754       return N2;
5755     } else if (SCC.getOpcode() == ISD::SETCC) {
5756       // Fold to a simpler select_cc
5757       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5758                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5759                          SCC.getOperand(2));
5760     }
5761   }
5762
5763   // If we can fold this based on the true/false value, do so.
5764   if (SimplifySelectOps(N, N2, N3))
5765     return SDValue(N, 0);  // Don't revisit N.
5766
5767   // fold select_cc into other things, such as min/max/abs
5768   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5769 }
5770
5771 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5772   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5773                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5774                        SDLoc(N));
5775 }
5776
5777 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5778   SDValue LHS = N->getOperand(0);
5779   SDValue RHS = N->getOperand(1);
5780   SDValue Carry = N->getOperand(2);
5781   SDValue Cond = N->getOperand(3);
5782
5783   // If Carry is false, fold to a regular SETCC.
5784   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5785     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5786
5787   return SDValue();
5788 }
5789
5790 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5791 /// a build_vector of constants.
5792 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5793 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5794 /// Vector extends are not folded if operations are legal; this is to
5795 /// avoid introducing illegal build_vector dag nodes.
5796 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5797                                          SelectionDAG &DAG, bool LegalTypes,
5798                                          bool LegalOperations) {
5799   unsigned Opcode = N->getOpcode();
5800   SDValue N0 = N->getOperand(0);
5801   EVT VT = N->getValueType(0);
5802
5803   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5804          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5805          && "Expected EXTEND dag node in input!");
5806
5807   // fold (sext c1) -> c1
5808   // fold (zext c1) -> c1
5809   // fold (aext c1) -> c1
5810   if (isa<ConstantSDNode>(N0))
5811     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5812
5813   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5814   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5815   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5816   EVT SVT = VT.getScalarType();
5817   if (!(VT.isVector() &&
5818       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5819       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5820     return nullptr;
5821
5822   // We can fold this node into a build_vector.
5823   unsigned VTBits = SVT.getSizeInBits();
5824   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5825   SmallVector<SDValue, 8> Elts;
5826   unsigned NumElts = VT.getVectorNumElements();
5827   SDLoc DL(N);
5828
5829   for (unsigned i=0; i != NumElts; ++i) {
5830     SDValue Op = N0->getOperand(i);
5831     if (Op->getOpcode() == ISD::UNDEF) {
5832       Elts.push_back(DAG.getUNDEF(SVT));
5833       continue;
5834     }
5835
5836     SDLoc DL(Op);
5837     // Get the constant value and if needed trunc it to the size of the type.
5838     // Nodes like build_vector might have constants wider than the scalar type.
5839     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5840     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5841       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5842     else
5843       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5844   }
5845
5846   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5847 }
5848
5849 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5850 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5851 // transformation. Returns true if extension are possible and the above
5852 // mentioned transformation is profitable.
5853 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5854                                     unsigned ExtOpc,
5855                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5856                                     const TargetLowering &TLI) {
5857   bool HasCopyToRegUses = false;
5858   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5859   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5860                             UE = N0.getNode()->use_end();
5861        UI != UE; ++UI) {
5862     SDNode *User = *UI;
5863     if (User == N)
5864       continue;
5865     if (UI.getUse().getResNo() != N0.getResNo())
5866       continue;
5867     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5868     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5869       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5870       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5871         // Sign bits will be lost after a zext.
5872         return false;
5873       bool Add = false;
5874       for (unsigned i = 0; i != 2; ++i) {
5875         SDValue UseOp = User->getOperand(i);
5876         if (UseOp == N0)
5877           continue;
5878         if (!isa<ConstantSDNode>(UseOp))
5879           return false;
5880         Add = true;
5881       }
5882       if (Add)
5883         ExtendNodes.push_back(User);
5884       continue;
5885     }
5886     // If truncates aren't free and there are users we can't
5887     // extend, it isn't worthwhile.
5888     if (!isTruncFree)
5889       return false;
5890     // Remember if this value is live-out.
5891     if (User->getOpcode() == ISD::CopyToReg)
5892       HasCopyToRegUses = true;
5893   }
5894
5895   if (HasCopyToRegUses) {
5896     bool BothLiveOut = false;
5897     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5898          UI != UE; ++UI) {
5899       SDUse &Use = UI.getUse();
5900       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5901         BothLiveOut = true;
5902         break;
5903       }
5904     }
5905     if (BothLiveOut)
5906       // Both unextended and extended values are live out. There had better be
5907       // a good reason for the transformation.
5908       return ExtendNodes.size();
5909   }
5910   return true;
5911 }
5912
5913 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5914                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5915                                   ISD::NodeType ExtType) {
5916   // Extend SetCC uses if necessary.
5917   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5918     SDNode *SetCC = SetCCs[i];
5919     SmallVector<SDValue, 4> Ops;
5920
5921     for (unsigned j = 0; j != 2; ++j) {
5922       SDValue SOp = SetCC->getOperand(j);
5923       if (SOp == Trunc)
5924         Ops.push_back(ExtLoad);
5925       else
5926         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5927     }
5928
5929     Ops.push_back(SetCC->getOperand(2));
5930     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5931   }
5932 }
5933
5934 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5935 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5936   SDValue N0 = N->getOperand(0);
5937   EVT DstVT = N->getValueType(0);
5938   EVT SrcVT = N0.getValueType();
5939
5940   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5941           N->getOpcode() == ISD::ZERO_EXTEND) &&
5942          "Unexpected node type (not an extend)!");
5943
5944   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5945   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5946   //   (v8i32 (sext (v8i16 (load x))))
5947   // into:
5948   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5949   //                          (v4i32 (sextload (x + 16)))))
5950   // Where uses of the original load, i.e.:
5951   //   (v8i16 (load x))
5952   // are replaced with:
5953   //   (v8i16 (truncate
5954   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5955   //                            (v4i32 (sextload (x + 16)))))))
5956   //
5957   // This combine is only applicable to illegal, but splittable, vectors.
5958   // All legal types, and illegal non-vector types, are handled elsewhere.
5959   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5960   //
5961   if (N0->getOpcode() != ISD::LOAD)
5962     return SDValue();
5963
5964   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5965
5966   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5967       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5968       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5969     return SDValue();
5970
5971   SmallVector<SDNode *, 4> SetCCs;
5972   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5973     return SDValue();
5974
5975   ISD::LoadExtType ExtType =
5976       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5977
5978   // Try to split the vector types to get down to legal types.
5979   EVT SplitSrcVT = SrcVT;
5980   EVT SplitDstVT = DstVT;
5981   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5982          SplitSrcVT.getVectorNumElements() > 1) {
5983     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5984     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5985   }
5986
5987   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5988     return SDValue();
5989
5990   SDLoc DL(N);
5991   const unsigned NumSplits =
5992       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5993   const unsigned Stride = SplitSrcVT.getStoreSize();
5994   SmallVector<SDValue, 4> Loads;
5995   SmallVector<SDValue, 4> Chains;
5996
5997   SDValue BasePtr = LN0->getBasePtr();
5998   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5999     const unsigned Offset = Idx * Stride;
6000     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6001
6002     SDValue SplitLoad = DAG.getExtLoad(
6003         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6004         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
6005         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
6006         Align, LN0->getAAInfo());
6007
6008     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6009                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6010
6011     Loads.push_back(SplitLoad.getValue(0));
6012     Chains.push_back(SplitLoad.getValue(1));
6013   }
6014
6015   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6016   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6017
6018   CombineTo(N, NewValue);
6019
6020   // Replace uses of the original load (before extension)
6021   // with a truncate of the concatenated sextloaded vectors.
6022   SDValue Trunc =
6023       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6024   CombineTo(N0.getNode(), Trunc, NewChain);
6025   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6026                   (ISD::NodeType)N->getOpcode());
6027   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6028 }
6029
6030 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6031   SDValue N0 = N->getOperand(0);
6032   EVT VT = N->getValueType(0);
6033
6034   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6035                                               LegalOperations))
6036     return SDValue(Res, 0);
6037
6038   // fold (sext (sext x)) -> (sext x)
6039   // fold (sext (aext x)) -> (sext x)
6040   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6041     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6042                        N0.getOperand(0));
6043
6044   if (N0.getOpcode() == ISD::TRUNCATE) {
6045     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6046     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6047     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6048       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6049       if (NarrowLoad.getNode() != N0.getNode()) {
6050         CombineTo(N0.getNode(), NarrowLoad);
6051         // CombineTo deleted the truncate, if needed, but not what's under it.
6052         AddToWorklist(oye);
6053       }
6054       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6055     }
6056
6057     // See if the value being truncated is already sign extended.  If so, just
6058     // eliminate the trunc/sext pair.
6059     SDValue Op = N0.getOperand(0);
6060     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6061     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6062     unsigned DestBits = VT.getScalarType().getSizeInBits();
6063     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6064
6065     if (OpBits == DestBits) {
6066       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6067       // bits, it is already ready.
6068       if (NumSignBits > DestBits-MidBits)
6069         return Op;
6070     } else if (OpBits < DestBits) {
6071       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6072       // bits, just sext from i32.
6073       if (NumSignBits > OpBits-MidBits)
6074         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6075     } else {
6076       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6077       // bits, just truncate to i32.
6078       if (NumSignBits > OpBits-MidBits)
6079         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6080     }
6081
6082     // fold (sext (truncate x)) -> (sextinreg x).
6083     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6084                                                  N0.getValueType())) {
6085       if (OpBits < DestBits)
6086         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6087       else if (OpBits > DestBits)
6088         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6089       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6090                          DAG.getValueType(N0.getValueType()));
6091     }
6092   }
6093
6094   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6095   // Only generate vector extloads when 1) they're legal, and 2) they are
6096   // deemed desirable by the target.
6097   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6098       ((!LegalOperations && !VT.isVector() &&
6099         !cast<LoadSDNode>(N0)->isVolatile()) ||
6100        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6101     bool DoXform = true;
6102     SmallVector<SDNode*, 4> SetCCs;
6103     if (!N0.hasOneUse())
6104       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6105     if (VT.isVector())
6106       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6107     if (DoXform) {
6108       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6109       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6110                                        LN0->getChain(),
6111                                        LN0->getBasePtr(), N0.getValueType(),
6112                                        LN0->getMemOperand());
6113       CombineTo(N, ExtLoad);
6114       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6115                                   N0.getValueType(), ExtLoad);
6116       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6117       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6118                       ISD::SIGN_EXTEND);
6119       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6120     }
6121   }
6122
6123   // fold (sext (load x)) to multiple smaller sextloads.
6124   // Only on illegal but splittable vectors.
6125   if (SDValue ExtLoad = CombineExtLoad(N))
6126     return ExtLoad;
6127
6128   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6129   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6130   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6131       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6132     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6133     EVT MemVT = LN0->getMemoryVT();
6134     if ((!LegalOperations && !LN0->isVolatile()) ||
6135         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6136       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6137                                        LN0->getChain(),
6138                                        LN0->getBasePtr(), MemVT,
6139                                        LN0->getMemOperand());
6140       CombineTo(N, ExtLoad);
6141       CombineTo(N0.getNode(),
6142                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6143                             N0.getValueType(), ExtLoad),
6144                 ExtLoad.getValue(1));
6145       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6146     }
6147   }
6148
6149   // fold (sext (and/or/xor (load x), cst)) ->
6150   //      (and/or/xor (sextload x), (sext cst))
6151   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6152        N0.getOpcode() == ISD::XOR) &&
6153       isa<LoadSDNode>(N0.getOperand(0)) &&
6154       N0.getOperand(1).getOpcode() == ISD::Constant &&
6155       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6156       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6157     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6158     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6159       bool DoXform = true;
6160       SmallVector<SDNode*, 4> SetCCs;
6161       if (!N0.hasOneUse())
6162         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6163                                           SetCCs, TLI);
6164       if (DoXform) {
6165         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6166                                          LN0->getChain(), LN0->getBasePtr(),
6167                                          LN0->getMemoryVT(),
6168                                          LN0->getMemOperand());
6169         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6170         Mask = Mask.sext(VT.getSizeInBits());
6171         SDLoc DL(N);
6172         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6173                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6174         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6175                                     SDLoc(N0.getOperand(0)),
6176                                     N0.getOperand(0).getValueType(), ExtLoad);
6177         CombineTo(N, And);
6178         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6179         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6180                         ISD::SIGN_EXTEND);
6181         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6182       }
6183     }
6184   }
6185
6186   if (N0.getOpcode() == ISD::SETCC) {
6187     EVT N0VT = N0.getOperand(0).getValueType();
6188     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6189     // Only do this before legalize for now.
6190     if (VT.isVector() && !LegalOperations &&
6191         TLI.getBooleanContents(N0VT) ==
6192             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6193       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6194       // of the same size as the compared operands. Only optimize sext(setcc())
6195       // if this is the case.
6196       EVT SVT = getSetCCResultType(N0VT);
6197
6198       // We know that the # elements of the results is the same as the
6199       // # elements of the compare (and the # elements of the compare result
6200       // for that matter).  Check to see that they are the same size.  If so,
6201       // we know that the element size of the sext'd result matches the
6202       // element size of the compare operands.
6203       if (VT.getSizeInBits() == SVT.getSizeInBits())
6204         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6205                              N0.getOperand(1),
6206                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6207
6208       // If the desired elements are smaller or larger than the source
6209       // elements we can use a matching integer vector type and then
6210       // truncate/sign extend
6211       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6212       if (SVT == MatchingVectorType) {
6213         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6214                                N0.getOperand(0), N0.getOperand(1),
6215                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6216         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6217       }
6218     }
6219
6220     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6221     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6222     SDLoc DL(N);
6223     SDValue NegOne =
6224       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6225     SDValue SCC =
6226       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6227                        NegOne, DAG.getConstant(0, DL, VT),
6228                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6229     if (SCC.getNode()) return SCC;
6230
6231     if (!VT.isVector()) {
6232       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6233       if (!LegalOperations ||
6234           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6235         SDLoc DL(N);
6236         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6237         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6238                                      N0.getOperand(0), N0.getOperand(1), CC);
6239         return DAG.getSelect(DL, VT, SetCC,
6240                              NegOne, DAG.getConstant(0, DL, VT));
6241       }
6242     }
6243   }
6244
6245   // fold (sext x) -> (zext x) if the sign bit is known zero.
6246   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6247       DAG.SignBitIsZero(N0))
6248     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6249
6250   return SDValue();
6251 }
6252
6253 // isTruncateOf - If N is a truncate of some other value, return true, record
6254 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6255 // This function computes KnownZero to avoid a duplicated call to
6256 // computeKnownBits in the caller.
6257 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6258                          APInt &KnownZero) {
6259   APInt KnownOne;
6260   if (N->getOpcode() == ISD::TRUNCATE) {
6261     Op = N->getOperand(0);
6262     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6263     return true;
6264   }
6265
6266   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6267       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6268     return false;
6269
6270   SDValue Op0 = N->getOperand(0);
6271   SDValue Op1 = N->getOperand(1);
6272   assert(Op0.getValueType() == Op1.getValueType());
6273
6274   if (isNullConstant(Op0))
6275     Op = Op1;
6276   else if (isNullConstant(Op1))
6277     Op = Op0;
6278   else
6279     return false;
6280
6281   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6282
6283   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6284     return false;
6285
6286   return true;
6287 }
6288
6289 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6290   SDValue N0 = N->getOperand(0);
6291   EVT VT = N->getValueType(0);
6292
6293   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6294                                               LegalOperations))
6295     return SDValue(Res, 0);
6296
6297   // fold (zext (zext x)) -> (zext x)
6298   // fold (zext (aext x)) -> (zext x)
6299   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6300     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6301                        N0.getOperand(0));
6302
6303   // fold (zext (truncate x)) -> (zext x) or
6304   //      (zext (truncate x)) -> (truncate x)
6305   // This is valid when the truncated bits of x are already zero.
6306   // FIXME: We should extend this to work for vectors too.
6307   SDValue Op;
6308   APInt KnownZero;
6309   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6310     APInt TruncatedBits =
6311       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6312       APInt(Op.getValueSizeInBits(), 0) :
6313       APInt::getBitsSet(Op.getValueSizeInBits(),
6314                         N0.getValueSizeInBits(),
6315                         std::min(Op.getValueSizeInBits(),
6316                                  VT.getSizeInBits()));
6317     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6318       if (VT.bitsGT(Op.getValueType()))
6319         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6320       if (VT.bitsLT(Op.getValueType()))
6321         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6322
6323       return Op;
6324     }
6325   }
6326
6327   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6328   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6329   if (N0.getOpcode() == ISD::TRUNCATE) {
6330     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6331       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6332       if (NarrowLoad.getNode() != N0.getNode()) {
6333         CombineTo(N0.getNode(), NarrowLoad);
6334         // CombineTo deleted the truncate, if needed, but not what's under it.
6335         AddToWorklist(oye);
6336       }
6337       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6338     }
6339   }
6340
6341   // fold (zext (truncate x)) -> (and x, mask)
6342   if (N0.getOpcode() == ISD::TRUNCATE) {
6343     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6344     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6345     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6346       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6347       if (NarrowLoad.getNode() != N0.getNode()) {
6348         CombineTo(N0.getNode(), NarrowLoad);
6349         // CombineTo deleted the truncate, if needed, but not what's under it.
6350         AddToWorklist(oye);
6351       }
6352       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6353     }
6354
6355     EVT SrcVT = N0.getOperand(0).getValueType();
6356     EVT MinVT = N0.getValueType();
6357
6358     // Try to mask before the extension to avoid having to generate a larger mask,
6359     // possibly over several sub-vectors.
6360     if (SrcVT.bitsLT(VT)) {
6361       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6362                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6363         SDValue Op = N0.getOperand(0);
6364         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6365         AddToWorklist(Op.getNode());
6366         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6367       }
6368     }
6369
6370     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6371       SDValue Op = N0.getOperand(0);
6372       if (SrcVT.bitsLT(VT)) {
6373         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6374         AddToWorklist(Op.getNode());
6375       } else if (SrcVT.bitsGT(VT)) {
6376         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6377         AddToWorklist(Op.getNode());
6378       }
6379       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6380     }
6381   }
6382
6383   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6384   // if either of the casts is not free.
6385   if (N0.getOpcode() == ISD::AND &&
6386       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6387       N0.getOperand(1).getOpcode() == ISD::Constant &&
6388       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6389                            N0.getValueType()) ||
6390        !TLI.isZExtFree(N0.getValueType(), VT))) {
6391     SDValue X = N0.getOperand(0).getOperand(0);
6392     if (X.getValueType().bitsLT(VT)) {
6393       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6394     } else if (X.getValueType().bitsGT(VT)) {
6395       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6396     }
6397     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6398     Mask = Mask.zext(VT.getSizeInBits());
6399     SDLoc DL(N);
6400     return DAG.getNode(ISD::AND, DL, VT,
6401                        X, DAG.getConstant(Mask, DL, VT));
6402   }
6403
6404   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6405   // Only generate vector extloads when 1) they're legal, and 2) they are
6406   // deemed desirable by the target.
6407   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6408       ((!LegalOperations && !VT.isVector() &&
6409         !cast<LoadSDNode>(N0)->isVolatile()) ||
6410        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6411     bool DoXform = true;
6412     SmallVector<SDNode*, 4> SetCCs;
6413     if (!N0.hasOneUse())
6414       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6415     if (VT.isVector())
6416       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6417     if (DoXform) {
6418       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6419       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6420                                        LN0->getChain(),
6421                                        LN0->getBasePtr(), N0.getValueType(),
6422                                        LN0->getMemOperand());
6423       CombineTo(N, ExtLoad);
6424       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6425                                   N0.getValueType(), ExtLoad);
6426       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6427
6428       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6429                       ISD::ZERO_EXTEND);
6430       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6431     }
6432   }
6433
6434   // fold (zext (load x)) to multiple smaller zextloads.
6435   // Only on illegal but splittable vectors.
6436   if (SDValue ExtLoad = CombineExtLoad(N))
6437     return ExtLoad;
6438
6439   // fold (zext (and/or/xor (load x), cst)) ->
6440   //      (and/or/xor (zextload x), (zext cst))
6441   // Unless (and (load x) cst) will match as a zextload already and has
6442   // additional users.
6443   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6444        N0.getOpcode() == ISD::XOR) &&
6445       isa<LoadSDNode>(N0.getOperand(0)) &&
6446       N0.getOperand(1).getOpcode() == ISD::Constant &&
6447       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6448       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6449     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6450     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6451       bool DoXform = true;
6452       SmallVector<SDNode*, 4> SetCCs;
6453       if (!N0.hasOneUse()) {
6454         if (N0.getOpcode() == ISD::AND) {
6455           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6456           auto NarrowLoad = false;
6457           EVT LoadResultTy = AndC->getValueType(0);
6458           EVT ExtVT, LoadedVT;
6459           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6460                                NarrowLoad))
6461             DoXform = false;
6462         }
6463         if (DoXform)
6464           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6465                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6466       }
6467       if (DoXform) {
6468         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6469                                          LN0->getChain(), LN0->getBasePtr(),
6470                                          LN0->getMemoryVT(),
6471                                          LN0->getMemOperand());
6472         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6473         Mask = Mask.zext(VT.getSizeInBits());
6474         SDLoc DL(N);
6475         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6476                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6477         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6478                                     SDLoc(N0.getOperand(0)),
6479                                     N0.getOperand(0).getValueType(), ExtLoad);
6480         CombineTo(N, And);
6481         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6482         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6483                         ISD::ZERO_EXTEND);
6484         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6485       }
6486     }
6487   }
6488
6489   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6490   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6491   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6492       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6493     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6494     EVT MemVT = LN0->getMemoryVT();
6495     if ((!LegalOperations && !LN0->isVolatile()) ||
6496         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6497       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6498                                        LN0->getChain(),
6499                                        LN0->getBasePtr(), MemVT,
6500                                        LN0->getMemOperand());
6501       CombineTo(N, ExtLoad);
6502       CombineTo(N0.getNode(),
6503                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6504                             ExtLoad),
6505                 ExtLoad.getValue(1));
6506       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6507     }
6508   }
6509
6510   if (N0.getOpcode() == ISD::SETCC) {
6511     if (!LegalOperations && VT.isVector() &&
6512         N0.getValueType().getVectorElementType() == MVT::i1) {
6513       EVT N0VT = N0.getOperand(0).getValueType();
6514       if (getSetCCResultType(N0VT) == N0.getValueType())
6515         return SDValue();
6516
6517       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6518       // Only do this before legalize for now.
6519       EVT EltVT = VT.getVectorElementType();
6520       SDLoc DL(N);
6521       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6522                                     DAG.getConstant(1, DL, EltVT));
6523       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6524         // We know that the # elements of the results is the same as the
6525         // # elements of the compare (and the # elements of the compare result
6526         // for that matter).  Check to see that they are the same size.  If so,
6527         // we know that the element size of the sext'd result matches the
6528         // element size of the compare operands.
6529         return DAG.getNode(ISD::AND, DL, VT,
6530                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6531                                          N0.getOperand(1),
6532                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6533                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6534                                        OneOps));
6535
6536       // If the desired elements are smaller or larger than the source
6537       // elements we can use a matching integer vector type and then
6538       // truncate/sign extend
6539       EVT MatchingElementType =
6540         EVT::getIntegerVT(*DAG.getContext(),
6541                           N0VT.getScalarType().getSizeInBits());
6542       EVT MatchingVectorType =
6543         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6544                          N0VT.getVectorNumElements());
6545       SDValue VsetCC =
6546         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6547                       N0.getOperand(1),
6548                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6549       return DAG.getNode(ISD::AND, DL, VT,
6550                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6551                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6552     }
6553
6554     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6555     SDLoc DL(N);
6556     SDValue SCC =
6557       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6558                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6559                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6560     if (SCC.getNode()) return SCC;
6561   }
6562
6563   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6564   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6565       isa<ConstantSDNode>(N0.getOperand(1)) &&
6566       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6567       N0.hasOneUse()) {
6568     SDValue ShAmt = N0.getOperand(1);
6569     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6570     if (N0.getOpcode() == ISD::SHL) {
6571       SDValue InnerZExt = N0.getOperand(0);
6572       // If the original shl may be shifting out bits, do not perform this
6573       // transformation.
6574       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6575         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6576       if (ShAmtVal > KnownZeroBits)
6577         return SDValue();
6578     }
6579
6580     SDLoc DL(N);
6581
6582     // Ensure that the shift amount is wide enough for the shifted value.
6583     if (VT.getSizeInBits() >= 256)
6584       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6585
6586     return DAG.getNode(N0.getOpcode(), DL, VT,
6587                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6588                        ShAmt);
6589   }
6590
6591   return SDValue();
6592 }
6593
6594 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6595   SDValue N0 = N->getOperand(0);
6596   EVT VT = N->getValueType(0);
6597
6598   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6599                                               LegalOperations))
6600     return SDValue(Res, 0);
6601
6602   // fold (aext (aext x)) -> (aext x)
6603   // fold (aext (zext x)) -> (zext x)
6604   // fold (aext (sext x)) -> (sext x)
6605   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6606       N0.getOpcode() == ISD::ZERO_EXTEND ||
6607       N0.getOpcode() == ISD::SIGN_EXTEND)
6608     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6609
6610   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6611   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6612   if (N0.getOpcode() == ISD::TRUNCATE) {
6613     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6614       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6615       if (NarrowLoad.getNode() != N0.getNode()) {
6616         CombineTo(N0.getNode(), NarrowLoad);
6617         // CombineTo deleted the truncate, if needed, but not what's under it.
6618         AddToWorklist(oye);
6619       }
6620       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6621     }
6622   }
6623
6624   // fold (aext (truncate x))
6625   if (N0.getOpcode() == ISD::TRUNCATE) {
6626     SDValue TruncOp = N0.getOperand(0);
6627     if (TruncOp.getValueType() == VT)
6628       return TruncOp; // x iff x size == zext size.
6629     if (TruncOp.getValueType().bitsGT(VT))
6630       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6631     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6632   }
6633
6634   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6635   // if the trunc is not free.
6636   if (N0.getOpcode() == ISD::AND &&
6637       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6638       N0.getOperand(1).getOpcode() == ISD::Constant &&
6639       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6640                           N0.getValueType())) {
6641     SDValue X = N0.getOperand(0).getOperand(0);
6642     if (X.getValueType().bitsLT(VT)) {
6643       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6644     } else if (X.getValueType().bitsGT(VT)) {
6645       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6646     }
6647     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6648     Mask = Mask.zext(VT.getSizeInBits());
6649     SDLoc DL(N);
6650     return DAG.getNode(ISD::AND, DL, VT,
6651                        X, DAG.getConstant(Mask, DL, VT));
6652   }
6653
6654   // fold (aext (load x)) -> (aext (truncate (extload x)))
6655   // None of the supported targets knows how to perform load and any_ext
6656   // on vectors in one instruction.  We only perform this transformation on
6657   // scalars.
6658   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6659       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6660       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6661     bool DoXform = true;
6662     SmallVector<SDNode*, 4> SetCCs;
6663     if (!N0.hasOneUse())
6664       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6665     if (DoXform) {
6666       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6667       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6668                                        LN0->getChain(),
6669                                        LN0->getBasePtr(), N0.getValueType(),
6670                                        LN0->getMemOperand());
6671       CombineTo(N, ExtLoad);
6672       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6673                                   N0.getValueType(), ExtLoad);
6674       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6675       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6676                       ISD::ANY_EXTEND);
6677       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6678     }
6679   }
6680
6681   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6682   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6683   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6684   if (N0.getOpcode() == ISD::LOAD &&
6685       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6686       N0.hasOneUse()) {
6687     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6688     ISD::LoadExtType ExtType = LN0->getExtensionType();
6689     EVT MemVT = LN0->getMemoryVT();
6690     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6691       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6692                                        VT, LN0->getChain(), LN0->getBasePtr(),
6693                                        MemVT, LN0->getMemOperand());
6694       CombineTo(N, ExtLoad);
6695       CombineTo(N0.getNode(),
6696                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6697                             N0.getValueType(), ExtLoad),
6698                 ExtLoad.getValue(1));
6699       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6700     }
6701   }
6702
6703   if (N0.getOpcode() == ISD::SETCC) {
6704     // For vectors:
6705     // aext(setcc) -> vsetcc
6706     // aext(setcc) -> truncate(vsetcc)
6707     // aext(setcc) -> aext(vsetcc)
6708     // Only do this before legalize for now.
6709     if (VT.isVector() && !LegalOperations) {
6710       EVT N0VT = N0.getOperand(0).getValueType();
6711         // We know that the # elements of the results is the same as the
6712         // # elements of the compare (and the # elements of the compare result
6713         // for that matter).  Check to see that they are the same size.  If so,
6714         // we know that the element size of the sext'd result matches the
6715         // element size of the compare operands.
6716       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6717         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6718                              N0.getOperand(1),
6719                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6720       // If the desired elements are smaller or larger than the source
6721       // elements we can use a matching integer vector type and then
6722       // truncate/any extend
6723       else {
6724         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6725         SDValue VsetCC =
6726           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6727                         N0.getOperand(1),
6728                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6729         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6730       }
6731     }
6732
6733     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6734     SDLoc DL(N);
6735     SDValue SCC =
6736       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6737                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6738                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6739     if (SCC.getNode())
6740       return SCC;
6741   }
6742
6743   return SDValue();
6744 }
6745
6746 /// See if the specified operand can be simplified with the knowledge that only
6747 /// the bits specified by Mask are used.  If so, return the simpler operand,
6748 /// otherwise return a null SDValue.
6749 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6750   switch (V.getOpcode()) {
6751   default: break;
6752   case ISD::Constant: {
6753     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6754     assert(CV && "Const value should be ConstSDNode.");
6755     const APInt &CVal = CV->getAPIntValue();
6756     APInt NewVal = CVal & Mask;
6757     if (NewVal != CVal)
6758       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6759     break;
6760   }
6761   case ISD::OR:
6762   case ISD::XOR:
6763     // If the LHS or RHS don't contribute bits to the or, drop them.
6764     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6765       return V.getOperand(1);
6766     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6767       return V.getOperand(0);
6768     break;
6769   case ISD::SRL:
6770     // Only look at single-use SRLs.
6771     if (!V.getNode()->hasOneUse())
6772       break;
6773     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6774       // See if we can recursively simplify the LHS.
6775       unsigned Amt = RHSC->getZExtValue();
6776
6777       // Watch out for shift count overflow though.
6778       if (Amt >= Mask.getBitWidth()) break;
6779       APInt NewMask = Mask << Amt;
6780       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6781         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6782                            SimplifyLHS, V.getOperand(1));
6783     }
6784   }
6785   return SDValue();
6786 }
6787
6788 /// If the result of a wider load is shifted to right of N  bits and then
6789 /// truncated to a narrower type and where N is a multiple of number of bits of
6790 /// the narrower type, transform it to a narrower load from address + N / num of
6791 /// bits of new type. If the result is to be extended, also fold the extension
6792 /// to form a extending load.
6793 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6794   unsigned Opc = N->getOpcode();
6795
6796   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6797   SDValue N0 = N->getOperand(0);
6798   EVT VT = N->getValueType(0);
6799   EVT ExtVT = VT;
6800
6801   // This transformation isn't valid for vector loads.
6802   if (VT.isVector())
6803     return SDValue();
6804
6805   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6806   // extended to VT.
6807   if (Opc == ISD::SIGN_EXTEND_INREG) {
6808     ExtType = ISD::SEXTLOAD;
6809     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6810   } else if (Opc == ISD::SRL) {
6811     // Another special-case: SRL is basically zero-extending a narrower value.
6812     ExtType = ISD::ZEXTLOAD;
6813     N0 = SDValue(N, 0);
6814     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6815     if (!N01) return SDValue();
6816     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6817                               VT.getSizeInBits() - N01->getZExtValue());
6818   }
6819   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6820     return SDValue();
6821
6822   unsigned EVTBits = ExtVT.getSizeInBits();
6823
6824   // Do not generate loads of non-round integer types since these can
6825   // be expensive (and would be wrong if the type is not byte sized).
6826   if (!ExtVT.isRound())
6827     return SDValue();
6828
6829   unsigned ShAmt = 0;
6830   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6831     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6832       ShAmt = N01->getZExtValue();
6833       // Is the shift amount a multiple of size of VT?
6834       if ((ShAmt & (EVTBits-1)) == 0) {
6835         N0 = N0.getOperand(0);
6836         // Is the load width a multiple of size of VT?
6837         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6838           return SDValue();
6839       }
6840
6841       // At this point, we must have a load or else we can't do the transform.
6842       if (!isa<LoadSDNode>(N0)) return SDValue();
6843
6844       // Because a SRL must be assumed to *need* to zero-extend the high bits
6845       // (as opposed to anyext the high bits), we can't combine the zextload
6846       // lowering of SRL and an sextload.
6847       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6848         return SDValue();
6849
6850       // If the shift amount is larger than the input type then we're not
6851       // accessing any of the loaded bytes.  If the load was a zextload/extload
6852       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6853       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6854         return SDValue();
6855     }
6856   }
6857
6858   // If the load is shifted left (and the result isn't shifted back right),
6859   // we can fold the truncate through the shift.
6860   unsigned ShLeftAmt = 0;
6861   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6862       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6863     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6864       ShLeftAmt = N01->getZExtValue();
6865       N0 = N0.getOperand(0);
6866     }
6867   }
6868
6869   // If we haven't found a load, we can't narrow it.  Don't transform one with
6870   // multiple uses, this would require adding a new load.
6871   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6872     return SDValue();
6873
6874   // Don't change the width of a volatile load.
6875   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6876   if (LN0->isVolatile())
6877     return SDValue();
6878
6879   // Verify that we are actually reducing a load width here.
6880   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6881     return SDValue();
6882
6883   // For the transform to be legal, the load must produce only two values
6884   // (the value loaded and the chain).  Don't transform a pre-increment
6885   // load, for example, which produces an extra value.  Otherwise the
6886   // transformation is not equivalent, and the downstream logic to replace
6887   // uses gets things wrong.
6888   if (LN0->getNumValues() > 2)
6889     return SDValue();
6890
6891   // If the load that we're shrinking is an extload and we're not just
6892   // discarding the extension we can't simply shrink the load. Bail.
6893   // TODO: It would be possible to merge the extensions in some cases.
6894   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6895       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6896     return SDValue();
6897
6898   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6899     return SDValue();
6900
6901   EVT PtrType = N0.getOperand(1).getValueType();
6902
6903   if (PtrType == MVT::Untyped || PtrType.isExtended())
6904     // It's not possible to generate a constant of extended or untyped type.
6905     return SDValue();
6906
6907   // For big endian targets, we need to adjust the offset to the pointer to
6908   // load the correct bytes.
6909   if (DAG.getDataLayout().isBigEndian()) {
6910     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6911     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6912     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6913   }
6914
6915   uint64_t PtrOff = ShAmt / 8;
6916   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6917   SDLoc DL(LN0);
6918   // The original load itself didn't wrap, so an offset within it doesn't.
6919   SDNodeFlags Flags;
6920   Flags.setNoUnsignedWrap(true);
6921   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6922                                PtrType, LN0->getBasePtr(),
6923                                DAG.getConstant(PtrOff, DL, PtrType),
6924                                &Flags);
6925   AddToWorklist(NewPtr.getNode());
6926
6927   SDValue Load;
6928   if (ExtType == ISD::NON_EXTLOAD)
6929     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6930                         LN0->getPointerInfo().getWithOffset(PtrOff),
6931                         LN0->isVolatile(), LN0->isNonTemporal(),
6932                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6933   else
6934     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6935                           LN0->getPointerInfo().getWithOffset(PtrOff),
6936                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6937                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6938
6939   // Replace the old load's chain with the new load's chain.
6940   WorklistRemover DeadNodes(*this);
6941   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6942
6943   // Shift the result left, if we've swallowed a left shift.
6944   SDValue Result = Load;
6945   if (ShLeftAmt != 0) {
6946     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6947     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6948       ShImmTy = VT;
6949     // If the shift amount is as large as the result size (but, presumably,
6950     // no larger than the source) then the useful bits of the result are
6951     // zero; we can't simply return the shortened shift, because the result
6952     // of that operation is undefined.
6953     SDLoc DL(N0);
6954     if (ShLeftAmt >= VT.getSizeInBits())
6955       Result = DAG.getConstant(0, DL, VT);
6956     else
6957       Result = DAG.getNode(ISD::SHL, DL, VT,
6958                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6959   }
6960
6961   // Return the new loaded value.
6962   return Result;
6963 }
6964
6965 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6966   SDValue N0 = N->getOperand(0);
6967   SDValue N1 = N->getOperand(1);
6968   EVT VT = N->getValueType(0);
6969   EVT EVT = cast<VTSDNode>(N1)->getVT();
6970   unsigned VTBits = VT.getScalarType().getSizeInBits();
6971   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6972
6973   if (N0.isUndef())
6974     return DAG.getUNDEF(VT);
6975
6976   // fold (sext_in_reg c1) -> c1
6977   if (isConstantIntBuildVectorOrConstantInt(N0))
6978     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6979
6980   // If the input is already sign extended, just drop the extension.
6981   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6982     return N0;
6983
6984   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6985   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6986       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6987     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6988                        N0.getOperand(0), N1);
6989
6990   // fold (sext_in_reg (sext x)) -> (sext x)
6991   // fold (sext_in_reg (aext x)) -> (sext x)
6992   // if x is small enough.
6993   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6994     SDValue N00 = N0.getOperand(0);
6995     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6996         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6997       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6998   }
6999
7000   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7001   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7002     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
7003
7004   // fold operands of sext_in_reg based on knowledge that the top bits are not
7005   // demanded.
7006   if (SimplifyDemandedBits(SDValue(N, 0)))
7007     return SDValue(N, 0);
7008
7009   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7010   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7011   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7012     return NarrowLoad;
7013
7014   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7015   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7016   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7017   if (N0.getOpcode() == ISD::SRL) {
7018     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7019       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7020         // We can turn this into an SRA iff the input to the SRL is already sign
7021         // extended enough.
7022         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7023         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7024           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7025                              N0.getOperand(0), N0.getOperand(1));
7026       }
7027   }
7028
7029   // fold (sext_inreg (extload x)) -> (sextload x)
7030   if (ISD::isEXTLoad(N0.getNode()) &&
7031       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7032       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7033       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7034        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7035     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7036     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7037                                      LN0->getChain(),
7038                                      LN0->getBasePtr(), EVT,
7039                                      LN0->getMemOperand());
7040     CombineTo(N, ExtLoad);
7041     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7042     AddToWorklist(ExtLoad.getNode());
7043     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7044   }
7045   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7046   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7047       N0.hasOneUse() &&
7048       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7049       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7050        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7051     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7052     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7053                                      LN0->getChain(),
7054                                      LN0->getBasePtr(), EVT,
7055                                      LN0->getMemOperand());
7056     CombineTo(N, ExtLoad);
7057     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7058     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7059   }
7060
7061   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7062   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7063     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7064                                        N0.getOperand(1), false);
7065     if (BSwap.getNode())
7066       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7067                          BSwap, N1);
7068   }
7069
7070   return SDValue();
7071 }
7072
7073 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7074   SDValue N0 = N->getOperand(0);
7075   EVT VT = N->getValueType(0);
7076
7077   if (N0.getOpcode() == ISD::UNDEF)
7078     return DAG.getUNDEF(VT);
7079
7080   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7081                                               LegalOperations))
7082     return SDValue(Res, 0);
7083
7084   return SDValue();
7085 }
7086
7087 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7088   SDValue N0 = N->getOperand(0);
7089   EVT VT = N->getValueType(0);
7090   bool isLE = DAG.getDataLayout().isLittleEndian();
7091
7092   // noop truncate
7093   if (N0.getValueType() == N->getValueType(0))
7094     return N0;
7095   // fold (truncate c1) -> c1
7096   if (isConstantIntBuildVectorOrConstantInt(N0))
7097     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7098   // fold (truncate (truncate x)) -> (truncate x)
7099   if (N0.getOpcode() == ISD::TRUNCATE)
7100     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7101   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7102   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7103       N0.getOpcode() == ISD::SIGN_EXTEND ||
7104       N0.getOpcode() == ISD::ANY_EXTEND) {
7105     if (N0.getOperand(0).getValueType().bitsLT(VT))
7106       // if the source is smaller than the dest, we still need an extend
7107       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7108                          N0.getOperand(0));
7109     if (N0.getOperand(0).getValueType().bitsGT(VT))
7110       // if the source is larger than the dest, than we just need the truncate
7111       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7112     // if the source and dest are the same type, we can drop both the extend
7113     // and the truncate.
7114     return N0.getOperand(0);
7115   }
7116
7117   // Fold extract-and-trunc into a narrow extract. For example:
7118   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7119   //   i32 y = TRUNCATE(i64 x)
7120   //        -- becomes --
7121   //   v16i8 b = BITCAST (v2i64 val)
7122   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7123   //
7124   // Note: We only run this optimization after type legalization (which often
7125   // creates this pattern) and before operation legalization after which
7126   // we need to be more careful about the vector instructions that we generate.
7127   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7128       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7129
7130     EVT VecTy = N0.getOperand(0).getValueType();
7131     EVT ExTy = N0.getValueType();
7132     EVT TrTy = N->getValueType(0);
7133
7134     unsigned NumElem = VecTy.getVectorNumElements();
7135     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7136
7137     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7138     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7139
7140     SDValue EltNo = N0->getOperand(1);
7141     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7142       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7143       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7144       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7145
7146       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7147                               NVT, N0.getOperand(0));
7148
7149       SDLoc DL(N);
7150       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7151                          DL, TrTy, V,
7152                          DAG.getConstant(Index, DL, IndexTy));
7153     }
7154   }
7155
7156   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7157   if (N0.getOpcode() == ISD::SELECT) {
7158     EVT SrcVT = N0.getValueType();
7159     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7160         TLI.isTruncateFree(SrcVT, VT)) {
7161       SDLoc SL(N0);
7162       SDValue Cond = N0.getOperand(0);
7163       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7164       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7165       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7166     }
7167   }
7168
7169   // Fold a series of buildvector, bitcast, and truncate if possible.
7170   // For example fold
7171   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7172   //   (2xi32 (buildvector x, y)).
7173   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7174       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7175       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7176       N0.getOperand(0).hasOneUse()) {
7177
7178     SDValue BuildVect = N0.getOperand(0);
7179     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7180     EVT TruncVecEltTy = VT.getVectorElementType();
7181
7182     // Check that the element types match.
7183     if (BuildVectEltTy == TruncVecEltTy) {
7184       // Now we only need to compute the offset of the truncated elements.
7185       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7186       unsigned TruncVecNumElts = VT.getVectorNumElements();
7187       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7188
7189       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7190              "Invalid number of elements");
7191
7192       SmallVector<SDValue, 8> Opnds;
7193       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7194         Opnds.push_back(BuildVect.getOperand(i));
7195
7196       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7197     }
7198   }
7199
7200   // See if we can simplify the input to this truncate through knowledge that
7201   // only the low bits are being used.
7202   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7203   // Currently we only perform this optimization on scalars because vectors
7204   // may have different active low bits.
7205   if (!VT.isVector()) {
7206     SDValue Shorter =
7207       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7208                                                VT.getSizeInBits()));
7209     if (Shorter.getNode())
7210       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7211   }
7212   // fold (truncate (load x)) -> (smaller load x)
7213   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7214   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7215     if (SDValue Reduced = ReduceLoadWidth(N))
7216       return Reduced;
7217
7218     // Handle the case where the load remains an extending load even
7219     // after truncation.
7220     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7221       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7222       if (!LN0->isVolatile() &&
7223           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7224         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7225                                          VT, LN0->getChain(), LN0->getBasePtr(),
7226                                          LN0->getMemoryVT(),
7227                                          LN0->getMemOperand());
7228         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7229         return NewLoad;
7230       }
7231     }
7232   }
7233   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7234   // where ... are all 'undef'.
7235   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7236     SmallVector<EVT, 8> VTs;
7237     SDValue V;
7238     unsigned Idx = 0;
7239     unsigned NumDefs = 0;
7240
7241     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7242       SDValue X = N0.getOperand(i);
7243       if (X.getOpcode() != ISD::UNDEF) {
7244         V = X;
7245         Idx = i;
7246         NumDefs++;
7247       }
7248       // Stop if more than one members are non-undef.
7249       if (NumDefs > 1)
7250         break;
7251       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7252                                      VT.getVectorElementType(),
7253                                      X.getValueType().getVectorNumElements()));
7254     }
7255
7256     if (NumDefs == 0)
7257       return DAG.getUNDEF(VT);
7258
7259     if (NumDefs == 1) {
7260       assert(V.getNode() && "The single defined operand is empty!");
7261       SmallVector<SDValue, 8> Opnds;
7262       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7263         if (i != Idx) {
7264           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7265           continue;
7266         }
7267         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7268         AddToWorklist(NV.getNode());
7269         Opnds.push_back(NV);
7270       }
7271       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7272     }
7273   }
7274
7275   // Simplify the operands using demanded-bits information.
7276   if (!VT.isVector() &&
7277       SimplifyDemandedBits(SDValue(N, 0)))
7278     return SDValue(N, 0);
7279
7280   return SDValue();
7281 }
7282
7283 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7284   SDValue Elt = N->getOperand(i);
7285   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7286     return Elt.getNode();
7287   return Elt.getOperand(Elt.getResNo()).getNode();
7288 }
7289
7290 /// build_pair (load, load) -> load
7291 /// if load locations are consecutive.
7292 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7293   assert(N->getOpcode() == ISD::BUILD_PAIR);
7294
7295   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7296   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7297   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7298       LD1->getAddressSpace() != LD2->getAddressSpace())
7299     return SDValue();
7300   EVT LD1VT = LD1->getValueType(0);
7301
7302   if (ISD::isNON_EXTLoad(LD2) &&
7303       LD2->hasOneUse() &&
7304       // If both are volatile this would reduce the number of volatile loads.
7305       // If one is volatile it might be ok, but play conservative and bail out.
7306       !LD1->isVolatile() &&
7307       !LD2->isVolatile() &&
7308       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7309     unsigned Align = LD1->getAlignment();
7310     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7311         VT.getTypeForEVT(*DAG.getContext()));
7312
7313     if (NewAlign <= Align &&
7314         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7315       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7316                          LD1->getBasePtr(), LD1->getPointerInfo(),
7317                          false, false, false, Align);
7318   }
7319
7320   return SDValue();
7321 }
7322
7323 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7324   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7325   // and Lo parts; on big-endian machines it doesn't.
7326   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7327 }
7328
7329 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7330   SDValue N0 = N->getOperand(0);
7331   EVT VT = N->getValueType(0);
7332
7333   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7334   // Only do this before legalize, since afterward the target may be depending
7335   // on the bitconvert.
7336   // First check to see if this is all constant.
7337   if (!LegalTypes &&
7338       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7339       VT.isVector()) {
7340     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7341
7342     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7343     assert(!DestEltVT.isVector() &&
7344            "Element type of vector ValueType must not be vector!");
7345     if (isSimple)
7346       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7347   }
7348
7349   // If the input is a constant, let getNode fold it.
7350   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7351     // If we can't allow illegal operations, we need to check that this is just
7352     // a fp -> int or int -> conversion and that the resulting operation will
7353     // be legal.
7354     if (!LegalOperations ||
7355         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7356          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7357         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7358          TLI.isOperationLegal(ISD::Constant, VT)))
7359       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7360   }
7361
7362   // (conv (conv x, t1), t2) -> (conv x, t2)
7363   if (N0.getOpcode() == ISD::BITCAST)
7364     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7365                        N0.getOperand(0));
7366
7367   // fold (conv (load x)) -> (load (conv*)x)
7368   // If the resultant load doesn't need a higher alignment than the original!
7369   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7370       // Do not change the width of a volatile load.
7371       !cast<LoadSDNode>(N0)->isVolatile() &&
7372       // Do not remove the cast if the types differ in endian layout.
7373       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7374           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7375       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7376       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7377     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7378     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7379         VT.getTypeForEVT(*DAG.getContext()));
7380     unsigned OrigAlign = LN0->getAlignment();
7381
7382     if (Align <= OrigAlign) {
7383       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7384                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7385                                  LN0->isVolatile(), LN0->isNonTemporal(),
7386                                  LN0->isInvariant(), OrigAlign,
7387                                  LN0->getAAInfo());
7388       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7389       return Load;
7390     }
7391   }
7392
7393   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7394   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7395   //
7396   // For ppc_fp128:
7397   // fold (bitcast (fneg x)) ->
7398   //     flipbit = signbit
7399   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7400   //
7401   // fold (bitcast (fabs x)) ->
7402   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7403   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7404   // This often reduces constant pool loads.
7405   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7406        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7407       N0.getNode()->hasOneUse() && VT.isInteger() &&
7408       !VT.isVector() && !N0.getValueType().isVector()) {
7409     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7410                                   N0.getOperand(0));
7411     AddToWorklist(NewConv.getNode());
7412
7413     SDLoc DL(N);
7414     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7415       assert(VT.getSizeInBits() == 128);
7416       SDValue SignBit = DAG.getConstant(
7417           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7418       SDValue FlipBit;
7419       if (N0.getOpcode() == ISD::FNEG) {
7420         FlipBit = SignBit;
7421         AddToWorklist(FlipBit.getNode());
7422       } else {
7423         assert(N0.getOpcode() == ISD::FABS);
7424         SDValue Hi =
7425             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7426                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7427                                               SDLoc(NewConv)));
7428         AddToWorklist(Hi.getNode());
7429         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7430         AddToWorklist(FlipBit.getNode());
7431       }
7432       SDValue FlipBits =
7433           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7434       AddToWorklist(FlipBits.getNode());
7435       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7436     }
7437     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7438     if (N0.getOpcode() == ISD::FNEG)
7439       return DAG.getNode(ISD::XOR, DL, VT,
7440                          NewConv, DAG.getConstant(SignBit, DL, VT));
7441     assert(N0.getOpcode() == ISD::FABS);
7442     return DAG.getNode(ISD::AND, DL, VT,
7443                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7444   }
7445
7446   // fold (bitconvert (fcopysign cst, x)) ->
7447   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7448   // Note that we don't handle (copysign x, cst) because this can always be
7449   // folded to an fneg or fabs.
7450   //
7451   // For ppc_fp128:
7452   // fold (bitcast (fcopysign cst, x)) ->
7453   //     flipbit = (and (extract_element
7454   //                     (xor (bitcast cst), (bitcast x)), 0),
7455   //                    signbit)
7456   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7457   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7458       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7459       VT.isInteger() && !VT.isVector()) {
7460     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7461     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7462     if (isTypeLegal(IntXVT)) {
7463       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7464                               IntXVT, N0.getOperand(1));
7465       AddToWorklist(X.getNode());
7466
7467       // If X has a different width than the result/lhs, sext it or truncate it.
7468       unsigned VTWidth = VT.getSizeInBits();
7469       if (OrigXWidth < VTWidth) {
7470         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7471         AddToWorklist(X.getNode());
7472       } else if (OrigXWidth > VTWidth) {
7473         // To get the sign bit in the right place, we have to shift it right
7474         // before truncating.
7475         SDLoc DL(X);
7476         X = DAG.getNode(ISD::SRL, DL,
7477                         X.getValueType(), X,
7478                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7479                                         X.getValueType()));
7480         AddToWorklist(X.getNode());
7481         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7482         AddToWorklist(X.getNode());
7483       }
7484
7485       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7486         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7487         SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(0)), VT,
7488                                   N0.getOperand(0));
7489         AddToWorklist(Cst.getNode());
7490         SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(1)), VT,
7491                                 N0.getOperand(1));
7492         AddToWorklist(X.getNode());
7493         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7494         AddToWorklist(XorResult.getNode());
7495         SDValue XorResult64 = DAG.getNode(
7496             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7497             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7498                                   SDLoc(XorResult)));
7499         AddToWorklist(XorResult64.getNode());
7500         SDValue FlipBit =
7501             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7502                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7503         AddToWorklist(FlipBit.getNode());
7504         SDValue FlipBits =
7505             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7506         AddToWorklist(FlipBits.getNode());
7507         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7508       }
7509       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7510       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7511                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7512       AddToWorklist(X.getNode());
7513
7514       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7515                                 VT, N0.getOperand(0));
7516       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7517                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7518       AddToWorklist(Cst.getNode());
7519
7520       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7521     }
7522   }
7523
7524   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7525   if (N0.getOpcode() == ISD::BUILD_PAIR)
7526     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7527       return CombineLD;
7528
7529   // Remove double bitcasts from shuffles - this is often a legacy of
7530   // XformToShuffleWithZero being used to combine bitmaskings (of
7531   // float vectors bitcast to integer vectors) into shuffles.
7532   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7533   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7534       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7535       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7536       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7537     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7538
7539     // If operands are a bitcast, peek through if it casts the original VT.
7540     // If operands are a constant, just bitcast back to original VT.
7541     auto PeekThroughBitcast = [&](SDValue Op) {
7542       if (Op.getOpcode() == ISD::BITCAST &&
7543           Op.getOperand(0).getValueType() == VT)
7544         return SDValue(Op.getOperand(0));
7545       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7546           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7547         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7548       return SDValue();
7549     };
7550
7551     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7552     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7553     if (!(SV0 && SV1))
7554       return SDValue();
7555
7556     int MaskScale =
7557         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7558     SmallVector<int, 8> NewMask;
7559     for (int M : SVN->getMask())
7560       for (int i = 0; i != MaskScale; ++i)
7561         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7562
7563     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7564     if (!LegalMask) {
7565       std::swap(SV0, SV1);
7566       ShuffleVectorSDNode::commuteMask(NewMask);
7567       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7568     }
7569
7570     if (LegalMask)
7571       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7572   }
7573
7574   return SDValue();
7575 }
7576
7577 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7578   EVT VT = N->getValueType(0);
7579   return CombineConsecutiveLoads(N, VT);
7580 }
7581
7582 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7583 /// operands. DstEltVT indicates the destination element value type.
7584 SDValue DAGCombiner::
7585 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7586   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7587
7588   // If this is already the right type, we're done.
7589   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7590
7591   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7592   unsigned DstBitSize = DstEltVT.getSizeInBits();
7593
7594   // If this is a conversion of N elements of one type to N elements of another
7595   // type, convert each element.  This handles FP<->INT cases.
7596   if (SrcBitSize == DstBitSize) {
7597     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7598                               BV->getValueType(0).getVectorNumElements());
7599
7600     // Due to the FP element handling below calling this routine recursively,
7601     // we can end up with a scalar-to-vector node here.
7602     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7603       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7604                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7605                                      DstEltVT, BV->getOperand(0)));
7606
7607     SmallVector<SDValue, 8> Ops;
7608     for (SDValue Op : BV->op_values()) {
7609       // If the vector element type is not legal, the BUILD_VECTOR operands
7610       // are promoted and implicitly truncated.  Make that explicit here.
7611       if (Op.getValueType() != SrcEltVT)
7612         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7613       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7614                                 DstEltVT, Op));
7615       AddToWorklist(Ops.back().getNode());
7616     }
7617     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7618   }
7619
7620   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7621   // handle annoying details of growing/shrinking FP values, we convert them to
7622   // int first.
7623   if (SrcEltVT.isFloatingPoint()) {
7624     // Convert the input float vector to a int vector where the elements are the
7625     // same sizes.
7626     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7627     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7628     SrcEltVT = IntVT;
7629   }
7630
7631   // Now we know the input is an integer vector.  If the output is a FP type,
7632   // convert to integer first, then to FP of the right size.
7633   if (DstEltVT.isFloatingPoint()) {
7634     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7635     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7636
7637     // Next, convert to FP elements of the same size.
7638     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7639   }
7640
7641   SDLoc DL(BV);
7642
7643   // Okay, we know the src/dst types are both integers of differing types.
7644   // Handling growing first.
7645   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7646   if (SrcBitSize < DstBitSize) {
7647     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7648
7649     SmallVector<SDValue, 8> Ops;
7650     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7651          i += NumInputsPerOutput) {
7652       bool isLE = DAG.getDataLayout().isLittleEndian();
7653       APInt NewBits = APInt(DstBitSize, 0);
7654       bool EltIsUndef = true;
7655       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7656         // Shift the previously computed bits over.
7657         NewBits <<= SrcBitSize;
7658         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7659         if (Op.getOpcode() == ISD::UNDEF) continue;
7660         EltIsUndef = false;
7661
7662         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7663                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7664       }
7665
7666       if (EltIsUndef)
7667         Ops.push_back(DAG.getUNDEF(DstEltVT));
7668       else
7669         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7670     }
7671
7672     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7673     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7674   }
7675
7676   // Finally, this must be the case where we are shrinking elements: each input
7677   // turns into multiple outputs.
7678   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7679   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7680                             NumOutputsPerInput*BV->getNumOperands());
7681   SmallVector<SDValue, 8> Ops;
7682
7683   for (const SDValue &Op : BV->op_values()) {
7684     if (Op.getOpcode() == ISD::UNDEF) {
7685       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7686       continue;
7687     }
7688
7689     APInt OpVal = cast<ConstantSDNode>(Op)->
7690                   getAPIntValue().zextOrTrunc(SrcBitSize);
7691
7692     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7693       APInt ThisVal = OpVal.trunc(DstBitSize);
7694       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7695       OpVal = OpVal.lshr(DstBitSize);
7696     }
7697
7698     // For big endian targets, swap the order of the pieces of each element.
7699     if (DAG.getDataLayout().isBigEndian())
7700       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7701   }
7702
7703   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7704 }
7705
7706 /// Try to perform FMA combining on a given FADD node.
7707 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7708   SDValue N0 = N->getOperand(0);
7709   SDValue N1 = N->getOperand(1);
7710   EVT VT = N->getValueType(0);
7711   SDLoc SL(N);
7712
7713   const TargetOptions &Options = DAG.getTarget().Options;
7714   bool AllowFusion =
7715       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7716
7717   // Floating-point multiply-add with intermediate rounding.
7718   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7719
7720   // Floating-point multiply-add without intermediate rounding.
7721   bool HasFMA =
7722       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7723       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7724
7725   // No valid opcode, do not combine.
7726   if (!HasFMAD && !HasFMA)
7727     return SDValue();
7728
7729   // Always prefer FMAD to FMA for precision.
7730   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7731   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7732   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7733
7734   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7735   // prefer to fold the multiply with fewer uses.
7736   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7737       N1.getOpcode() == ISD::FMUL) {
7738     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7739       std::swap(N0, N1);
7740   }
7741
7742   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7743   if (N0.getOpcode() == ISD::FMUL &&
7744       (Aggressive || N0->hasOneUse())) {
7745     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746                        N0.getOperand(0), N0.getOperand(1), N1);
7747   }
7748
7749   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7750   // Note: Commutes FADD operands.
7751   if (N1.getOpcode() == ISD::FMUL &&
7752       (Aggressive || N1->hasOneUse())) {
7753     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7754                        N1.getOperand(0), N1.getOperand(1), N0);
7755   }
7756
7757   // Look through FP_EXTEND nodes to do more combining.
7758   if (AllowFusion && LookThroughFPExt) {
7759     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7760     if (N0.getOpcode() == ISD::FP_EXTEND) {
7761       SDValue N00 = N0.getOperand(0);
7762       if (N00.getOpcode() == ISD::FMUL)
7763         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                        N00.getOperand(0)),
7766                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7767                                        N00.getOperand(1)), N1);
7768     }
7769
7770     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7771     // Note: Commutes FADD operands.
7772     if (N1.getOpcode() == ISD::FP_EXTEND) {
7773       SDValue N10 = N1.getOperand(0);
7774       if (N10.getOpcode() == ISD::FMUL)
7775         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7776                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777                                        N10.getOperand(0)),
7778                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                        N10.getOperand(1)), N0);
7780     }
7781   }
7782
7783   // More folding opportunities when target permits.
7784   if ((AllowFusion || HasFMAD)  && Aggressive) {
7785     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7786     if (N0.getOpcode() == PreferredFusedOpcode &&
7787         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7788       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7789                          N0.getOperand(0), N0.getOperand(1),
7790                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7791                                      N0.getOperand(2).getOperand(0),
7792                                      N0.getOperand(2).getOperand(1),
7793                                      N1));
7794     }
7795
7796     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7797     if (N1->getOpcode() == PreferredFusedOpcode &&
7798         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7799       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7800                          N1.getOperand(0), N1.getOperand(1),
7801                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                                      N1.getOperand(2).getOperand(0),
7803                                      N1.getOperand(2).getOperand(1),
7804                                      N0));
7805     }
7806
7807     if (AllowFusion && LookThroughFPExt) {
7808       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7809       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7810       auto FoldFAddFMAFPExtFMul = [&] (
7811           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7812         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7813                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7814                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7815                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7816                                        Z));
7817       };
7818       if (N0.getOpcode() == PreferredFusedOpcode) {
7819         SDValue N02 = N0.getOperand(2);
7820         if (N02.getOpcode() == ISD::FP_EXTEND) {
7821           SDValue N020 = N02.getOperand(0);
7822           if (N020.getOpcode() == ISD::FMUL)
7823             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7824                                         N020.getOperand(0), N020.getOperand(1),
7825                                         N1);
7826         }
7827       }
7828
7829       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7830       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7831       // FIXME: This turns two single-precision and one double-precision
7832       // operation into two double-precision operations, which might not be
7833       // interesting for all targets, especially GPUs.
7834       auto FoldFAddFPExtFMAFMul = [&] (
7835           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7836         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7837                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7838                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7839                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7840                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7841                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7842                                        Z));
7843       };
7844       if (N0.getOpcode() == ISD::FP_EXTEND) {
7845         SDValue N00 = N0.getOperand(0);
7846         if (N00.getOpcode() == PreferredFusedOpcode) {
7847           SDValue N002 = N00.getOperand(2);
7848           if (N002.getOpcode() == ISD::FMUL)
7849             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7850                                         N002.getOperand(0), N002.getOperand(1),
7851                                         N1);
7852         }
7853       }
7854
7855       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7856       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7857       if (N1.getOpcode() == PreferredFusedOpcode) {
7858         SDValue N12 = N1.getOperand(2);
7859         if (N12.getOpcode() == ISD::FP_EXTEND) {
7860           SDValue N120 = N12.getOperand(0);
7861           if (N120.getOpcode() == ISD::FMUL)
7862             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7863                                         N120.getOperand(0), N120.getOperand(1),
7864                                         N0);
7865         }
7866       }
7867
7868       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7869       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7870       // FIXME: This turns two single-precision and one double-precision
7871       // operation into two double-precision operations, which might not be
7872       // interesting for all targets, especially GPUs.
7873       if (N1.getOpcode() == ISD::FP_EXTEND) {
7874         SDValue N10 = N1.getOperand(0);
7875         if (N10.getOpcode() == PreferredFusedOpcode) {
7876           SDValue N102 = N10.getOperand(2);
7877           if (N102.getOpcode() == ISD::FMUL)
7878             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7879                                         N102.getOperand(0), N102.getOperand(1),
7880                                         N0);
7881         }
7882       }
7883     }
7884   }
7885
7886   return SDValue();
7887 }
7888
7889 /// Try to perform FMA combining on a given FSUB node.
7890 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7891   SDValue N0 = N->getOperand(0);
7892   SDValue N1 = N->getOperand(1);
7893   EVT VT = N->getValueType(0);
7894   SDLoc SL(N);
7895
7896   const TargetOptions &Options = DAG.getTarget().Options;
7897   bool AllowFusion =
7898       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7899
7900   // Floating-point multiply-add with intermediate rounding.
7901   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7902
7903   // Floating-point multiply-add without intermediate rounding.
7904   bool HasFMA =
7905       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7906       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7907
7908   // No valid opcode, do not combine.
7909   if (!HasFMAD && !HasFMA)
7910     return SDValue();
7911
7912   // Always prefer FMAD to FMA for precision.
7913   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7914   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7915   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7916
7917   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7918   if (N0.getOpcode() == ISD::FMUL &&
7919       (Aggressive || N0->hasOneUse())) {
7920     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7921                        N0.getOperand(0), N0.getOperand(1),
7922                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7923   }
7924
7925   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7926   // Note: Commutes FSUB operands.
7927   if (N1.getOpcode() == ISD::FMUL &&
7928       (Aggressive || N1->hasOneUse()))
7929     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7930                        DAG.getNode(ISD::FNEG, SL, VT,
7931                                    N1.getOperand(0)),
7932                        N1.getOperand(1), N0);
7933
7934   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7935   if (N0.getOpcode() == ISD::FNEG &&
7936       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7937       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7938     SDValue N00 = N0.getOperand(0).getOperand(0);
7939     SDValue N01 = N0.getOperand(0).getOperand(1);
7940     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7941                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7942                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7943   }
7944
7945   // Look through FP_EXTEND nodes to do more combining.
7946   if (AllowFusion && LookThroughFPExt) {
7947     // fold (fsub (fpext (fmul x, y)), z)
7948     //   -> (fma (fpext x), (fpext y), (fneg z))
7949     if (N0.getOpcode() == ISD::FP_EXTEND) {
7950       SDValue N00 = N0.getOperand(0);
7951       if (N00.getOpcode() == ISD::FMUL)
7952         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7953                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7954                                        N00.getOperand(0)),
7955                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7956                                        N00.getOperand(1)),
7957                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7958     }
7959
7960     // fold (fsub x, (fpext (fmul y, z)))
7961     //   -> (fma (fneg (fpext y)), (fpext z), x)
7962     // Note: Commutes FSUB operands.
7963     if (N1.getOpcode() == ISD::FP_EXTEND) {
7964       SDValue N10 = N1.getOperand(0);
7965       if (N10.getOpcode() == ISD::FMUL)
7966         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7967                            DAG.getNode(ISD::FNEG, SL, VT,
7968                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7969                                                    N10.getOperand(0))),
7970                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7971                                        N10.getOperand(1)),
7972                            N0);
7973     }
7974
7975     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7976     //   -> (fneg (fma (fpext x), (fpext y), z))
7977     // Note: This could be removed with appropriate canonicalization of the
7978     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7979     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7980     // from implementing the canonicalization in visitFSUB.
7981     if (N0.getOpcode() == ISD::FP_EXTEND) {
7982       SDValue N00 = N0.getOperand(0);
7983       if (N00.getOpcode() == ISD::FNEG) {
7984         SDValue N000 = N00.getOperand(0);
7985         if (N000.getOpcode() == ISD::FMUL) {
7986           return DAG.getNode(ISD::FNEG, SL, VT,
7987                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7988                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7989                                                      N000.getOperand(0)),
7990                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7991                                                      N000.getOperand(1)),
7992                                          N1));
7993         }
7994       }
7995     }
7996
7997     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7998     //   -> (fneg (fma (fpext x)), (fpext y), z)
7999     // Note: This could be removed with appropriate canonicalization of the
8000     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8001     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8002     // from implementing the canonicalization in visitFSUB.
8003     if (N0.getOpcode() == ISD::FNEG) {
8004       SDValue N00 = N0.getOperand(0);
8005       if (N00.getOpcode() == ISD::FP_EXTEND) {
8006         SDValue N000 = N00.getOperand(0);
8007         if (N000.getOpcode() == ISD::FMUL) {
8008           return DAG.getNode(ISD::FNEG, SL, VT,
8009                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8010                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8011                                                      N000.getOperand(0)),
8012                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8013                                                      N000.getOperand(1)),
8014                                          N1));
8015         }
8016       }
8017     }
8018
8019   }
8020
8021   // More folding opportunities when target permits.
8022   if ((AllowFusion || HasFMAD) && Aggressive) {
8023     // fold (fsub (fma x, y, (fmul u, v)), z)
8024     //   -> (fma x, y (fma u, v, (fneg z)))
8025     if (N0.getOpcode() == PreferredFusedOpcode &&
8026         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8027       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8028                          N0.getOperand(0), N0.getOperand(1),
8029                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8030                                      N0.getOperand(2).getOperand(0),
8031                                      N0.getOperand(2).getOperand(1),
8032                                      DAG.getNode(ISD::FNEG, SL, VT,
8033                                                  N1)));
8034     }
8035
8036     // fold (fsub x, (fma y, z, (fmul u, v)))
8037     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8038     if (N1.getOpcode() == PreferredFusedOpcode &&
8039         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8040       SDValue N20 = N1.getOperand(2).getOperand(0);
8041       SDValue N21 = N1.getOperand(2).getOperand(1);
8042       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8043                          DAG.getNode(ISD::FNEG, SL, VT,
8044                                      N1.getOperand(0)),
8045                          N1.getOperand(1),
8046                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8047                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8048
8049                                      N21, N0));
8050     }
8051
8052     if (AllowFusion && LookThroughFPExt) {
8053       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8054       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8055       if (N0.getOpcode() == PreferredFusedOpcode) {
8056         SDValue N02 = N0.getOperand(2);
8057         if (N02.getOpcode() == ISD::FP_EXTEND) {
8058           SDValue N020 = N02.getOperand(0);
8059           if (N020.getOpcode() == ISD::FMUL)
8060             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8061                                N0.getOperand(0), N0.getOperand(1),
8062                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8063                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8064                                                        N020.getOperand(0)),
8065                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8066                                                        N020.getOperand(1)),
8067                                            DAG.getNode(ISD::FNEG, SL, VT,
8068                                                        N1)));
8069         }
8070       }
8071
8072       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8073       //   -> (fma (fpext x), (fpext y),
8074       //           (fma (fpext u), (fpext v), (fneg z)))
8075       // FIXME: This turns two single-precision and one double-precision
8076       // operation into two double-precision operations, which might not be
8077       // interesting for all targets, especially GPUs.
8078       if (N0.getOpcode() == ISD::FP_EXTEND) {
8079         SDValue N00 = N0.getOperand(0);
8080         if (N00.getOpcode() == PreferredFusedOpcode) {
8081           SDValue N002 = N00.getOperand(2);
8082           if (N002.getOpcode() == ISD::FMUL)
8083             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8084                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8085                                            N00.getOperand(0)),
8086                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8087                                            N00.getOperand(1)),
8088                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8089                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8090                                                        N002.getOperand(0)),
8091                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8092                                                        N002.getOperand(1)),
8093                                            DAG.getNode(ISD::FNEG, SL, VT,
8094                                                        N1)));
8095         }
8096       }
8097
8098       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8099       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8100       if (N1.getOpcode() == PreferredFusedOpcode &&
8101         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8102         SDValue N120 = N1.getOperand(2).getOperand(0);
8103         if (N120.getOpcode() == ISD::FMUL) {
8104           SDValue N1200 = N120.getOperand(0);
8105           SDValue N1201 = N120.getOperand(1);
8106           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8107                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8108                              N1.getOperand(1),
8109                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8110                                          DAG.getNode(ISD::FNEG, SL, VT,
8111                                              DAG.getNode(ISD::FP_EXTEND, SL,
8112                                                          VT, N1200)),
8113                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8114                                                      N1201),
8115                                          N0));
8116         }
8117       }
8118
8119       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8120       //   -> (fma (fneg (fpext y)), (fpext z),
8121       //           (fma (fneg (fpext u)), (fpext v), x))
8122       // FIXME: This turns two single-precision and one double-precision
8123       // operation into two double-precision operations, which might not be
8124       // interesting for all targets, especially GPUs.
8125       if (N1.getOpcode() == ISD::FP_EXTEND &&
8126         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8127         SDValue N100 = N1.getOperand(0).getOperand(0);
8128         SDValue N101 = N1.getOperand(0).getOperand(1);
8129         SDValue N102 = N1.getOperand(0).getOperand(2);
8130         if (N102.getOpcode() == ISD::FMUL) {
8131           SDValue N1020 = N102.getOperand(0);
8132           SDValue N1021 = N102.getOperand(1);
8133           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8134                              DAG.getNode(ISD::FNEG, SL, VT,
8135                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8136                                                      N100)),
8137                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8138                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8139                                          DAG.getNode(ISD::FNEG, SL, VT,
8140                                              DAG.getNode(ISD::FP_EXTEND, SL,
8141                                                          VT, N1020)),
8142                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8143                                                      N1021),
8144                                          N0));
8145         }
8146       }
8147     }
8148   }
8149
8150   return SDValue();
8151 }
8152
8153 /// Try to perform FMA combining on a given FMUL node.
8154 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8155   SDValue N0 = N->getOperand(0);
8156   SDValue N1 = N->getOperand(1);
8157   EVT VT = N->getValueType(0);
8158   SDLoc SL(N);
8159
8160   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8161
8162   const TargetOptions &Options = DAG.getTarget().Options;
8163   bool AllowFusion =
8164       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8165
8166   // Floating-point multiply-add with intermediate rounding.
8167   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8168
8169   // Floating-point multiply-add without intermediate rounding.
8170   bool HasFMA =
8171       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8172       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8173
8174   // No valid opcode, do not combine.
8175   if (!HasFMAD && !HasFMA)
8176     return SDValue();
8177
8178   // Always prefer FMAD to FMA for precision.
8179   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8180   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8181
8182   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8183   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8184   auto FuseFADD = [&](SDValue X, SDValue Y) {
8185     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8186       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8187       if (XC1 && XC1->isExactlyValue(+1.0))
8188         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8189       if (XC1 && XC1->isExactlyValue(-1.0))
8190         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8191                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8192     }
8193     return SDValue();
8194   };
8195
8196   if (SDValue FMA = FuseFADD(N0, N1))
8197     return FMA;
8198   if (SDValue FMA = FuseFADD(N1, N0))
8199     return FMA;
8200
8201   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8202   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8203   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8204   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8205   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8206     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8207       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8208       if (XC0 && XC0->isExactlyValue(+1.0))
8209         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8210                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8211                            Y);
8212       if (XC0 && XC0->isExactlyValue(-1.0))
8213         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8214                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8215                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8216
8217       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8218       if (XC1 && XC1->isExactlyValue(+1.0))
8219         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8220                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8221       if (XC1 && XC1->isExactlyValue(-1.0))
8222         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8223     }
8224     return SDValue();
8225   };
8226
8227   if (SDValue FMA = FuseFSUB(N0, N1))
8228     return FMA;
8229   if (SDValue FMA = FuseFSUB(N1, N0))
8230     return FMA;
8231
8232   return SDValue();
8233 }
8234
8235 SDValue DAGCombiner::visitFADD(SDNode *N) {
8236   SDValue N0 = N->getOperand(0);
8237   SDValue N1 = N->getOperand(1);
8238   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8239   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8240   EVT VT = N->getValueType(0);
8241   SDLoc DL(N);
8242   const TargetOptions &Options = DAG.getTarget().Options;
8243   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8244
8245   // fold vector ops
8246   if (VT.isVector())
8247     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8248       return FoldedVOp;
8249
8250   // fold (fadd c1, c2) -> c1 + c2
8251   if (N0CFP && N1CFP)
8252     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8253
8254   // canonicalize constant to RHS
8255   if (N0CFP && !N1CFP)
8256     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8257
8258   // fold (fadd A, (fneg B)) -> (fsub A, B)
8259   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8260       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8261     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8262                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8263
8264   // fold (fadd (fneg A), B) -> (fsub B, A)
8265   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8266       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8267     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8268                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8269
8270   // If 'unsafe math' is enabled, fold lots of things.
8271   if (Options.UnsafeFPMath) {
8272     // No FP constant should be created after legalization as Instruction
8273     // Selection pass has a hard time dealing with FP constants.
8274     bool AllowNewConst = (Level < AfterLegalizeDAG);
8275
8276     // fold (fadd A, 0) -> A
8277     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8278       if (N1C->isZero())
8279         return N0;
8280
8281     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8282     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8283         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8284       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8285                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8286                                      Flags),
8287                          Flags);
8288
8289     // If allowed, fold (fadd (fneg x), x) -> 0.0
8290     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8291       return DAG.getConstantFP(0.0, DL, VT);
8292
8293     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8294     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8295       return DAG.getConstantFP(0.0, DL, VT);
8296
8297     // We can fold chains of FADD's of the same value into multiplications.
8298     // This transform is not safe in general because we are reducing the number
8299     // of rounding steps.
8300     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8301       if (N0.getOpcode() == ISD::FMUL) {
8302         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8303         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8304
8305         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8306         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8307           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8308                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8309           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8310         }
8311
8312         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8313         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8314             N1.getOperand(0) == N1.getOperand(1) &&
8315             N0.getOperand(0) == N1.getOperand(0)) {
8316           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8317                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8318           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8319         }
8320       }
8321
8322       if (N1.getOpcode() == ISD::FMUL) {
8323         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8324         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8325
8326         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8327         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8328           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8329                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8330           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8331         }
8332
8333         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8334         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8335             N0.getOperand(0) == N0.getOperand(1) &&
8336             N1.getOperand(0) == N0.getOperand(0)) {
8337           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8338                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8339           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8340         }
8341       }
8342
8343       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8344         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8345         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8346         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8347             (N0.getOperand(0) == N1)) {
8348           return DAG.getNode(ISD::FMUL, DL, VT,
8349                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8350         }
8351       }
8352
8353       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8354         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8355         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8356         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8357             N1.getOperand(0) == N0) {
8358           return DAG.getNode(ISD::FMUL, DL, VT,
8359                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8360         }
8361       }
8362
8363       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8364       if (AllowNewConst &&
8365           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8366           N0.getOperand(0) == N0.getOperand(1) &&
8367           N1.getOperand(0) == N1.getOperand(1) &&
8368           N0.getOperand(0) == N1.getOperand(0)) {
8369         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8370                            DAG.getConstantFP(4.0, DL, VT), Flags);
8371       }
8372     }
8373   } // enable-unsafe-fp-math
8374
8375   // FADD -> FMA combines:
8376   if (SDValue Fused = visitFADDForFMACombine(N)) {
8377     AddToWorklist(Fused.getNode());
8378     return Fused;
8379   }
8380
8381   return SDValue();
8382 }
8383
8384 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8385   SDValue N0 = N->getOperand(0);
8386   SDValue N1 = N->getOperand(1);
8387   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8388   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8389   EVT VT = N->getValueType(0);
8390   SDLoc dl(N);
8391   const TargetOptions &Options = DAG.getTarget().Options;
8392   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8393
8394   // fold vector ops
8395   if (VT.isVector())
8396     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8397       return FoldedVOp;
8398
8399   // fold (fsub c1, c2) -> c1-c2
8400   if (N0CFP && N1CFP)
8401     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8402
8403   // fold (fsub A, (fneg B)) -> (fadd A, B)
8404   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8405     return DAG.getNode(ISD::FADD, dl, VT, N0,
8406                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8407
8408   // If 'unsafe math' is enabled, fold lots of things.
8409   if (Options.UnsafeFPMath) {
8410     // (fsub A, 0) -> A
8411     if (N1CFP && N1CFP->isZero())
8412       return N0;
8413
8414     // (fsub 0, B) -> -B
8415     if (N0CFP && N0CFP->isZero()) {
8416       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8417         return GetNegatedExpression(N1, DAG, LegalOperations);
8418       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8419         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8420     }
8421
8422     // (fsub x, x) -> 0.0
8423     if (N0 == N1)
8424       return DAG.getConstantFP(0.0f, dl, VT);
8425
8426     // (fsub x, (fadd x, y)) -> (fneg y)
8427     // (fsub x, (fadd y, x)) -> (fneg y)
8428     if (N1.getOpcode() == ISD::FADD) {
8429       SDValue N10 = N1->getOperand(0);
8430       SDValue N11 = N1->getOperand(1);
8431
8432       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8433         return GetNegatedExpression(N11, DAG, LegalOperations);
8434
8435       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8436         return GetNegatedExpression(N10, DAG, LegalOperations);
8437     }
8438   }
8439
8440   // FSUB -> FMA combines:
8441   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8442     AddToWorklist(Fused.getNode());
8443     return Fused;
8444   }
8445
8446   return SDValue();
8447 }
8448
8449 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8450   SDValue N0 = N->getOperand(0);
8451   SDValue N1 = N->getOperand(1);
8452   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8453   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8454   EVT VT = N->getValueType(0);
8455   SDLoc DL(N);
8456   const TargetOptions &Options = DAG.getTarget().Options;
8457   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8458
8459   // fold vector ops
8460   if (VT.isVector()) {
8461     // This just handles C1 * C2 for vectors. Other vector folds are below.
8462     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8463       return FoldedVOp;
8464   }
8465
8466   // fold (fmul c1, c2) -> c1*c2
8467   if (N0CFP && N1CFP)
8468     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8469
8470   // canonicalize constant to RHS
8471   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8472      !isConstantFPBuildVectorOrConstantFP(N1))
8473     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8474
8475   // fold (fmul A, 1.0) -> A
8476   if (N1CFP && N1CFP->isExactlyValue(1.0))
8477     return N0;
8478
8479   if (Options.UnsafeFPMath) {
8480     // fold (fmul A, 0) -> 0
8481     if (N1CFP && N1CFP->isZero())
8482       return N1;
8483
8484     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8485     if (N0.getOpcode() == ISD::FMUL) {
8486       // Fold scalars or any vector constants (not just splats).
8487       // This fold is done in general by InstCombine, but extra fmul insts
8488       // may have been generated during lowering.
8489       SDValue N00 = N0.getOperand(0);
8490       SDValue N01 = N0.getOperand(1);
8491       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8492       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8493       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8494
8495       // Check 1: Make sure that the first operand of the inner multiply is NOT
8496       // a constant. Otherwise, we may induce infinite looping.
8497       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8498         // Check 2: Make sure that the second operand of the inner multiply and
8499         // the second operand of the outer multiply are constants.
8500         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8501             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8502           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8503           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8504         }
8505       }
8506     }
8507
8508     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8509     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8510     // during an early run of DAGCombiner can prevent folding with fmuls
8511     // inserted during lowering.
8512     if (N0.getOpcode() == ISD::FADD &&
8513         (N0.getOperand(0) == N0.getOperand(1)) &&
8514         N0.hasOneUse()) {
8515       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8516       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8517       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8518     }
8519   }
8520
8521   // fold (fmul X, 2.0) -> (fadd X, X)
8522   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8523     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8524
8525   // fold (fmul X, -1.0) -> (fneg X)
8526   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8527     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8528       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8529
8530   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8531   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8532     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8533       // Both can be negated for free, check to see if at least one is cheaper
8534       // negated.
8535       if (LHSNeg == 2 || RHSNeg == 2)
8536         return DAG.getNode(ISD::FMUL, DL, VT,
8537                            GetNegatedExpression(N0, DAG, LegalOperations),
8538                            GetNegatedExpression(N1, DAG, LegalOperations),
8539                            Flags);
8540     }
8541   }
8542
8543   // FMUL -> FMA combines:
8544   if (SDValue Fused = visitFMULForFMACombine(N)) {
8545     AddToWorklist(Fused.getNode());
8546     return Fused;
8547   }
8548
8549   return SDValue();
8550 }
8551
8552 SDValue DAGCombiner::visitFMA(SDNode *N) {
8553   SDValue N0 = N->getOperand(0);
8554   SDValue N1 = N->getOperand(1);
8555   SDValue N2 = N->getOperand(2);
8556   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8557   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8558   EVT VT = N->getValueType(0);
8559   SDLoc dl(N);
8560   const TargetOptions &Options = DAG.getTarget().Options;
8561
8562   // Constant fold FMA.
8563   if (isa<ConstantFPSDNode>(N0) &&
8564       isa<ConstantFPSDNode>(N1) &&
8565       isa<ConstantFPSDNode>(N2)) {
8566     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8567   }
8568
8569   if (Options.UnsafeFPMath) {
8570     if (N0CFP && N0CFP->isZero())
8571       return N2;
8572     if (N1CFP && N1CFP->isZero())
8573       return N2;
8574   }
8575   // TODO: The FMA node should have flags that propagate to these nodes.
8576   if (N0CFP && N0CFP->isExactlyValue(1.0))
8577     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8578   if (N1CFP && N1CFP->isExactlyValue(1.0))
8579     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8580
8581   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8582   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8583      !isConstantFPBuildVectorOrConstantFP(N1))
8584     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8585
8586   // TODO: FMA nodes should have flags that propagate to the created nodes.
8587   // For now, create a Flags object for use with all unsafe math transforms.
8588   SDNodeFlags Flags;
8589   Flags.setUnsafeAlgebra(true);
8590
8591   if (Options.UnsafeFPMath) {
8592     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8593     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8594         isConstantFPBuildVectorOrConstantFP(N1) &&
8595         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8596       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8597                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8598                                      &Flags), &Flags);
8599     }
8600
8601     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8602     if (N0.getOpcode() == ISD::FMUL &&
8603         isConstantFPBuildVectorOrConstantFP(N1) &&
8604         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8605       return DAG.getNode(ISD::FMA, dl, VT,
8606                          N0.getOperand(0),
8607                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8608                                      &Flags),
8609                          N2);
8610     }
8611   }
8612
8613   // (fma x, 1, y) -> (fadd x, y)
8614   // (fma x, -1, y) -> (fadd (fneg x), y)
8615   if (N1CFP) {
8616     if (N1CFP->isExactlyValue(1.0))
8617       // TODO: The FMA node should have flags that propagate to this node.
8618       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8619
8620     if (N1CFP->isExactlyValue(-1.0) &&
8621         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8622       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8623       AddToWorklist(RHSNeg.getNode());
8624       // TODO: The FMA node should have flags that propagate to this node.
8625       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8626     }
8627   }
8628
8629   if (Options.UnsafeFPMath) {
8630     // (fma x, c, x) -> (fmul x, (c+1))
8631     if (N1CFP && N0 == N2) {
8632     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8633                          DAG.getNode(ISD::FADD, dl, VT,
8634                                      N1, DAG.getConstantFP(1.0, dl, VT),
8635                                      &Flags), &Flags);
8636     }
8637
8638     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8639     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8640       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8641                          DAG.getNode(ISD::FADD, dl, VT,
8642                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8643                                      &Flags), &Flags);
8644     }
8645   }
8646
8647   return SDValue();
8648 }
8649
8650 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8651 // reciprocal.
8652 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8653 // Notice that this is not always beneficial. One reason is different target
8654 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8655 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8656 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8657 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8658   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8659   const SDNodeFlags *Flags = N->getFlags();
8660   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8661     return SDValue();
8662
8663   // Skip if current node is a reciprocal.
8664   SDValue N0 = N->getOperand(0);
8665   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8666   if (N0CFP && N0CFP->isExactlyValue(1.0))
8667     return SDValue();
8668
8669   // Exit early if the target does not want this transform or if there can't
8670   // possibly be enough uses of the divisor to make the transform worthwhile.
8671   SDValue N1 = N->getOperand(1);
8672   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8673   if (!MinUses || N1->use_size() < MinUses)
8674     return SDValue();
8675
8676   // Find all FDIV users of the same divisor.
8677   // Use a set because duplicates may be present in the user list.
8678   SetVector<SDNode *> Users;
8679   for (auto *U : N1->uses()) {
8680     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8681       // This division is eligible for optimization only if global unsafe math
8682       // is enabled or if this division allows reciprocal formation.
8683       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8684         Users.insert(U);
8685     }
8686   }
8687
8688   // Now that we have the actual number of divisor uses, make sure it meets
8689   // the minimum threshold specified by the target.
8690   if (Users.size() < MinUses)
8691     return SDValue();
8692
8693   EVT VT = N->getValueType(0);
8694   SDLoc DL(N);
8695   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8696   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8697
8698   // Dividend / Divisor -> Dividend * Reciprocal
8699   for (auto *U : Users) {
8700     SDValue Dividend = U->getOperand(0);
8701     if (Dividend != FPOne) {
8702       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8703                                     Reciprocal, Flags);
8704       CombineTo(U, NewNode);
8705     } else if (U != Reciprocal.getNode()) {
8706       // In the absence of fast-math-flags, this user node is always the
8707       // same node as Reciprocal, but with FMF they may be different nodes.
8708       CombineTo(U, Reciprocal);
8709     }
8710   }
8711   return SDValue(N, 0);  // N was replaced.
8712 }
8713
8714 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8715   SDValue N0 = N->getOperand(0);
8716   SDValue N1 = N->getOperand(1);
8717   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8718   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8719   EVT VT = N->getValueType(0);
8720   SDLoc DL(N);
8721   const TargetOptions &Options = DAG.getTarget().Options;
8722   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8723
8724   // fold vector ops
8725   if (VT.isVector())
8726     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8727       return FoldedVOp;
8728
8729   // fold (fdiv c1, c2) -> c1/c2
8730   if (N0CFP && N1CFP)
8731     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8732
8733   if (Options.UnsafeFPMath) {
8734     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8735     if (N1CFP) {
8736       // Compute the reciprocal 1.0 / c2.
8737       APFloat N1APF = N1CFP->getValueAPF();
8738       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8739       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8740       // Only do the transform if the reciprocal is a legal fp immediate that
8741       // isn't too nasty (eg NaN, denormal, ...).
8742       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8743           (!LegalOperations ||
8744            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8745            // backend)... we should handle this gracefully after Legalize.
8746            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8747            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8748            TLI.isFPImmLegal(Recip, VT)))
8749         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8750                            DAG.getConstantFP(Recip, DL, VT), Flags);
8751     }
8752
8753     // If this FDIV is part of a reciprocal square root, it may be folded
8754     // into a target-specific square root estimate instruction.
8755     if (N1.getOpcode() == ISD::FSQRT) {
8756       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8757         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8758       }
8759     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8760                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8761       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8762                                           Flags)) {
8763         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8764         AddToWorklist(RV.getNode());
8765         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8766       }
8767     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8768                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8769       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8770                                           Flags)) {
8771         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8772         AddToWorklist(RV.getNode());
8773         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8774       }
8775     } else if (N1.getOpcode() == ISD::FMUL) {
8776       // Look through an FMUL. Even though this won't remove the FDIV directly,
8777       // it's still worthwhile to get rid of the FSQRT if possible.
8778       SDValue SqrtOp;
8779       SDValue OtherOp;
8780       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8781         SqrtOp = N1.getOperand(0);
8782         OtherOp = N1.getOperand(1);
8783       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8784         SqrtOp = N1.getOperand(1);
8785         OtherOp = N1.getOperand(0);
8786       }
8787       if (SqrtOp.getNode()) {
8788         // We found a FSQRT, so try to make this fold:
8789         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8790         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8791           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8792           AddToWorklist(RV.getNode());
8793           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8794         }
8795       }
8796     }
8797
8798     // Fold into a reciprocal estimate and multiply instead of a real divide.
8799     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8800       AddToWorklist(RV.getNode());
8801       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8802     }
8803   }
8804
8805   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8806   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8807     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8808       // Both can be negated for free, check to see if at least one is cheaper
8809       // negated.
8810       if (LHSNeg == 2 || RHSNeg == 2)
8811         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8812                            GetNegatedExpression(N0, DAG, LegalOperations),
8813                            GetNegatedExpression(N1, DAG, LegalOperations),
8814                            Flags);
8815     }
8816   }
8817
8818   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8819     return CombineRepeatedDivisors;
8820
8821   return SDValue();
8822 }
8823
8824 SDValue DAGCombiner::visitFREM(SDNode *N) {
8825   SDValue N0 = N->getOperand(0);
8826   SDValue N1 = N->getOperand(1);
8827   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8828   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8829   EVT VT = N->getValueType(0);
8830
8831   // fold (frem c1, c2) -> fmod(c1,c2)
8832   if (N0CFP && N1CFP)
8833     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8834                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8835
8836   return SDValue();
8837 }
8838
8839 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8840   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8841     return SDValue();
8842
8843   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8844   // For now, create a Flags object for use with all unsafe math transforms.
8845   SDNodeFlags Flags;
8846   Flags.setUnsafeAlgebra(true);
8847
8848   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8849   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8850   if (!RV)
8851     return SDValue();
8852
8853   EVT VT = RV.getValueType();
8854   SDLoc DL(N);
8855   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8856   AddToWorklist(RV.getNode());
8857
8858   // Unfortunately, RV is now NaN if the input was exactly 0.
8859   // Select out this case and force the answer to 0.
8860   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8861   EVT CCVT = getSetCCResultType(VT);
8862   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8863   AddToWorklist(ZeroCmp.getNode());
8864   AddToWorklist(RV.getNode());
8865
8866   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8867                      ZeroCmp, Zero, RV);
8868 }
8869
8870 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8871 /// copysign(x, fp_round(y)) -> copysign(x, y)
8872 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8873   SDValue N1 = N->getOperand(1);
8874   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8875        N1.getOpcode() == ISD::FP_ROUND)) {
8876     // Do not optimize out type conversion of f128 type yet.
8877     // For some targets like x86_64, configuration is changed to keep one f128
8878     // value in one SSE register, but instruction selection cannot handle
8879     // FCOPYSIGN on SSE registers yet.
8880     EVT N1VT = N1->getValueType(0);
8881     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8882     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8883   }
8884   return false;
8885 }
8886
8887 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8888   SDValue N0 = N->getOperand(0);
8889   SDValue N1 = N->getOperand(1);
8890   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8891   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8892   EVT VT = N->getValueType(0);
8893
8894   if (N0CFP && N1CFP)  // Constant fold
8895     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8896
8897   if (N1CFP) {
8898     const APFloat& V = N1CFP->getValueAPF();
8899     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8900     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8901     if (!V.isNegative()) {
8902       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8903         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8904     } else {
8905       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8906         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8907                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8908     }
8909   }
8910
8911   // copysign(fabs(x), y) -> copysign(x, y)
8912   // copysign(fneg(x), y) -> copysign(x, y)
8913   // copysign(copysign(x,z), y) -> copysign(x, y)
8914   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8915       N0.getOpcode() == ISD::FCOPYSIGN)
8916     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8917                        N0.getOperand(0), N1);
8918
8919   // copysign(x, abs(y)) -> abs(x)
8920   if (N1.getOpcode() == ISD::FABS)
8921     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8922
8923   // copysign(x, copysign(y,z)) -> copysign(x, z)
8924   if (N1.getOpcode() == ISD::FCOPYSIGN)
8925     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8926                        N0, N1.getOperand(1));
8927
8928   // copysign(x, fp_extend(y)) -> copysign(x, y)
8929   // copysign(x, fp_round(y)) -> copysign(x, y)
8930   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8931     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8932                        N0, N1.getOperand(0));
8933
8934   return SDValue();
8935 }
8936
8937 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8938   SDValue N0 = N->getOperand(0);
8939   EVT VT = N->getValueType(0);
8940   EVT OpVT = N0.getValueType();
8941
8942   // fold (sint_to_fp c1) -> c1fp
8943   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8944       // ...but only if the target supports immediate floating-point values
8945       (!LegalOperations ||
8946        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8947     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8948
8949   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8950   // but UINT_TO_FP is legal on this target, try to convert.
8951   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8952       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8953     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8954     if (DAG.SignBitIsZero(N0))
8955       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8956   }
8957
8958   // The next optimizations are desirable only if SELECT_CC can be lowered.
8959   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8960     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8961     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8962         !VT.isVector() &&
8963         (!LegalOperations ||
8964          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8965       SDLoc DL(N);
8966       SDValue Ops[] =
8967         { N0.getOperand(0), N0.getOperand(1),
8968           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8969           N0.getOperand(2) };
8970       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8971     }
8972
8973     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8974     //      (select_cc x, y, 1.0, 0.0,, cc)
8975     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8976         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8977         (!LegalOperations ||
8978          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8979       SDLoc DL(N);
8980       SDValue Ops[] =
8981         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8982           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8983           N0.getOperand(0).getOperand(2) };
8984       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8985     }
8986   }
8987
8988   return SDValue();
8989 }
8990
8991 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8992   SDValue N0 = N->getOperand(0);
8993   EVT VT = N->getValueType(0);
8994   EVT OpVT = N0.getValueType();
8995
8996   // fold (uint_to_fp c1) -> c1fp
8997   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8998       // ...but only if the target supports immediate floating-point values
8999       (!LegalOperations ||
9000        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9001     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9002
9003   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9004   // but SINT_TO_FP is legal on this target, try to convert.
9005   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9006       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9007     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9008     if (DAG.SignBitIsZero(N0))
9009       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9010   }
9011
9012   // The next optimizations are desirable only if SELECT_CC can be lowered.
9013   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9014     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9015
9016     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9017         (!LegalOperations ||
9018          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9019       SDLoc DL(N);
9020       SDValue Ops[] =
9021         { N0.getOperand(0), N0.getOperand(1),
9022           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9023           N0.getOperand(2) };
9024       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9025     }
9026   }
9027
9028   return SDValue();
9029 }
9030
9031 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9032 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9033   SDValue N0 = N->getOperand(0);
9034   EVT VT = N->getValueType(0);
9035
9036   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9037     return SDValue();
9038
9039   SDValue Src = N0.getOperand(0);
9040   EVT SrcVT = Src.getValueType();
9041   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9042   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9043
9044   // We can safely assume the conversion won't overflow the output range,
9045   // because (for example) (uint8_t)18293.f is undefined behavior.
9046
9047   // Since we can assume the conversion won't overflow, our decision as to
9048   // whether the input will fit in the float should depend on the minimum
9049   // of the input range and output range.
9050
9051   // This means this is also safe for a signed input and unsigned output, since
9052   // a negative input would lead to undefined behavior.
9053   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9054   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9055   unsigned ActualSize = std::min(InputSize, OutputSize);
9056   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9057
9058   // We can only fold away the float conversion if the input range can be
9059   // represented exactly in the float range.
9060   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9061     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9062       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9063                                                        : ISD::ZERO_EXTEND;
9064       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9065     }
9066     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9067       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9068     if (SrcVT == VT)
9069       return Src;
9070     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
9071   }
9072   return SDValue();
9073 }
9074
9075 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9076   SDValue N0 = N->getOperand(0);
9077   EVT VT = N->getValueType(0);
9078
9079   // fold (fp_to_sint c1fp) -> c1
9080   if (isConstantFPBuildVectorOrConstantFP(N0))
9081     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9082
9083   return FoldIntToFPToInt(N, DAG);
9084 }
9085
9086 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9087   SDValue N0 = N->getOperand(0);
9088   EVT VT = N->getValueType(0);
9089
9090   // fold (fp_to_uint c1fp) -> c1
9091   if (isConstantFPBuildVectorOrConstantFP(N0))
9092     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9093
9094   return FoldIntToFPToInt(N, DAG);
9095 }
9096
9097 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9098   SDValue N0 = N->getOperand(0);
9099   SDValue N1 = N->getOperand(1);
9100   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9101   EVT VT = N->getValueType(0);
9102
9103   // fold (fp_round c1fp) -> c1fp
9104   if (N0CFP)
9105     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9106
9107   // fold (fp_round (fp_extend x)) -> x
9108   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9109     return N0.getOperand(0);
9110
9111   // fold (fp_round (fp_round x)) -> (fp_round x)
9112   if (N0.getOpcode() == ISD::FP_ROUND) {
9113     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9114     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9115     // If the first fp_round isn't a value preserving truncation, it might
9116     // introduce a tie in the second fp_round, that wouldn't occur in the
9117     // single-step fp_round we want to fold to.
9118     // In other words, double rounding isn't the same as rounding.
9119     // Also, this is a value preserving truncation iff both fp_round's are.
9120     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9121       SDLoc DL(N);
9122       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9123                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9124     }
9125   }
9126
9127   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9128   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9129     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9130                               N0.getOperand(0), N1);
9131     AddToWorklist(Tmp.getNode());
9132     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9133                        Tmp, N0.getOperand(1));
9134   }
9135
9136   return SDValue();
9137 }
9138
9139 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9140   SDValue N0 = N->getOperand(0);
9141   EVT VT = N->getValueType(0);
9142   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9143   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9144
9145   // fold (fp_round_inreg c1fp) -> c1fp
9146   if (N0CFP && isTypeLegal(EVT)) {
9147     SDLoc DL(N);
9148     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9149     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9150   }
9151
9152   return SDValue();
9153 }
9154
9155 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9156   SDValue N0 = N->getOperand(0);
9157   EVT VT = N->getValueType(0);
9158
9159   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9160   if (N->hasOneUse() &&
9161       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9162     return SDValue();
9163
9164   // fold (fp_extend c1fp) -> c1fp
9165   if (isConstantFPBuildVectorOrConstantFP(N0))
9166     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9167
9168   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9169   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9170       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9171     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9172
9173   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9174   // value of X.
9175   if (N0.getOpcode() == ISD::FP_ROUND
9176       && N0.getNode()->getConstantOperandVal(1) == 1) {
9177     SDValue In = N0.getOperand(0);
9178     if (In.getValueType() == VT) return In;
9179     if (VT.bitsLT(In.getValueType()))
9180       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9181                          In, N0.getOperand(1));
9182     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9183   }
9184
9185   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9186   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9187        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9188     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9189     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9190                                      LN0->getChain(),
9191                                      LN0->getBasePtr(), N0.getValueType(),
9192                                      LN0->getMemOperand());
9193     CombineTo(N, ExtLoad);
9194     CombineTo(N0.getNode(),
9195               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9196                           N0.getValueType(), ExtLoad,
9197                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9198               ExtLoad.getValue(1));
9199     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9200   }
9201
9202   return SDValue();
9203 }
9204
9205 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9206   SDValue N0 = N->getOperand(0);
9207   EVT VT = N->getValueType(0);
9208
9209   // fold (fceil c1) -> fceil(c1)
9210   if (isConstantFPBuildVectorOrConstantFP(N0))
9211     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9212
9213   return SDValue();
9214 }
9215
9216 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9217   SDValue N0 = N->getOperand(0);
9218   EVT VT = N->getValueType(0);
9219
9220   // fold (ftrunc c1) -> ftrunc(c1)
9221   if (isConstantFPBuildVectorOrConstantFP(N0))
9222     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9223
9224   return SDValue();
9225 }
9226
9227 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9228   SDValue N0 = N->getOperand(0);
9229   EVT VT = N->getValueType(0);
9230
9231   // fold (ffloor c1) -> ffloor(c1)
9232   if (isConstantFPBuildVectorOrConstantFP(N0))
9233     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9234
9235   return SDValue();
9236 }
9237
9238 // FIXME: FNEG and FABS have a lot in common; refactor.
9239 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9240   SDValue N0 = N->getOperand(0);
9241   EVT VT = N->getValueType(0);
9242
9243   // Constant fold FNEG.
9244   if (isConstantFPBuildVectorOrConstantFP(N0))
9245     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9246
9247   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9248                          &DAG.getTarget().Options))
9249     return GetNegatedExpression(N0, DAG, LegalOperations);
9250
9251   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9252   // constant pool values.
9253   if (!TLI.isFNegFree(VT) &&
9254       N0.getOpcode() == ISD::BITCAST &&
9255       N0.getNode()->hasOneUse()) {
9256     SDValue Int = N0.getOperand(0);
9257     EVT IntVT = Int.getValueType();
9258     if (IntVT.isInteger() && !IntVT.isVector()) {
9259       APInt SignMask;
9260       if (N0.getValueType().isVector()) {
9261         // For a vector, get a mask such as 0x80... per scalar element
9262         // and splat it.
9263         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9264         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9265       } else {
9266         // For a scalar, just generate 0x80...
9267         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9268       }
9269       SDLoc DL0(N0);
9270       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9271                         DAG.getConstant(SignMask, DL0, IntVT));
9272       AddToWorklist(Int.getNode());
9273       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9274     }
9275   }
9276
9277   // (fneg (fmul c, x)) -> (fmul -c, x)
9278   if (N0.getOpcode() == ISD::FMUL &&
9279       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9280     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9281     if (CFP1) {
9282       APFloat CVal = CFP1->getValueAPF();
9283       CVal.changeSign();
9284       if (Level >= AfterLegalizeDAG &&
9285           (TLI.isFPImmLegal(CVal, VT) ||
9286            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9287         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9288                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9289                                        N0.getOperand(1)),
9290                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9291     }
9292   }
9293
9294   return SDValue();
9295 }
9296
9297 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9298   SDValue N0 = N->getOperand(0);
9299   SDValue N1 = N->getOperand(1);
9300   EVT VT = N->getValueType(0);
9301   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9302   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9303
9304   if (N0CFP && N1CFP) {
9305     const APFloat &C0 = N0CFP->getValueAPF();
9306     const APFloat &C1 = N1CFP->getValueAPF();
9307     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9308   }
9309
9310   // Canonicalize to constant on RHS.
9311   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9312      !isConstantFPBuildVectorOrConstantFP(N1))
9313     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9314
9315   return SDValue();
9316 }
9317
9318 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9319   SDValue N0 = N->getOperand(0);
9320   SDValue N1 = N->getOperand(1);
9321   EVT VT = N->getValueType(0);
9322   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9323   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9324
9325   if (N0CFP && N1CFP) {
9326     const APFloat &C0 = N0CFP->getValueAPF();
9327     const APFloat &C1 = N1CFP->getValueAPF();
9328     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9329   }
9330
9331   // Canonicalize to constant on RHS.
9332   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9333      !isConstantFPBuildVectorOrConstantFP(N1))
9334     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9335
9336   return SDValue();
9337 }
9338
9339 SDValue DAGCombiner::visitFABS(SDNode *N) {
9340   SDValue N0 = N->getOperand(0);
9341   EVT VT = N->getValueType(0);
9342
9343   // fold (fabs c1) -> fabs(c1)
9344   if (isConstantFPBuildVectorOrConstantFP(N0))
9345     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9346
9347   // fold (fabs (fabs x)) -> (fabs x)
9348   if (N0.getOpcode() == ISD::FABS)
9349     return N->getOperand(0);
9350
9351   // fold (fabs (fneg x)) -> (fabs x)
9352   // fold (fabs (fcopysign x, y)) -> (fabs x)
9353   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9354     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9355
9356   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9357   // constant pool values.
9358   if (!TLI.isFAbsFree(VT) &&
9359       N0.getOpcode() == ISD::BITCAST &&
9360       N0.getNode()->hasOneUse()) {
9361     SDValue Int = N0.getOperand(0);
9362     EVT IntVT = Int.getValueType();
9363     if (IntVT.isInteger() && !IntVT.isVector()) {
9364       APInt SignMask;
9365       if (N0.getValueType().isVector()) {
9366         // For a vector, get a mask such as 0x7f... per scalar element
9367         // and splat it.
9368         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9369         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9370       } else {
9371         // For a scalar, just generate 0x7f...
9372         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9373       }
9374       SDLoc DL(N0);
9375       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9376                         DAG.getConstant(SignMask, DL, IntVT));
9377       AddToWorklist(Int.getNode());
9378       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9379     }
9380   }
9381
9382   return SDValue();
9383 }
9384
9385 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9386   SDValue Chain = N->getOperand(0);
9387   SDValue N1 = N->getOperand(1);
9388   SDValue N2 = N->getOperand(2);
9389
9390   // If N is a constant we could fold this into a fallthrough or unconditional
9391   // branch. However that doesn't happen very often in normal code, because
9392   // Instcombine/SimplifyCFG should have handled the available opportunities.
9393   // If we did this folding here, it would be necessary to update the
9394   // MachineBasicBlock CFG, which is awkward.
9395
9396   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9397   // on the target.
9398   if (N1.getOpcode() == ISD::SETCC &&
9399       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9400                                    N1.getOperand(0).getValueType())) {
9401     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9402                        Chain, N1.getOperand(2),
9403                        N1.getOperand(0), N1.getOperand(1), N2);
9404   }
9405
9406   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9407       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9408        (N1.getOperand(0).hasOneUse() &&
9409         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9410     SDNode *Trunc = nullptr;
9411     if (N1.getOpcode() == ISD::TRUNCATE) {
9412       // Look pass the truncate.
9413       Trunc = N1.getNode();
9414       N1 = N1.getOperand(0);
9415     }
9416
9417     // Match this pattern so that we can generate simpler code:
9418     //
9419     //   %a = ...
9420     //   %b = and i32 %a, 2
9421     //   %c = srl i32 %b, 1
9422     //   brcond i32 %c ...
9423     //
9424     // into
9425     //
9426     //   %a = ...
9427     //   %b = and i32 %a, 2
9428     //   %c = setcc eq %b, 0
9429     //   brcond %c ...
9430     //
9431     // This applies only when the AND constant value has one bit set and the
9432     // SRL constant is equal to the log2 of the AND constant. The back-end is
9433     // smart enough to convert the result into a TEST/JMP sequence.
9434     SDValue Op0 = N1.getOperand(0);
9435     SDValue Op1 = N1.getOperand(1);
9436
9437     if (Op0.getOpcode() == ISD::AND &&
9438         Op1.getOpcode() == ISD::Constant) {
9439       SDValue AndOp1 = Op0.getOperand(1);
9440
9441       if (AndOp1.getOpcode() == ISD::Constant) {
9442         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9443
9444         if (AndConst.isPowerOf2() &&
9445             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9446           SDLoc DL(N);
9447           SDValue SetCC =
9448             DAG.getSetCC(DL,
9449                          getSetCCResultType(Op0.getValueType()),
9450                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9451                          ISD::SETNE);
9452
9453           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9454                                           MVT::Other, Chain, SetCC, N2);
9455           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9456           // will convert it back to (X & C1) >> C2.
9457           CombineTo(N, NewBRCond, false);
9458           // Truncate is dead.
9459           if (Trunc)
9460             deleteAndRecombine(Trunc);
9461           // Replace the uses of SRL with SETCC
9462           WorklistRemover DeadNodes(*this);
9463           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9464           deleteAndRecombine(N1.getNode());
9465           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9466         }
9467       }
9468     }
9469
9470     if (Trunc)
9471       // Restore N1 if the above transformation doesn't match.
9472       N1 = N->getOperand(1);
9473   }
9474
9475   // Transform br(xor(x, y)) -> br(x != y)
9476   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9477   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9478     SDNode *TheXor = N1.getNode();
9479     SDValue Op0 = TheXor->getOperand(0);
9480     SDValue Op1 = TheXor->getOperand(1);
9481     if (Op0.getOpcode() == Op1.getOpcode()) {
9482       // Avoid missing important xor optimizations.
9483       if (SDValue Tmp = visitXOR(TheXor)) {
9484         if (Tmp.getNode() != TheXor) {
9485           DEBUG(dbgs() << "\nReplacing.8 ";
9486                 TheXor->dump(&DAG);
9487                 dbgs() << "\nWith: ";
9488                 Tmp.getNode()->dump(&DAG);
9489                 dbgs() << '\n');
9490           WorklistRemover DeadNodes(*this);
9491           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9492           deleteAndRecombine(TheXor);
9493           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9494                              MVT::Other, Chain, Tmp, N2);
9495         }
9496
9497         // visitXOR has changed XOR's operands or replaced the XOR completely,
9498         // bail out.
9499         return SDValue(N, 0);
9500       }
9501     }
9502
9503     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9504       bool Equal = false;
9505       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9506           Op0.getOpcode() == ISD::XOR) {
9507         TheXor = Op0.getNode();
9508         Equal = true;
9509       }
9510
9511       EVT SetCCVT = N1.getValueType();
9512       if (LegalTypes)
9513         SetCCVT = getSetCCResultType(SetCCVT);
9514       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9515                                    SetCCVT,
9516                                    Op0, Op1,
9517                                    Equal ? ISD::SETEQ : ISD::SETNE);
9518       // Replace the uses of XOR with SETCC
9519       WorklistRemover DeadNodes(*this);
9520       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9521       deleteAndRecombine(N1.getNode());
9522       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9523                          MVT::Other, Chain, SetCC, N2);
9524     }
9525   }
9526
9527   return SDValue();
9528 }
9529
9530 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9531 //
9532 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9533   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9534   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9535
9536   // If N is a constant we could fold this into a fallthrough or unconditional
9537   // branch. However that doesn't happen very often in normal code, because
9538   // Instcombine/SimplifyCFG should have handled the available opportunities.
9539   // If we did this folding here, it would be necessary to update the
9540   // MachineBasicBlock CFG, which is awkward.
9541
9542   // Use SimplifySetCC to simplify SETCC's.
9543   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9544                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9545                                false);
9546   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9547
9548   // fold to a simpler setcc
9549   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9550     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9551                        N->getOperand(0), Simp.getOperand(2),
9552                        Simp.getOperand(0), Simp.getOperand(1),
9553                        N->getOperand(4));
9554
9555   return SDValue();
9556 }
9557
9558 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9559 /// and that N may be folded in the load / store addressing mode.
9560 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9561                                     SelectionDAG &DAG,
9562                                     const TargetLowering &TLI) {
9563   EVT VT;
9564   unsigned AS;
9565
9566   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9567     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9568       return false;
9569     VT = LD->getMemoryVT();
9570     AS = LD->getAddressSpace();
9571   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9572     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9573       return false;
9574     VT = ST->getMemoryVT();
9575     AS = ST->getAddressSpace();
9576   } else
9577     return false;
9578
9579   TargetLowering::AddrMode AM;
9580   if (N->getOpcode() == ISD::ADD) {
9581     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9582     if (Offset)
9583       // [reg +/- imm]
9584       AM.BaseOffs = Offset->getSExtValue();
9585     else
9586       // [reg +/- reg]
9587       AM.Scale = 1;
9588   } else if (N->getOpcode() == ISD::SUB) {
9589     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9590     if (Offset)
9591       // [reg +/- imm]
9592       AM.BaseOffs = -Offset->getSExtValue();
9593     else
9594       // [reg +/- reg]
9595       AM.Scale = 1;
9596   } else
9597     return false;
9598
9599   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9600                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9601 }
9602
9603 /// Try turning a load/store into a pre-indexed load/store when the base
9604 /// pointer is an add or subtract and it has other uses besides the load/store.
9605 /// After the transformation, the new indexed load/store has effectively folded
9606 /// the add/subtract in and all of its other uses are redirected to the
9607 /// new load/store.
9608 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9609   if (Level < AfterLegalizeDAG)
9610     return false;
9611
9612   bool isLoad = true;
9613   SDValue Ptr;
9614   EVT VT;
9615   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9616     if (LD->isIndexed())
9617       return false;
9618     VT = LD->getMemoryVT();
9619     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9620         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9621       return false;
9622     Ptr = LD->getBasePtr();
9623   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9624     if (ST->isIndexed())
9625       return false;
9626     VT = ST->getMemoryVT();
9627     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9628         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9629       return false;
9630     Ptr = ST->getBasePtr();
9631     isLoad = false;
9632   } else {
9633     return false;
9634   }
9635
9636   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9637   // out.  There is no reason to make this a preinc/predec.
9638   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9639       Ptr.getNode()->hasOneUse())
9640     return false;
9641
9642   // Ask the target to do addressing mode selection.
9643   SDValue BasePtr;
9644   SDValue Offset;
9645   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9646   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9647     return false;
9648
9649   // Backends without true r+i pre-indexed forms may need to pass a
9650   // constant base with a variable offset so that constant coercion
9651   // will work with the patterns in canonical form.
9652   bool Swapped = false;
9653   if (isa<ConstantSDNode>(BasePtr)) {
9654     std::swap(BasePtr, Offset);
9655     Swapped = true;
9656   }
9657
9658   // Don't create a indexed load / store with zero offset.
9659   if (isNullConstant(Offset))
9660     return false;
9661
9662   // Try turning it into a pre-indexed load / store except when:
9663   // 1) The new base ptr is a frame index.
9664   // 2) If N is a store and the new base ptr is either the same as or is a
9665   //    predecessor of the value being stored.
9666   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9667   //    that would create a cycle.
9668   // 4) All uses are load / store ops that use it as old base ptr.
9669
9670   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9671   // (plus the implicit offset) to a register to preinc anyway.
9672   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9673     return false;
9674
9675   // Check #2.
9676   if (!isLoad) {
9677     SDValue Val = cast<StoreSDNode>(N)->getValue();
9678     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9679       return false;
9680   }
9681
9682   // If the offset is a constant, there may be other adds of constants that
9683   // can be folded with this one. We should do this to avoid having to keep
9684   // a copy of the original base pointer.
9685   SmallVector<SDNode *, 16> OtherUses;
9686   if (isa<ConstantSDNode>(Offset))
9687     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9688                               UE = BasePtr.getNode()->use_end();
9689          UI != UE; ++UI) {
9690       SDUse &Use = UI.getUse();
9691       // Skip the use that is Ptr and uses of other results from BasePtr's
9692       // node (important for nodes that return multiple results).
9693       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9694         continue;
9695
9696       if (Use.getUser()->isPredecessorOf(N))
9697         continue;
9698
9699       if (Use.getUser()->getOpcode() != ISD::ADD &&
9700           Use.getUser()->getOpcode() != ISD::SUB) {
9701         OtherUses.clear();
9702         break;
9703       }
9704
9705       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9706       if (!isa<ConstantSDNode>(Op1)) {
9707         OtherUses.clear();
9708         break;
9709       }
9710
9711       // FIXME: In some cases, we can be smarter about this.
9712       if (Op1.getValueType() != Offset.getValueType()) {
9713         OtherUses.clear();
9714         break;
9715       }
9716
9717       OtherUses.push_back(Use.getUser());
9718     }
9719
9720   if (Swapped)
9721     std::swap(BasePtr, Offset);
9722
9723   // Now check for #3 and #4.
9724   bool RealUse = false;
9725
9726   // Caches for hasPredecessorHelper
9727   SmallPtrSet<const SDNode *, 32> Visited;
9728   SmallVector<const SDNode *, 16> Worklist;
9729
9730   for (SDNode *Use : Ptr.getNode()->uses()) {
9731     if (Use == N)
9732       continue;
9733     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9734       return false;
9735
9736     // If Ptr may be folded in addressing mode of other use, then it's
9737     // not profitable to do this transformation.
9738     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9739       RealUse = true;
9740   }
9741
9742   if (!RealUse)
9743     return false;
9744
9745   SDValue Result;
9746   if (isLoad)
9747     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9748                                 BasePtr, Offset, AM);
9749   else
9750     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9751                                  BasePtr, Offset, AM);
9752   ++PreIndexedNodes;
9753   ++NodesCombined;
9754   DEBUG(dbgs() << "\nReplacing.4 ";
9755         N->dump(&DAG);
9756         dbgs() << "\nWith: ";
9757         Result.getNode()->dump(&DAG);
9758         dbgs() << '\n');
9759   WorklistRemover DeadNodes(*this);
9760   if (isLoad) {
9761     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9762     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9763   } else {
9764     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9765   }
9766
9767   // Finally, since the node is now dead, remove it from the graph.
9768   deleteAndRecombine(N);
9769
9770   if (Swapped)
9771     std::swap(BasePtr, Offset);
9772
9773   // Replace other uses of BasePtr that can be updated to use Ptr
9774   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9775     unsigned OffsetIdx = 1;
9776     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9777       OffsetIdx = 0;
9778     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9779            BasePtr.getNode() && "Expected BasePtr operand");
9780
9781     // We need to replace ptr0 in the following expression:
9782     //   x0 * offset0 + y0 * ptr0 = t0
9783     // knowing that
9784     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9785     //
9786     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9787     // indexed load/store and the expresion that needs to be re-written.
9788     //
9789     // Therefore, we have:
9790     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9791
9792     ConstantSDNode *CN =
9793       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9794     int X0, X1, Y0, Y1;
9795     APInt Offset0 = CN->getAPIntValue();
9796     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9797
9798     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9799     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9800     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9801     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9802
9803     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9804
9805     APInt CNV = Offset0;
9806     if (X0 < 0) CNV = -CNV;
9807     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9808     else CNV = CNV - Offset1;
9809
9810     SDLoc DL(OtherUses[i]);
9811
9812     // We can now generate the new expression.
9813     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9814     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9815
9816     SDValue NewUse = DAG.getNode(Opcode,
9817                                  DL,
9818                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9819     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9820     deleteAndRecombine(OtherUses[i]);
9821   }
9822
9823   // Replace the uses of Ptr with uses of the updated base value.
9824   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9825   deleteAndRecombine(Ptr.getNode());
9826
9827   return true;
9828 }
9829
9830 /// Try to combine a load/store with a add/sub of the base pointer node into a
9831 /// post-indexed load/store. The transformation folded the add/subtract into the
9832 /// new indexed load/store effectively and all of its uses are redirected to the
9833 /// new load/store.
9834 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9835   if (Level < AfterLegalizeDAG)
9836     return false;
9837
9838   bool isLoad = true;
9839   SDValue Ptr;
9840   EVT VT;
9841   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9842     if (LD->isIndexed())
9843       return false;
9844     VT = LD->getMemoryVT();
9845     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9846         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9847       return false;
9848     Ptr = LD->getBasePtr();
9849   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9850     if (ST->isIndexed())
9851       return false;
9852     VT = ST->getMemoryVT();
9853     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9854         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9855       return false;
9856     Ptr = ST->getBasePtr();
9857     isLoad = false;
9858   } else {
9859     return false;
9860   }
9861
9862   if (Ptr.getNode()->hasOneUse())
9863     return false;
9864
9865   for (SDNode *Op : Ptr.getNode()->uses()) {
9866     if (Op == N ||
9867         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9868       continue;
9869
9870     SDValue BasePtr;
9871     SDValue Offset;
9872     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9873     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9874       // Don't create a indexed load / store with zero offset.
9875       if (isNullConstant(Offset))
9876         continue;
9877
9878       // Try turning it into a post-indexed load / store except when
9879       // 1) All uses are load / store ops that use it as base ptr (and
9880       //    it may be folded as addressing mmode).
9881       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9882       //    nor a successor of N. Otherwise, if Op is folded that would
9883       //    create a cycle.
9884
9885       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9886         continue;
9887
9888       // Check for #1.
9889       bool TryNext = false;
9890       for (SDNode *Use : BasePtr.getNode()->uses()) {
9891         if (Use == Ptr.getNode())
9892           continue;
9893
9894         // If all the uses are load / store addresses, then don't do the
9895         // transformation.
9896         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9897           bool RealUse = false;
9898           for (SDNode *UseUse : Use->uses()) {
9899             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9900               RealUse = true;
9901           }
9902
9903           if (!RealUse) {
9904             TryNext = true;
9905             break;
9906           }
9907         }
9908       }
9909
9910       if (TryNext)
9911         continue;
9912
9913       // Check for #2
9914       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9915         SDValue Result = isLoad
9916           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9917                                BasePtr, Offset, AM)
9918           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9919                                 BasePtr, Offset, AM);
9920         ++PostIndexedNodes;
9921         ++NodesCombined;
9922         DEBUG(dbgs() << "\nReplacing.5 ";
9923               N->dump(&DAG);
9924               dbgs() << "\nWith: ";
9925               Result.getNode()->dump(&DAG);
9926               dbgs() << '\n');
9927         WorklistRemover DeadNodes(*this);
9928         if (isLoad) {
9929           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9930           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9931         } else {
9932           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9933         }
9934
9935         // Finally, since the node is now dead, remove it from the graph.
9936         deleteAndRecombine(N);
9937
9938         // Replace the uses of Use with uses of the updated base value.
9939         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9940                                       Result.getValue(isLoad ? 1 : 0));
9941         deleteAndRecombine(Op);
9942         return true;
9943       }
9944     }
9945   }
9946
9947   return false;
9948 }
9949
9950 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9951 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9952   ISD::MemIndexedMode AM = LD->getAddressingMode();
9953   assert(AM != ISD::UNINDEXED);
9954   SDValue BP = LD->getOperand(1);
9955   SDValue Inc = LD->getOperand(2);
9956
9957   // Some backends use TargetConstants for load offsets, but don't expect
9958   // TargetConstants in general ADD nodes. We can convert these constants into
9959   // regular Constants (if the constant is not opaque).
9960   assert((Inc.getOpcode() != ISD::TargetConstant ||
9961           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9962          "Cannot split out indexing using opaque target constants");
9963   if (Inc.getOpcode() == ISD::TargetConstant) {
9964     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9965     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9966                           ConstInc->getValueType(0));
9967   }
9968
9969   unsigned Opc =
9970       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9971   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9972 }
9973
9974 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9975   LoadSDNode *LD  = cast<LoadSDNode>(N);
9976   SDValue Chain = LD->getChain();
9977   SDValue Ptr   = LD->getBasePtr();
9978
9979   // If load is not volatile and there are no uses of the loaded value (and
9980   // the updated indexed value in case of indexed loads), change uses of the
9981   // chain value into uses of the chain input (i.e. delete the dead load).
9982   if (!LD->isVolatile()) {
9983     if (N->getValueType(1) == MVT::Other) {
9984       // Unindexed loads.
9985       if (!N->hasAnyUseOfValue(0)) {
9986         // It's not safe to use the two value CombineTo variant here. e.g.
9987         // v1, chain2 = load chain1, loc
9988         // v2, chain3 = load chain2, loc
9989         // v3         = add v2, c
9990         // Now we replace use of chain2 with chain1.  This makes the second load
9991         // isomorphic to the one we are deleting, and thus makes this load live.
9992         DEBUG(dbgs() << "\nReplacing.6 ";
9993               N->dump(&DAG);
9994               dbgs() << "\nWith chain: ";
9995               Chain.getNode()->dump(&DAG);
9996               dbgs() << "\n");
9997         WorklistRemover DeadNodes(*this);
9998         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9999
10000         if (N->use_empty())
10001           deleteAndRecombine(N);
10002
10003         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10004       }
10005     } else {
10006       // Indexed loads.
10007       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10008
10009       // If this load has an opaque TargetConstant offset, then we cannot split
10010       // the indexing into an add/sub directly (that TargetConstant may not be
10011       // valid for a different type of node, and we cannot convert an opaque
10012       // target constant into a regular constant).
10013       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10014                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10015
10016       if (!N->hasAnyUseOfValue(0) &&
10017           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10018         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10019         SDValue Index;
10020         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10021           Index = SplitIndexingFromLoad(LD);
10022           // Try to fold the base pointer arithmetic into subsequent loads and
10023           // stores.
10024           AddUsersToWorklist(N);
10025         } else
10026           Index = DAG.getUNDEF(N->getValueType(1));
10027         DEBUG(dbgs() << "\nReplacing.7 ";
10028               N->dump(&DAG);
10029               dbgs() << "\nWith: ";
10030               Undef.getNode()->dump(&DAG);
10031               dbgs() << " and 2 other values\n");
10032         WorklistRemover DeadNodes(*this);
10033         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10034         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10035         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10036         deleteAndRecombine(N);
10037         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10038       }
10039     }
10040   }
10041
10042   // If this load is directly stored, replace the load value with the stored
10043   // value.
10044   // TODO: Handle store large -> read small portion.
10045   // TODO: Handle TRUNCSTORE/LOADEXT
10046   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10047     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10048       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10049       if (PrevST->getBasePtr() == Ptr &&
10050           PrevST->getValue().getValueType() == N->getValueType(0))
10051       return CombineTo(N, Chain.getOperand(1), Chain);
10052     }
10053   }
10054
10055   // Try to infer better alignment information than the load already has.
10056   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10057     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10058       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10059         SDValue NewLoad =
10060                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10061                               LD->getValueType(0),
10062                               Chain, Ptr, LD->getPointerInfo(),
10063                               LD->getMemoryVT(),
10064                               LD->isVolatile(), LD->isNonTemporal(),
10065                               LD->isInvariant(), Align, LD->getAAInfo());
10066         if (NewLoad.getNode() != N)
10067           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10068       }
10069     }
10070   }
10071
10072   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10073                                                   : DAG.getSubtarget().useAA();
10074 #ifndef NDEBUG
10075   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10076       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10077     UseAA = false;
10078 #endif
10079   if (UseAA && LD->isUnindexed()) {
10080     // Walk up chain skipping non-aliasing memory nodes.
10081     SDValue BetterChain = FindBetterChain(N, Chain);
10082
10083     // If there is a better chain.
10084     if (Chain != BetterChain) {
10085       SDValue ReplLoad;
10086
10087       // Replace the chain to void dependency.
10088       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10089         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10090                                BetterChain, Ptr, LD->getMemOperand());
10091       } else {
10092         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10093                                   LD->getValueType(0),
10094                                   BetterChain, Ptr, LD->getMemoryVT(),
10095                                   LD->getMemOperand());
10096       }
10097
10098       // Create token factor to keep old chain connected.
10099       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10100                                   MVT::Other, Chain, ReplLoad.getValue(1));
10101
10102       // Make sure the new and old chains are cleaned up.
10103       AddToWorklist(Token.getNode());
10104
10105       // Replace uses with load result and token factor. Don't add users
10106       // to work list.
10107       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10108     }
10109   }
10110
10111   // Try transforming N to an indexed load.
10112   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10113     return SDValue(N, 0);
10114
10115   // Try to slice up N to more direct loads if the slices are mapped to
10116   // different register banks or pairing can take place.
10117   if (SliceUpLoad(N))
10118     return SDValue(N, 0);
10119
10120   return SDValue();
10121 }
10122
10123 namespace {
10124 /// \brief Helper structure used to slice a load in smaller loads.
10125 /// Basically a slice is obtained from the following sequence:
10126 /// Origin = load Ty1, Base
10127 /// Shift = srl Ty1 Origin, CstTy Amount
10128 /// Inst = trunc Shift to Ty2
10129 ///
10130 /// Then, it will be rewriten into:
10131 /// Slice = load SliceTy, Base + SliceOffset
10132 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10133 ///
10134 /// SliceTy is deduced from the number of bits that are actually used to
10135 /// build Inst.
10136 struct LoadedSlice {
10137   /// \brief Helper structure used to compute the cost of a slice.
10138   struct Cost {
10139     /// Are we optimizing for code size.
10140     bool ForCodeSize;
10141     /// Various cost.
10142     unsigned Loads;
10143     unsigned Truncates;
10144     unsigned CrossRegisterBanksCopies;
10145     unsigned ZExts;
10146     unsigned Shift;
10147
10148     Cost(bool ForCodeSize = false)
10149         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10150           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10151
10152     /// \brief Get the cost of one isolated slice.
10153     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10154         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10155           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10156       EVT TruncType = LS.Inst->getValueType(0);
10157       EVT LoadedType = LS.getLoadedType();
10158       if (TruncType != LoadedType &&
10159           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10160         ZExts = 1;
10161     }
10162
10163     /// \brief Account for slicing gain in the current cost.
10164     /// Slicing provide a few gains like removing a shift or a
10165     /// truncate. This method allows to grow the cost of the original
10166     /// load with the gain from this slice.
10167     void addSliceGain(const LoadedSlice &LS) {
10168       // Each slice saves a truncate.
10169       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10170       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10171                               LS.Inst->getValueType(0)))
10172         ++Truncates;
10173       // If there is a shift amount, this slice gets rid of it.
10174       if (LS.Shift)
10175         ++Shift;
10176       // If this slice can merge a cross register bank copy, account for it.
10177       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10178         ++CrossRegisterBanksCopies;
10179     }
10180
10181     Cost &operator+=(const Cost &RHS) {
10182       Loads += RHS.Loads;
10183       Truncates += RHS.Truncates;
10184       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10185       ZExts += RHS.ZExts;
10186       Shift += RHS.Shift;
10187       return *this;
10188     }
10189
10190     bool operator==(const Cost &RHS) const {
10191       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10192              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10193              ZExts == RHS.ZExts && Shift == RHS.Shift;
10194     }
10195
10196     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10197
10198     bool operator<(const Cost &RHS) const {
10199       // Assume cross register banks copies are as expensive as loads.
10200       // FIXME: Do we want some more target hooks?
10201       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10202       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10203       // Unless we are optimizing for code size, consider the
10204       // expensive operation first.
10205       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10206         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10207       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10208              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10209     }
10210
10211     bool operator>(const Cost &RHS) const { return RHS < *this; }
10212
10213     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10214
10215     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10216   };
10217   // The last instruction that represent the slice. This should be a
10218   // truncate instruction.
10219   SDNode *Inst;
10220   // The original load instruction.
10221   LoadSDNode *Origin;
10222   // The right shift amount in bits from the original load.
10223   unsigned Shift;
10224   // The DAG from which Origin came from.
10225   // This is used to get some contextual information about legal types, etc.
10226   SelectionDAG *DAG;
10227
10228   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10229               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10230       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10231
10232   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10233   /// \return Result is \p BitWidth and has used bits set to 1 and
10234   ///         not used bits set to 0.
10235   APInt getUsedBits() const {
10236     // Reproduce the trunc(lshr) sequence:
10237     // - Start from the truncated value.
10238     // - Zero extend to the desired bit width.
10239     // - Shift left.
10240     assert(Origin && "No original load to compare against.");
10241     unsigned BitWidth = Origin->getValueSizeInBits(0);
10242     assert(Inst && "This slice is not bound to an instruction");
10243     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10244            "Extracted slice is bigger than the whole type!");
10245     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10246     UsedBits.setAllBits();
10247     UsedBits = UsedBits.zext(BitWidth);
10248     UsedBits <<= Shift;
10249     return UsedBits;
10250   }
10251
10252   /// \brief Get the size of the slice to be loaded in bytes.
10253   unsigned getLoadedSize() const {
10254     unsigned SliceSize = getUsedBits().countPopulation();
10255     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10256     return SliceSize / 8;
10257   }
10258
10259   /// \brief Get the type that will be loaded for this slice.
10260   /// Note: This may not be the final type for the slice.
10261   EVT getLoadedType() const {
10262     assert(DAG && "Missing context");
10263     LLVMContext &Ctxt = *DAG->getContext();
10264     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10265   }
10266
10267   /// \brief Get the alignment of the load used for this slice.
10268   unsigned getAlignment() const {
10269     unsigned Alignment = Origin->getAlignment();
10270     unsigned Offset = getOffsetFromBase();
10271     if (Offset != 0)
10272       Alignment = MinAlign(Alignment, Alignment + Offset);
10273     return Alignment;
10274   }
10275
10276   /// \brief Check if this slice can be rewritten with legal operations.
10277   bool isLegal() const {
10278     // An invalid slice is not legal.
10279     if (!Origin || !Inst || !DAG)
10280       return false;
10281
10282     // Offsets are for indexed load only, we do not handle that.
10283     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10284       return false;
10285
10286     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10287
10288     // Check that the type is legal.
10289     EVT SliceType = getLoadedType();
10290     if (!TLI.isTypeLegal(SliceType))
10291       return false;
10292
10293     // Check that the load is legal for this type.
10294     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10295       return false;
10296
10297     // Check that the offset can be computed.
10298     // 1. Check its type.
10299     EVT PtrType = Origin->getBasePtr().getValueType();
10300     if (PtrType == MVT::Untyped || PtrType.isExtended())
10301       return false;
10302
10303     // 2. Check that it fits in the immediate.
10304     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10305       return false;
10306
10307     // 3. Check that the computation is legal.
10308     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10309       return false;
10310
10311     // Check that the zext is legal if it needs one.
10312     EVT TruncateType = Inst->getValueType(0);
10313     if (TruncateType != SliceType &&
10314         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10315       return false;
10316
10317     return true;
10318   }
10319
10320   /// \brief Get the offset in bytes of this slice in the original chunk of
10321   /// bits.
10322   /// \pre DAG != nullptr.
10323   uint64_t getOffsetFromBase() const {
10324     assert(DAG && "Missing context.");
10325     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10326     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10327     uint64_t Offset = Shift / 8;
10328     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10329     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10330            "The size of the original loaded type is not a multiple of a"
10331            " byte.");
10332     // If Offset is bigger than TySizeInBytes, it means we are loading all
10333     // zeros. This should have been optimized before in the process.
10334     assert(TySizeInBytes > Offset &&
10335            "Invalid shift amount for given loaded size");
10336     if (IsBigEndian)
10337       Offset = TySizeInBytes - Offset - getLoadedSize();
10338     return Offset;
10339   }
10340
10341   /// \brief Generate the sequence of instructions to load the slice
10342   /// represented by this object and redirect the uses of this slice to
10343   /// this new sequence of instructions.
10344   /// \pre this->Inst && this->Origin are valid Instructions and this
10345   /// object passed the legal check: LoadedSlice::isLegal returned true.
10346   /// \return The last instruction of the sequence used to load the slice.
10347   SDValue loadSlice() const {
10348     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10349     const SDValue &OldBaseAddr = Origin->getBasePtr();
10350     SDValue BaseAddr = OldBaseAddr;
10351     // Get the offset in that chunk of bytes w.r.t. the endianess.
10352     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10353     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10354     if (Offset) {
10355       // BaseAddr = BaseAddr + Offset.
10356       EVT ArithType = BaseAddr.getValueType();
10357       SDLoc DL(Origin);
10358       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10359                               DAG->getConstant(Offset, DL, ArithType));
10360     }
10361
10362     // Create the type of the loaded slice according to its size.
10363     EVT SliceType = getLoadedType();
10364
10365     // Create the load for the slice.
10366     SDValue LastInst = DAG->getLoad(
10367         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10368         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10369         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10370     // If the final type is not the same as the loaded type, this means that
10371     // we have to pad with zero. Create a zero extend for that.
10372     EVT FinalType = Inst->getValueType(0);
10373     if (SliceType != FinalType)
10374       LastInst =
10375           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10376     return LastInst;
10377   }
10378
10379   /// \brief Check if this slice can be merged with an expensive cross register
10380   /// bank copy. E.g.,
10381   /// i = load i32
10382   /// f = bitcast i32 i to float
10383   bool canMergeExpensiveCrossRegisterBankCopy() const {
10384     if (!Inst || !Inst->hasOneUse())
10385       return false;
10386     SDNode *Use = *Inst->use_begin();
10387     if (Use->getOpcode() != ISD::BITCAST)
10388       return false;
10389     assert(DAG && "Missing context");
10390     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10391     EVT ResVT = Use->getValueType(0);
10392     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10393     const TargetRegisterClass *ArgRC =
10394         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10395     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10396       return false;
10397
10398     // At this point, we know that we perform a cross-register-bank copy.
10399     // Check if it is expensive.
10400     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10401     // Assume bitcasts are cheap, unless both register classes do not
10402     // explicitly share a common sub class.
10403     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10404       return false;
10405
10406     // Check if it will be merged with the load.
10407     // 1. Check the alignment constraint.
10408     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10409         ResVT.getTypeForEVT(*DAG->getContext()));
10410
10411     if (RequiredAlignment > getAlignment())
10412       return false;
10413
10414     // 2. Check that the load is a legal operation for that type.
10415     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10416       return false;
10417
10418     // 3. Check that we do not have a zext in the way.
10419     if (Inst->getValueType(0) != getLoadedType())
10420       return false;
10421
10422     return true;
10423   }
10424 };
10425 }
10426
10427 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10428 /// \p UsedBits looks like 0..0 1..1 0..0.
10429 static bool areUsedBitsDense(const APInt &UsedBits) {
10430   // If all the bits are one, this is dense!
10431   if (UsedBits.isAllOnesValue())
10432     return true;
10433
10434   // Get rid of the unused bits on the right.
10435   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10436   // Get rid of the unused bits on the left.
10437   if (NarrowedUsedBits.countLeadingZeros())
10438     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10439   // Check that the chunk of bits is completely used.
10440   return NarrowedUsedBits.isAllOnesValue();
10441 }
10442
10443 /// \brief Check whether or not \p First and \p Second are next to each other
10444 /// in memory. This means that there is no hole between the bits loaded
10445 /// by \p First and the bits loaded by \p Second.
10446 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10447                                      const LoadedSlice &Second) {
10448   assert(First.Origin == Second.Origin && First.Origin &&
10449          "Unable to match different memory origins.");
10450   APInt UsedBits = First.getUsedBits();
10451   assert((UsedBits & Second.getUsedBits()) == 0 &&
10452          "Slices are not supposed to overlap.");
10453   UsedBits |= Second.getUsedBits();
10454   return areUsedBitsDense(UsedBits);
10455 }
10456
10457 /// \brief Adjust the \p GlobalLSCost according to the target
10458 /// paring capabilities and the layout of the slices.
10459 /// \pre \p GlobalLSCost should account for at least as many loads as
10460 /// there is in the slices in \p LoadedSlices.
10461 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10462                                  LoadedSlice::Cost &GlobalLSCost) {
10463   unsigned NumberOfSlices = LoadedSlices.size();
10464   // If there is less than 2 elements, no pairing is possible.
10465   if (NumberOfSlices < 2)
10466     return;
10467
10468   // Sort the slices so that elements that are likely to be next to each
10469   // other in memory are next to each other in the list.
10470   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10471             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10472     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10473     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10474   });
10475   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10476   // First (resp. Second) is the first (resp. Second) potentially candidate
10477   // to be placed in a paired load.
10478   const LoadedSlice *First = nullptr;
10479   const LoadedSlice *Second = nullptr;
10480   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10481                 // Set the beginning of the pair.
10482                                                            First = Second) {
10483
10484     Second = &LoadedSlices[CurrSlice];
10485
10486     // If First is NULL, it means we start a new pair.
10487     // Get to the next slice.
10488     if (!First)
10489       continue;
10490
10491     EVT LoadedType = First->getLoadedType();
10492
10493     // If the types of the slices are different, we cannot pair them.
10494     if (LoadedType != Second->getLoadedType())
10495       continue;
10496
10497     // Check if the target supplies paired loads for this type.
10498     unsigned RequiredAlignment = 0;
10499     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10500       // move to the next pair, this type is hopeless.
10501       Second = nullptr;
10502       continue;
10503     }
10504     // Check if we meet the alignment requirement.
10505     if (RequiredAlignment > First->getAlignment())
10506       continue;
10507
10508     // Check that both loads are next to each other in memory.
10509     if (!areSlicesNextToEachOther(*First, *Second))
10510       continue;
10511
10512     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10513     --GlobalLSCost.Loads;
10514     // Move to the next pair.
10515     Second = nullptr;
10516   }
10517 }
10518
10519 /// \brief Check the profitability of all involved LoadedSlice.
10520 /// Currently, it is considered profitable if there is exactly two
10521 /// involved slices (1) which are (2) next to each other in memory, and
10522 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10523 ///
10524 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10525 /// the elements themselves.
10526 ///
10527 /// FIXME: When the cost model will be mature enough, we can relax
10528 /// constraints (1) and (2).
10529 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10530                                 const APInt &UsedBits, bool ForCodeSize) {
10531   unsigned NumberOfSlices = LoadedSlices.size();
10532   if (StressLoadSlicing)
10533     return NumberOfSlices > 1;
10534
10535   // Check (1).
10536   if (NumberOfSlices != 2)
10537     return false;
10538
10539   // Check (2).
10540   if (!areUsedBitsDense(UsedBits))
10541     return false;
10542
10543   // Check (3).
10544   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10545   // The original code has one big load.
10546   OrigCost.Loads = 1;
10547   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10548     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10549     // Accumulate the cost of all the slices.
10550     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10551     GlobalSlicingCost += SliceCost;
10552
10553     // Account as cost in the original configuration the gain obtained
10554     // with the current slices.
10555     OrigCost.addSliceGain(LS);
10556   }
10557
10558   // If the target supports paired load, adjust the cost accordingly.
10559   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10560   return OrigCost > GlobalSlicingCost;
10561 }
10562
10563 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10564 /// operations, split it in the various pieces being extracted.
10565 ///
10566 /// This sort of thing is introduced by SROA.
10567 /// This slicing takes care not to insert overlapping loads.
10568 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10569 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10570   if (Level < AfterLegalizeDAG)
10571     return false;
10572
10573   LoadSDNode *LD = cast<LoadSDNode>(N);
10574   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10575       !LD->getValueType(0).isInteger())
10576     return false;
10577
10578   // Keep track of already used bits to detect overlapping values.
10579   // In that case, we will just abort the transformation.
10580   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10581
10582   SmallVector<LoadedSlice, 4> LoadedSlices;
10583
10584   // Check if this load is used as several smaller chunks of bits.
10585   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10586   // of computation for each trunc.
10587   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10588        UI != UIEnd; ++UI) {
10589     // Skip the uses of the chain.
10590     if (UI.getUse().getResNo() != 0)
10591       continue;
10592
10593     SDNode *User = *UI;
10594     unsigned Shift = 0;
10595
10596     // Check if this is a trunc(lshr).
10597     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10598         isa<ConstantSDNode>(User->getOperand(1))) {
10599       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10600       User = *User->use_begin();
10601     }
10602
10603     // At this point, User is a Truncate, iff we encountered, trunc or
10604     // trunc(lshr).
10605     if (User->getOpcode() != ISD::TRUNCATE)
10606       return false;
10607
10608     // The width of the type must be a power of 2 and greater than 8-bits.
10609     // Otherwise the load cannot be represented in LLVM IR.
10610     // Moreover, if we shifted with a non-8-bits multiple, the slice
10611     // will be across several bytes. We do not support that.
10612     unsigned Width = User->getValueSizeInBits(0);
10613     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10614       return 0;
10615
10616     // Build the slice for this chain of computations.
10617     LoadedSlice LS(User, LD, Shift, &DAG);
10618     APInt CurrentUsedBits = LS.getUsedBits();
10619
10620     // Check if this slice overlaps with another.
10621     if ((CurrentUsedBits & UsedBits) != 0)
10622       return false;
10623     // Update the bits used globally.
10624     UsedBits |= CurrentUsedBits;
10625
10626     // Check if the new slice would be legal.
10627     if (!LS.isLegal())
10628       return false;
10629
10630     // Record the slice.
10631     LoadedSlices.push_back(LS);
10632   }
10633
10634   // Abort slicing if it does not seem to be profitable.
10635   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10636     return false;
10637
10638   ++SlicedLoads;
10639
10640   // Rewrite each chain to use an independent load.
10641   // By construction, each chain can be represented by a unique load.
10642
10643   // Prepare the argument for the new token factor for all the slices.
10644   SmallVector<SDValue, 8> ArgChains;
10645   for (SmallVectorImpl<LoadedSlice>::const_iterator
10646            LSIt = LoadedSlices.begin(),
10647            LSItEnd = LoadedSlices.end();
10648        LSIt != LSItEnd; ++LSIt) {
10649     SDValue SliceInst = LSIt->loadSlice();
10650     CombineTo(LSIt->Inst, SliceInst, true);
10651     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10652       SliceInst = SliceInst.getOperand(0);
10653     assert(SliceInst->getOpcode() == ISD::LOAD &&
10654            "It takes more than a zext to get to the loaded slice!!");
10655     ArgChains.push_back(SliceInst.getValue(1));
10656   }
10657
10658   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10659                               ArgChains);
10660   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10661   return true;
10662 }
10663
10664 /// Check to see if V is (and load (ptr), imm), where the load is having
10665 /// specific bytes cleared out.  If so, return the byte size being masked out
10666 /// and the shift amount.
10667 static std::pair<unsigned, unsigned>
10668 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10669   std::pair<unsigned, unsigned> Result(0, 0);
10670
10671   // Check for the structure we're looking for.
10672   if (V->getOpcode() != ISD::AND ||
10673       !isa<ConstantSDNode>(V->getOperand(1)) ||
10674       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10675     return Result;
10676
10677   // Check the chain and pointer.
10678   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10679   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10680
10681   // The store should be chained directly to the load or be an operand of a
10682   // tokenfactor.
10683   if (LD == Chain.getNode())
10684     ; // ok.
10685   else if (Chain->getOpcode() != ISD::TokenFactor)
10686     return Result; // Fail.
10687   else {
10688     bool isOk = false;
10689     for (const SDValue &ChainOp : Chain->op_values())
10690       if (ChainOp.getNode() == LD) {
10691         isOk = true;
10692         break;
10693       }
10694     if (!isOk) return Result;
10695   }
10696
10697   // This only handles simple types.
10698   if (V.getValueType() != MVT::i16 &&
10699       V.getValueType() != MVT::i32 &&
10700       V.getValueType() != MVT::i64)
10701     return Result;
10702
10703   // Check the constant mask.  Invert it so that the bits being masked out are
10704   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10705   // follow the sign bit for uniformity.
10706   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10707   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10708   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10709   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10710   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10711   if (NotMaskLZ == 64) return Result;  // All zero mask.
10712
10713   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10714   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10715     return Result;
10716
10717   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10718   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10719     NotMaskLZ -= 64-V.getValueSizeInBits();
10720
10721   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10722   switch (MaskedBytes) {
10723   case 1:
10724   case 2:
10725   case 4: break;
10726   default: return Result; // All one mask, or 5-byte mask.
10727   }
10728
10729   // Verify that the first bit starts at a multiple of mask so that the access
10730   // is aligned the same as the access width.
10731   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10732
10733   Result.first = MaskedBytes;
10734   Result.second = NotMaskTZ/8;
10735   return Result;
10736 }
10737
10738
10739 /// Check to see if IVal is something that provides a value as specified by
10740 /// MaskInfo. If so, replace the specified store with a narrower store of
10741 /// truncated IVal.
10742 static SDNode *
10743 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10744                                 SDValue IVal, StoreSDNode *St,
10745                                 DAGCombiner *DC) {
10746   unsigned NumBytes = MaskInfo.first;
10747   unsigned ByteShift = MaskInfo.second;
10748   SelectionDAG &DAG = DC->getDAG();
10749
10750   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10751   // that uses this.  If not, this is not a replacement.
10752   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10753                                   ByteShift*8, (ByteShift+NumBytes)*8);
10754   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10755
10756   // Check that it is legal on the target to do this.  It is legal if the new
10757   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10758   // legalization.
10759   MVT VT = MVT::getIntegerVT(NumBytes*8);
10760   if (!DC->isTypeLegal(VT))
10761     return nullptr;
10762
10763   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10764   // shifted by ByteShift and truncated down to NumBytes.
10765   if (ByteShift) {
10766     SDLoc DL(IVal);
10767     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10768                        DAG.getConstant(ByteShift*8, DL,
10769                                     DC->getShiftAmountTy(IVal.getValueType())));
10770   }
10771
10772   // Figure out the offset for the store and the alignment of the access.
10773   unsigned StOffset;
10774   unsigned NewAlign = St->getAlignment();
10775
10776   if (DAG.getDataLayout().isLittleEndian())
10777     StOffset = ByteShift;
10778   else
10779     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10780
10781   SDValue Ptr = St->getBasePtr();
10782   if (StOffset) {
10783     SDLoc DL(IVal);
10784     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10785                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10786     NewAlign = MinAlign(NewAlign, StOffset);
10787   }
10788
10789   // Truncate down to the new size.
10790   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10791
10792   ++OpsNarrowed;
10793   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10794                       St->getPointerInfo().getWithOffset(StOffset),
10795                       false, false, NewAlign).getNode();
10796 }
10797
10798
10799 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10800 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10801 /// narrowing the load and store if it would end up being a win for performance
10802 /// or code size.
10803 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10804   StoreSDNode *ST  = cast<StoreSDNode>(N);
10805   if (ST->isVolatile())
10806     return SDValue();
10807
10808   SDValue Chain = ST->getChain();
10809   SDValue Value = ST->getValue();
10810   SDValue Ptr   = ST->getBasePtr();
10811   EVT VT = Value.getValueType();
10812
10813   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10814     return SDValue();
10815
10816   unsigned Opc = Value.getOpcode();
10817
10818   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10819   // is a byte mask indicating a consecutive number of bytes, check to see if
10820   // Y is known to provide just those bytes.  If so, we try to replace the
10821   // load + replace + store sequence with a single (narrower) store, which makes
10822   // the load dead.
10823   if (Opc == ISD::OR) {
10824     std::pair<unsigned, unsigned> MaskedLoad;
10825     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10826     if (MaskedLoad.first)
10827       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10828                                                   Value.getOperand(1), ST,this))
10829         return SDValue(NewST, 0);
10830
10831     // Or is commutative, so try swapping X and Y.
10832     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10833     if (MaskedLoad.first)
10834       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10835                                                   Value.getOperand(0), ST,this))
10836         return SDValue(NewST, 0);
10837   }
10838
10839   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10840       Value.getOperand(1).getOpcode() != ISD::Constant)
10841     return SDValue();
10842
10843   SDValue N0 = Value.getOperand(0);
10844   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10845       Chain == SDValue(N0.getNode(), 1)) {
10846     LoadSDNode *LD = cast<LoadSDNode>(N0);
10847     if (LD->getBasePtr() != Ptr ||
10848         LD->getPointerInfo().getAddrSpace() !=
10849         ST->getPointerInfo().getAddrSpace())
10850       return SDValue();
10851
10852     // Find the type to narrow it the load / op / store to.
10853     SDValue N1 = Value.getOperand(1);
10854     unsigned BitWidth = N1.getValueSizeInBits();
10855     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10856     if (Opc == ISD::AND)
10857       Imm ^= APInt::getAllOnesValue(BitWidth);
10858     if (Imm == 0 || Imm.isAllOnesValue())
10859       return SDValue();
10860     unsigned ShAmt = Imm.countTrailingZeros();
10861     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10862     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10863     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10864     // The narrowing should be profitable, the load/store operation should be
10865     // legal (or custom) and the store size should be equal to the NewVT width.
10866     while (NewBW < BitWidth &&
10867            (NewVT.getStoreSizeInBits() != NewBW ||
10868             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10869             !TLI.isNarrowingProfitable(VT, NewVT))) {
10870       NewBW = NextPowerOf2(NewBW);
10871       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10872     }
10873     if (NewBW >= BitWidth)
10874       return SDValue();
10875
10876     // If the lsb changed does not start at the type bitwidth boundary,
10877     // start at the previous one.
10878     if (ShAmt % NewBW)
10879       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10880     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10881                                    std::min(BitWidth, ShAmt + NewBW));
10882     if ((Imm & Mask) == Imm) {
10883       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10884       if (Opc == ISD::AND)
10885         NewImm ^= APInt::getAllOnesValue(NewBW);
10886       uint64_t PtrOff = ShAmt / 8;
10887       // For big endian targets, we need to adjust the offset to the pointer to
10888       // load the correct bytes.
10889       if (DAG.getDataLayout().isBigEndian())
10890         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10891
10892       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10893       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10894       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10895         return SDValue();
10896
10897       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10898                                    Ptr.getValueType(), Ptr,
10899                                    DAG.getConstant(PtrOff, SDLoc(LD),
10900                                                    Ptr.getValueType()));
10901       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10902                                   LD->getChain(), NewPtr,
10903                                   LD->getPointerInfo().getWithOffset(PtrOff),
10904                                   LD->isVolatile(), LD->isNonTemporal(),
10905                                   LD->isInvariant(), NewAlign,
10906                                   LD->getAAInfo());
10907       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10908                                    DAG.getConstant(NewImm, SDLoc(Value),
10909                                                    NewVT));
10910       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10911                                    NewVal, NewPtr,
10912                                    ST->getPointerInfo().getWithOffset(PtrOff),
10913                                    false, false, NewAlign);
10914
10915       AddToWorklist(NewPtr.getNode());
10916       AddToWorklist(NewLD.getNode());
10917       AddToWorklist(NewVal.getNode());
10918       WorklistRemover DeadNodes(*this);
10919       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10920       ++OpsNarrowed;
10921       return NewST;
10922     }
10923   }
10924
10925   return SDValue();
10926 }
10927
10928 /// For a given floating point load / store pair, if the load value isn't used
10929 /// by any other operations, then consider transforming the pair to integer
10930 /// load / store operations if the target deems the transformation profitable.
10931 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10932   StoreSDNode *ST  = cast<StoreSDNode>(N);
10933   SDValue Chain = ST->getChain();
10934   SDValue Value = ST->getValue();
10935   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10936       Value.hasOneUse() &&
10937       Chain == SDValue(Value.getNode(), 1)) {
10938     LoadSDNode *LD = cast<LoadSDNode>(Value);
10939     EVT VT = LD->getMemoryVT();
10940     if (!VT.isFloatingPoint() ||
10941         VT != ST->getMemoryVT() ||
10942         LD->isNonTemporal() ||
10943         ST->isNonTemporal() ||
10944         LD->getPointerInfo().getAddrSpace() != 0 ||
10945         ST->getPointerInfo().getAddrSpace() != 0)
10946       return SDValue();
10947
10948     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10949     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10950         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10951         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10952         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10953       return SDValue();
10954
10955     unsigned LDAlign = LD->getAlignment();
10956     unsigned STAlign = ST->getAlignment();
10957     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10958     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10959     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10960       return SDValue();
10961
10962     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10963                                 LD->getChain(), LD->getBasePtr(),
10964                                 LD->getPointerInfo(),
10965                                 false, false, false, LDAlign);
10966
10967     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10968                                  NewLD, ST->getBasePtr(),
10969                                  ST->getPointerInfo(),
10970                                  false, false, STAlign);
10971
10972     AddToWorklist(NewLD.getNode());
10973     AddToWorklist(NewST.getNode());
10974     WorklistRemover DeadNodes(*this);
10975     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10976     ++LdStFP2Int;
10977     return NewST;
10978   }
10979
10980   return SDValue();
10981 }
10982
10983 namespace {
10984 /// Helper struct to parse and store a memory address as base + index + offset.
10985 /// We ignore sign extensions when it is safe to do so.
10986 /// The following two expressions are not equivalent. To differentiate we need
10987 /// to store whether there was a sign extension involved in the index
10988 /// computation.
10989 ///  (load (i64 add (i64 copyfromreg %c)
10990 ///                 (i64 signextend (add (i8 load %index)
10991 ///                                      (i8 1))))
10992 /// vs
10993 ///
10994 /// (load (i64 add (i64 copyfromreg %c)
10995 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10996 ///                                         (i32 1)))))
10997 struct BaseIndexOffset {
10998   SDValue Base;
10999   SDValue Index;
11000   int64_t Offset;
11001   bool IsIndexSignExt;
11002
11003   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11004
11005   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11006                   bool IsIndexSignExt) :
11007     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11008
11009   bool equalBaseIndex(const BaseIndexOffset &Other) {
11010     return Other.Base == Base && Other.Index == Index &&
11011       Other.IsIndexSignExt == IsIndexSignExt;
11012   }
11013
11014   /// Parses tree in Ptr for base, index, offset addresses.
11015   static BaseIndexOffset match(SDValue Ptr) {
11016     bool IsIndexSignExt = false;
11017
11018     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11019     // instruction, then it could be just the BASE or everything else we don't
11020     // know how to handle. Just use Ptr as BASE and give up.
11021     if (Ptr->getOpcode() != ISD::ADD)
11022       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11023
11024     // We know that we have at least an ADD instruction. Try to pattern match
11025     // the simple case of BASE + OFFSET.
11026     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11027       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11028       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11029                               IsIndexSignExt);
11030     }
11031
11032     // Inside a loop the current BASE pointer is calculated using an ADD and a
11033     // MUL instruction. In this case Ptr is the actual BASE pointer.
11034     // (i64 add (i64 %array_ptr)
11035     //          (i64 mul (i64 %induction_var)
11036     //                   (i64 %element_size)))
11037     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11038       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11039
11040     // Look at Base + Index + Offset cases.
11041     SDValue Base = Ptr->getOperand(0);
11042     SDValue IndexOffset = Ptr->getOperand(1);
11043
11044     // Skip signextends.
11045     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11046       IndexOffset = IndexOffset->getOperand(0);
11047       IsIndexSignExt = true;
11048     }
11049
11050     // Either the case of Base + Index (no offset) or something else.
11051     if (IndexOffset->getOpcode() != ISD::ADD)
11052       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11053
11054     // Now we have the case of Base + Index + offset.
11055     SDValue Index = IndexOffset->getOperand(0);
11056     SDValue Offset = IndexOffset->getOperand(1);
11057
11058     if (!isa<ConstantSDNode>(Offset))
11059       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11060
11061     // Ignore signextends.
11062     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11063       Index = Index->getOperand(0);
11064       IsIndexSignExt = true;
11065     } else IsIndexSignExt = false;
11066
11067     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11068     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11069   }
11070 };
11071 } // namespace
11072
11073 // This is a helper function for visitMUL to check the profitability
11074 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11075 // MulNode is the original multiply, AddNode is (add x, c1),
11076 // and ConstNode is c2.
11077 //
11078 // If the (add x, c1) has multiple uses, we could increase
11079 // the number of adds if we make this transformation.
11080 // It would only be worth doing this if we can remove a
11081 // multiply in the process. Check for that here.
11082 // To illustrate:
11083 //     (A + c1) * c3
11084 //     (A + c2) * c3
11085 // We're checking for cases where we have common "c3 * A" expressions.
11086 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11087                                               SDValue &AddNode,
11088                                               SDValue &ConstNode) {
11089   APInt Val;
11090
11091   // If the add only has one use, this would be OK to do.
11092   if (AddNode.getNode()->hasOneUse())
11093     return true;
11094
11095   // Walk all the users of the constant with which we're multiplying.
11096   for (SDNode *Use : ConstNode->uses()) {
11097
11098     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11099       continue;
11100
11101     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11102       SDNode *OtherOp;
11103       SDNode *MulVar = AddNode.getOperand(0).getNode();
11104
11105       // OtherOp is what we're multiplying against the constant.
11106       if (Use->getOperand(0) == ConstNode)
11107         OtherOp = Use->getOperand(1).getNode();
11108       else
11109         OtherOp = Use->getOperand(0).getNode();
11110
11111       // Check to see if multiply is with the same operand of our "add".
11112       //
11113       //     ConstNode  = CONST
11114       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11115       //     ...
11116       //     AddNode  = (A + c1)  <-- MulVar is A.
11117       //         = AddNode * ConstNode   <-- current visiting instruction.
11118       //
11119       // If we make this transformation, we will have a common
11120       // multiply (ConstNode * A) that we can save.
11121       if (OtherOp == MulVar)
11122         return true;
11123
11124       // Now check to see if a future expansion will give us a common
11125       // multiply.
11126       //
11127       //     ConstNode  = CONST
11128       //     AddNode    = (A + c1)
11129       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11130       //     ...
11131       //     OtherOp = (A + c2)
11132       //     Use     = OtherOp * ConstNode <-- visiting Use.
11133       //
11134       // If we make this transformation, we will have a common
11135       // multiply (CONST * A) after we also do the same transformation
11136       // to the "t2" instruction.
11137       if (OtherOp->getOpcode() == ISD::ADD &&
11138           isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11139           OtherOp->getOperand(0).getNode() == MulVar)
11140         return true;
11141     }
11142   }
11143
11144   // Didn't find a case where this would be profitable.
11145   return false;
11146 }
11147
11148 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11149                                                   SDLoc SL,
11150                                                   ArrayRef<MemOpLink> Stores,
11151                                                   SmallVectorImpl<SDValue> &Chains,
11152                                                   EVT Ty) const {
11153   SmallVector<SDValue, 8> BuildVector;
11154
11155   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11156     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11157     Chains.push_back(St->getChain());
11158     BuildVector.push_back(St->getValue());
11159   }
11160
11161   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
11162 }
11163
11164 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11165                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11166                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11167   // Make sure we have something to merge.
11168   if (NumStores < 2)
11169     return false;
11170
11171   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11172   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11173   unsigned LatestNodeUsed = 0;
11174
11175   for (unsigned i=0; i < NumStores; ++i) {
11176     // Find a chain for the new wide-store operand. Notice that some
11177     // of the store nodes that we found may not be selected for inclusion
11178     // in the wide store. The chain we use needs to be the chain of the
11179     // latest store node which is *used* and replaced by the wide store.
11180     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11181       LatestNodeUsed = i;
11182   }
11183
11184   SmallVector<SDValue, 8> Chains;
11185
11186   // The latest Node in the DAG.
11187   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11188   SDLoc DL(StoreNodes[0].MemNode);
11189
11190   SDValue StoredVal;
11191   if (UseVector) {
11192     bool IsVec = MemVT.isVector();
11193     unsigned Elts = NumStores;
11194     if (IsVec) {
11195       // When merging vector stores, get the total number of elements.
11196       Elts *= MemVT.getVectorNumElements();
11197     }
11198     // Get the type for the merged vector store.
11199     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11200     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11201
11202     if (IsConstantSrc) {
11203       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11204     } else {
11205       SmallVector<SDValue, 8> Ops;
11206       for (unsigned i = 0; i < NumStores; ++i) {
11207         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11208         SDValue Val = St->getValue();
11209         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11210         if (Val.getValueType() != MemVT)
11211           return false;
11212         Ops.push_back(Val);
11213         Chains.push_back(St->getChain());
11214       }
11215
11216       // Build the extracted vector elements back into a vector.
11217       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11218                               DL, Ty, Ops);    }
11219   } else {
11220     // We should always use a vector store when merging extracted vector
11221     // elements, so this path implies a store of constants.
11222     assert(IsConstantSrc && "Merged vector elements should use vector store");
11223
11224     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11225     APInt StoreInt(SizeInBits, 0);
11226
11227     // Construct a single integer constant which is made of the smaller
11228     // constant inputs.
11229     bool IsLE = DAG.getDataLayout().isLittleEndian();
11230     for (unsigned i = 0; i < NumStores; ++i) {
11231       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11232       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11233       Chains.push_back(St->getChain());
11234
11235       SDValue Val = St->getValue();
11236       StoreInt <<= ElementSizeBytes * 8;
11237       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11238         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11239       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11240         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11241       } else {
11242         llvm_unreachable("Invalid constant element type");
11243       }
11244     }
11245
11246     // Create the new Load and Store operations.
11247     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11248     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11249   }
11250
11251   assert(!Chains.empty());
11252
11253   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11254   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11255                                   FirstInChain->getBasePtr(),
11256                                   FirstInChain->getPointerInfo(),
11257                                   false, false,
11258                                   FirstInChain->getAlignment());
11259
11260   // Replace the last store with the new store
11261   CombineTo(LatestOp, NewStore);
11262   // Erase all other stores.
11263   for (unsigned i = 0; i < NumStores; ++i) {
11264     if (StoreNodes[i].MemNode == LatestOp)
11265       continue;
11266     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11267     // ReplaceAllUsesWith will replace all uses that existed when it was
11268     // called, but graph optimizations may cause new ones to appear. For
11269     // example, the case in pr14333 looks like
11270     //
11271     //  St's chain -> St -> another store -> X
11272     //
11273     // And the only difference from St to the other store is the chain.
11274     // When we change it's chain to be St's chain they become identical,
11275     // get CSEed and the net result is that X is now a use of St.
11276     // Since we know that St is redundant, just iterate.
11277     while (!St->use_empty())
11278       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11279     deleteAndRecombine(St);
11280   }
11281
11282   return true;
11283 }
11284
11285 void DAGCombiner::getStoreMergeAndAliasCandidates(
11286     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11287     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11288   // This holds the base pointer, index, and the offset in bytes from the base
11289   // pointer.
11290   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11291
11292   // We must have a base and an offset.
11293   if (!BasePtr.Base.getNode())
11294     return;
11295
11296   // Do not handle stores to undef base pointers.
11297   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11298     return;
11299
11300   // Walk up the chain and look for nodes with offsets from the same
11301   // base pointer. Stop when reaching an instruction with a different kind
11302   // or instruction which has a different base pointer.
11303   EVT MemVT = St->getMemoryVT();
11304   unsigned Seq = 0;
11305   StoreSDNode *Index = St;
11306
11307
11308   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11309                                                   : DAG.getSubtarget().useAA();
11310
11311   if (UseAA) {
11312     // Look at other users of the same chain. Stores on the same chain do not
11313     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11314     // to be on the same chain, so don't bother looking at adjacent chains.
11315
11316     SDValue Chain = St->getChain();
11317     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11318       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11319         if (I.getOperandNo() != 0)
11320           continue;
11321
11322         if (OtherST->isVolatile() || OtherST->isIndexed())
11323           continue;
11324
11325         if (OtherST->getMemoryVT() != MemVT)
11326           continue;
11327
11328         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11329
11330         if (Ptr.equalBaseIndex(BasePtr))
11331           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11332       }
11333     }
11334
11335     return;
11336   }
11337
11338   while (Index) {
11339     // If the chain has more than one use, then we can't reorder the mem ops.
11340     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11341       break;
11342
11343     // Find the base pointer and offset for this memory node.
11344     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11345
11346     // Check that the base pointer is the same as the original one.
11347     if (!Ptr.equalBaseIndex(BasePtr))
11348       break;
11349
11350     // The memory operands must not be volatile.
11351     if (Index->isVolatile() || Index->isIndexed())
11352       break;
11353
11354     // No truncation.
11355     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11356       if (St->isTruncatingStore())
11357         break;
11358
11359     // The stored memory type must be the same.
11360     if (Index->getMemoryVT() != MemVT)
11361       break;
11362
11363     // We do not allow under-aligned stores in order to prevent
11364     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11365     // be irrelevant here; what MATTERS is that we not move memory
11366     // operations that potentially overlap past each-other.
11367     if (Index->getAlignment() < MemVT.getStoreSize())
11368       break;
11369
11370     // We found a potential memory operand to merge.
11371     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11372
11373     // Find the next memory operand in the chain. If the next operand in the
11374     // chain is a store then move up and continue the scan with the next
11375     // memory operand. If the next operand is a load save it and use alias
11376     // information to check if it interferes with anything.
11377     SDNode *NextInChain = Index->getChain().getNode();
11378     while (1) {
11379       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11380         // We found a store node. Use it for the next iteration.
11381         Index = STn;
11382         break;
11383       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11384         if (Ldn->isVolatile()) {
11385           Index = nullptr;
11386           break;
11387         }
11388
11389         // Save the load node for later. Continue the scan.
11390         AliasLoadNodes.push_back(Ldn);
11391         NextInChain = Ldn->getChain().getNode();
11392         continue;
11393       } else {
11394         Index = nullptr;
11395         break;
11396       }
11397     }
11398   }
11399 }
11400
11401 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11402   if (OptLevel == CodeGenOpt::None)
11403     return false;
11404
11405   EVT MemVT = St->getMemoryVT();
11406   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11407   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11408       Attribute::NoImplicitFloat);
11409
11410   // This function cannot currently deal with non-byte-sized memory sizes.
11411   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11412     return false;
11413
11414   if (!MemVT.isSimple())
11415     return false;
11416
11417   // Perform an early exit check. Do not bother looking at stored values that
11418   // are not constants, loads, or extracted vector elements.
11419   SDValue StoredVal = St->getValue();
11420   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11421   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11422                        isa<ConstantFPSDNode>(StoredVal);
11423   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11424                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11425
11426   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11427     return false;
11428
11429   // Don't merge vectors into wider vectors if the source data comes from loads.
11430   // TODO: This restriction can be lifted by using logic similar to the
11431   // ExtractVecSrc case.
11432   if (MemVT.isVector() && IsLoadSrc)
11433     return false;
11434
11435   // Only look at ends of store sequences.
11436   SDValue Chain = SDValue(St, 0);
11437   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11438     return false;
11439
11440   // Save the LoadSDNodes that we find in the chain.
11441   // We need to make sure that these nodes do not interfere with
11442   // any of the store nodes.
11443   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11444
11445   // Save the StoreSDNodes that we find in the chain.
11446   SmallVector<MemOpLink, 8> StoreNodes;
11447
11448   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11449
11450   // Check if there is anything to merge.
11451   if (StoreNodes.size() < 2)
11452     return false;
11453
11454   // Sort the memory operands according to their distance from the
11455   // base pointer.  As a secondary criteria: make sure stores coming
11456   // later in the code come first in the list. This is important for
11457   // the non-UseAA case, because we're merging stores into the FINAL
11458   // store along a chain which potentially contains aliasing stores.
11459   // Thus, if there are multiple stores to the same address, the last
11460   // one can be considered for merging but not the others.
11461   std::sort(StoreNodes.begin(), StoreNodes.end(),
11462             [](MemOpLink LHS, MemOpLink RHS) {
11463     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11464            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11465             LHS.SequenceNum < RHS.SequenceNum);
11466   });
11467
11468   // Scan the memory operations on the chain and find the first non-consecutive
11469   // store memory address.
11470   unsigned LastConsecutiveStore = 0;
11471   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11472   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11473
11474     // Check that the addresses are consecutive starting from the second
11475     // element in the list of stores.
11476     if (i > 0) {
11477       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11478       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11479         break;
11480     }
11481
11482     // Check if this store interferes with any of the loads that we found.
11483     // If we find a load that alias with this store. Stop the sequence.
11484     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11485                     [&](LSBaseSDNode* Ldn) {
11486                       return isAlias(Ldn, StoreNodes[i].MemNode);
11487                     }))
11488       break;
11489
11490     // Mark this node as useful.
11491     LastConsecutiveStore = i;
11492   }
11493
11494   // The node with the lowest store address.
11495   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11496   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11497   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11498   LLVMContext &Context = *DAG.getContext();
11499   const DataLayout &DL = DAG.getDataLayout();
11500
11501   // Store the constants into memory as one consecutive store.
11502   if (IsConstantSrc) {
11503     unsigned LastLegalType = 0;
11504     unsigned LastLegalVectorType = 0;
11505     bool NonZero = false;
11506     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11507       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11508       SDValue StoredVal = St->getValue();
11509
11510       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11511         NonZero |= !C->isNullValue();
11512       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11513         NonZero |= !C->getConstantFPValue()->isNullValue();
11514       } else {
11515         // Non-constant.
11516         break;
11517       }
11518
11519       // Find a legal type for the constant store.
11520       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11521       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11522       bool IsFast;
11523       if (TLI.isTypeLegal(StoreTy) &&
11524           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11525                                  FirstStoreAlign, &IsFast) && IsFast) {
11526         LastLegalType = i+1;
11527       // Or check whether a truncstore is legal.
11528       } else if (TLI.getTypeAction(Context, StoreTy) ==
11529                  TargetLowering::TypePromoteInteger) {
11530         EVT LegalizedStoredValueTy =
11531           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11532         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11533             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11534                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11535             IsFast) {
11536           LastLegalType = i + 1;
11537         }
11538       }
11539
11540       // We only use vectors if the constant is known to be zero or the target
11541       // allows it and the function is not marked with the noimplicitfloat
11542       // attribute.
11543       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11544                                                         FirstStoreAS)) &&
11545           !NoVectors) {
11546         // Find a legal type for the vector store.
11547         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11548         if (TLI.isTypeLegal(Ty) &&
11549             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11550                                    FirstStoreAlign, &IsFast) && IsFast)
11551           LastLegalVectorType = i + 1;
11552       }
11553     }
11554
11555     // Check if we found a legal integer type to store.
11556     if (LastLegalType == 0 && LastLegalVectorType == 0)
11557       return false;
11558
11559     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11560     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11561
11562     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11563                                            true, UseVector);
11564   }
11565
11566   // When extracting multiple vector elements, try to store them
11567   // in one vector store rather than a sequence of scalar stores.
11568   if (IsExtractVecSrc) {
11569     unsigned NumStoresToMerge = 0;
11570     bool IsVec = MemVT.isVector();
11571     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11572       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11573       unsigned StoreValOpcode = St->getValue().getOpcode();
11574       // This restriction could be loosened.
11575       // Bail out if any stored values are not elements extracted from a vector.
11576       // It should be possible to handle mixed sources, but load sources need
11577       // more careful handling (see the block of code below that handles
11578       // consecutive loads).
11579       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11580           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11581         return false;
11582
11583       // Find a legal type for the vector store.
11584       unsigned Elts = i + 1;
11585       if (IsVec) {
11586         // When merging vector stores, get the total number of elements.
11587         Elts *= MemVT.getVectorNumElements();
11588       }
11589       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11590       bool IsFast;
11591       if (TLI.isTypeLegal(Ty) &&
11592           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11593                                  FirstStoreAlign, &IsFast) && IsFast)
11594         NumStoresToMerge = i + 1;
11595     }
11596
11597     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11598                                            false, true);
11599   }
11600
11601   // Below we handle the case of multiple consecutive stores that
11602   // come from multiple consecutive loads. We merge them into a single
11603   // wide load and a single wide store.
11604
11605   // Look for load nodes which are used by the stored values.
11606   SmallVector<MemOpLink, 8> LoadNodes;
11607
11608   // Find acceptable loads. Loads need to have the same chain (token factor),
11609   // must not be zext, volatile, indexed, and they must be consecutive.
11610   BaseIndexOffset LdBasePtr;
11611   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11612     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11613     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11614     if (!Ld) break;
11615
11616     // Loads must only have one use.
11617     if (!Ld->hasNUsesOfValue(1, 0))
11618       break;
11619
11620     // The memory operands must not be volatile.
11621     if (Ld->isVolatile() || Ld->isIndexed())
11622       break;
11623
11624     // We do not accept ext loads.
11625     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11626       break;
11627
11628     // The stored memory type must be the same.
11629     if (Ld->getMemoryVT() != MemVT)
11630       break;
11631
11632     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11633     // If this is not the first ptr that we check.
11634     if (LdBasePtr.Base.getNode()) {
11635       // The base ptr must be the same.
11636       if (!LdPtr.equalBaseIndex(LdBasePtr))
11637         break;
11638     } else {
11639       // Check that all other base pointers are the same as this one.
11640       LdBasePtr = LdPtr;
11641     }
11642
11643     // We found a potential memory operand to merge.
11644     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11645   }
11646
11647   if (LoadNodes.size() < 2)
11648     return false;
11649
11650   // If we have load/store pair instructions and we only have two values,
11651   // don't bother.
11652   unsigned RequiredAlignment;
11653   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11654       St->getAlignment() >= RequiredAlignment)
11655     return false;
11656
11657   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11658   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11659   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11660
11661   // Scan the memory operations on the chain and find the first non-consecutive
11662   // load memory address. These variables hold the index in the store node
11663   // array.
11664   unsigned LastConsecutiveLoad = 0;
11665   // This variable refers to the size and not index in the array.
11666   unsigned LastLegalVectorType = 0;
11667   unsigned LastLegalIntegerType = 0;
11668   StartAddress = LoadNodes[0].OffsetFromBase;
11669   SDValue FirstChain = FirstLoad->getChain();
11670   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11671     // All loads must share the same chain.
11672     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11673       break;
11674
11675     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11676     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11677       break;
11678     LastConsecutiveLoad = i;
11679     // Find a legal type for the vector store.
11680     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11681     bool IsFastSt, IsFastLd;
11682     if (TLI.isTypeLegal(StoreTy) &&
11683         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11684                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11685         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11686                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11687       LastLegalVectorType = i + 1;
11688     }
11689
11690     // Find a legal type for the integer store.
11691     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11692     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11693     if (TLI.isTypeLegal(StoreTy) &&
11694         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11695                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11696         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11697                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11698       LastLegalIntegerType = i + 1;
11699     // Or check whether a truncstore and extload is legal.
11700     else if (TLI.getTypeAction(Context, StoreTy) ==
11701              TargetLowering::TypePromoteInteger) {
11702       EVT LegalizedStoredValueTy =
11703         TLI.getTypeToTransformTo(Context, StoreTy);
11704       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11705           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11706           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11707           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11708           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11709                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11710           IsFastSt &&
11711           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11712                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11713           IsFastLd)
11714         LastLegalIntegerType = i+1;
11715     }
11716   }
11717
11718   // Only use vector types if the vector type is larger than the integer type.
11719   // If they are the same, use integers.
11720   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11721   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11722
11723   // We add +1 here because the LastXXX variables refer to location while
11724   // the NumElem refers to array/index size.
11725   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11726   NumElem = std::min(LastLegalType, NumElem);
11727
11728   if (NumElem < 2)
11729     return false;
11730
11731   // Collect the chains from all merged stores.
11732   SmallVector<SDValue, 8> MergeStoreChains;
11733   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11734
11735   // The latest Node in the DAG.
11736   unsigned LatestNodeUsed = 0;
11737   for (unsigned i=1; i<NumElem; ++i) {
11738     // Find a chain for the new wide-store operand. Notice that some
11739     // of the store nodes that we found may not be selected for inclusion
11740     // in the wide store. The chain we use needs to be the chain of the
11741     // latest store node which is *used* and replaced by the wide store.
11742     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11743       LatestNodeUsed = i;
11744
11745     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11746   }
11747
11748   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11749
11750   // Find if it is better to use vectors or integers to load and store
11751   // to memory.
11752   EVT JointMemOpVT;
11753   if (UseVectorTy) {
11754     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11755   } else {
11756     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11757     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11758   }
11759
11760   SDLoc LoadDL(LoadNodes[0].MemNode);
11761   SDLoc StoreDL(StoreNodes[0].MemNode);
11762
11763   // The merged loads are required to have the same incoming chain, so
11764   // using the first's chain is acceptable.
11765   SDValue NewLoad = DAG.getLoad(
11766       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11767       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11768
11769   SDValue NewStoreChain =
11770     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11771
11772   SDValue NewStore = DAG.getStore(
11773     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11774       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11775
11776   // Transfer chain users from old loads to the new load.
11777   for (unsigned i = 0; i < NumElem; ++i) {
11778     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11779     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11780                                   SDValue(NewLoad.getNode(), 1));
11781   }
11782
11783   // Replace the last store with the new store.
11784   CombineTo(LatestOp, NewStore);
11785   // Erase all other stores.
11786   for (unsigned i = 0; i < NumElem ; ++i) {
11787     // Remove all Store nodes.
11788     if (StoreNodes[i].MemNode == LatestOp)
11789       continue;
11790     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11791     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11792     deleteAndRecombine(St);
11793   }
11794
11795   return true;
11796 }
11797
11798 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11799   SDLoc SL(ST);
11800   SDValue ReplStore;
11801
11802   // Replace the chain to avoid dependency.
11803   if (ST->isTruncatingStore()) {
11804     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11805                                   ST->getBasePtr(), ST->getMemoryVT(),
11806                                   ST->getMemOperand());
11807   } else {
11808     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11809                              ST->getMemOperand());
11810   }
11811
11812   // Create token to keep both nodes around.
11813   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11814                               MVT::Other, ST->getChain(), ReplStore);
11815
11816   // Make sure the new and old chains are cleaned up.
11817   AddToWorklist(Token.getNode());
11818
11819   // Don't add users to work list.
11820   return CombineTo(ST, Token, false);
11821 }
11822
11823 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11824   SDValue Value = ST->getValue();
11825   if (Value.getOpcode() == ISD::TargetConstantFP)
11826     return SDValue();
11827
11828   SDLoc DL(ST);
11829
11830   SDValue Chain = ST->getChain();
11831   SDValue Ptr = ST->getBasePtr();
11832
11833   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11834
11835   // NOTE: If the original store is volatile, this transform must not increase
11836   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11837   // processor operation but an i64 (which is not legal) requires two.  So the
11838   // transform should not be done in this case.
11839
11840   SDValue Tmp;
11841   switch (CFP->getSimpleValueType(0).SimpleTy) {
11842   default:
11843     llvm_unreachable("Unknown FP type");
11844   case MVT::f16:    // We don't do this for these yet.
11845   case MVT::f80:
11846   case MVT::f128:
11847   case MVT::ppcf128:
11848     return SDValue();
11849   case MVT::f32:
11850     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11851         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11852       ;
11853       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11854                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11855                             MVT::i32);
11856       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11857     }
11858
11859     return SDValue();
11860   case MVT::f64:
11861     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11862          !ST->isVolatile()) ||
11863         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11864       ;
11865       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11866                             getZExtValue(), SDLoc(CFP), MVT::i64);
11867       return DAG.getStore(Chain, DL, Tmp,
11868                           Ptr, ST->getMemOperand());
11869     }
11870
11871     if (!ST->isVolatile() &&
11872         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11873       // Many FP stores are not made apparent until after legalize, e.g. for
11874       // argument passing.  Since this is so common, custom legalize the
11875       // 64-bit integer store into two 32-bit stores.
11876       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11877       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11878       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11879       if (DAG.getDataLayout().isBigEndian())
11880         std::swap(Lo, Hi);
11881
11882       unsigned Alignment = ST->getAlignment();
11883       bool isVolatile = ST->isVolatile();
11884       bool isNonTemporal = ST->isNonTemporal();
11885       AAMDNodes AAInfo = ST->getAAInfo();
11886
11887       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11888                                  Ptr, ST->getPointerInfo(),
11889                                  isVolatile, isNonTemporal,
11890                                  ST->getAlignment(), AAInfo);
11891       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11892                         DAG.getConstant(4, DL, Ptr.getValueType()));
11893       Alignment = MinAlign(Alignment, 4U);
11894       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11895                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11896                                  isVolatile, isNonTemporal,
11897                                  Alignment, AAInfo);
11898       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11899                          St0, St1);
11900     }
11901
11902     return SDValue();
11903   }
11904 }
11905
11906 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11907   StoreSDNode *ST  = cast<StoreSDNode>(N);
11908   SDValue Chain = ST->getChain();
11909   SDValue Value = ST->getValue();
11910   SDValue Ptr   = ST->getBasePtr();
11911
11912   // If this is a store of a bit convert, store the input value if the
11913   // resultant store does not need a higher alignment than the original.
11914   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11915       ST->isUnindexed()) {
11916     unsigned OrigAlign = ST->getAlignment();
11917     EVT SVT = Value.getOperand(0).getValueType();
11918     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11919         SVT.getTypeForEVT(*DAG.getContext()));
11920     if (Align <= OrigAlign &&
11921         ((!LegalOperations && !ST->isVolatile()) ||
11922          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11923       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11924                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11925                           ST->isNonTemporal(), OrigAlign,
11926                           ST->getAAInfo());
11927   }
11928
11929   // Turn 'store undef, Ptr' -> nothing.
11930   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11931     return Chain;
11932
11933   // Try to infer better alignment information than the store already has.
11934   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11935     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11936       if (Align > ST->getAlignment()) {
11937         SDValue NewStore =
11938                DAG.getTruncStore(Chain, SDLoc(N), Value,
11939                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11940                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11941                                  ST->getAAInfo());
11942         if (NewStore.getNode() != N)
11943           return CombineTo(ST, NewStore, true);
11944       }
11945     }
11946   }
11947
11948   // Try transforming a pair floating point load / store ops to integer
11949   // load / store ops.
11950   if (SDValue NewST = TransformFPLoadStorePair(N))
11951     return NewST;
11952
11953   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11954                                                   : DAG.getSubtarget().useAA();
11955 #ifndef NDEBUG
11956   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11957       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11958     UseAA = false;
11959 #endif
11960   if (UseAA && ST->isUnindexed()) {
11961     // FIXME: We should do this even without AA enabled. AA will just allow
11962     // FindBetterChain to work in more situations. The problem with this is that
11963     // any combine that expects memory operations to be on consecutive chains
11964     // first needs to be updated to look for users of the same chain.
11965
11966     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11967     // adjacent stores.
11968     if (findBetterNeighborChains(ST)) {
11969       // replaceStoreChain uses CombineTo, which handled all of the worklist
11970       // manipulation. Return the original node to not do anything else.
11971       return SDValue(ST, 0);
11972     }
11973   }
11974
11975   // Try transforming N to an indexed store.
11976   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11977     return SDValue(N, 0);
11978
11979   // FIXME: is there such a thing as a truncating indexed store?
11980   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11981       Value.getValueType().isInteger()) {
11982     // See if we can simplify the input to this truncstore with knowledge that
11983     // only the low bits are being used.  For example:
11984     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11985     SDValue Shorter =
11986       GetDemandedBits(Value,
11987                       APInt::getLowBitsSet(
11988                         Value.getValueType().getScalarType().getSizeInBits(),
11989                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11990     AddToWorklist(Value.getNode());
11991     if (Shorter.getNode())
11992       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11993                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11994
11995     // Otherwise, see if we can simplify the operation with
11996     // SimplifyDemandedBits, which only works if the value has a single use.
11997     if (SimplifyDemandedBits(Value,
11998                         APInt::getLowBitsSet(
11999                           Value.getValueType().getScalarType().getSizeInBits(),
12000                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12001       return SDValue(N, 0);
12002   }
12003
12004   // If this is a load followed by a store to the same location, then the store
12005   // is dead/noop.
12006   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12007     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12008         ST->isUnindexed() && !ST->isVolatile() &&
12009         // There can't be any side effects between the load and store, such as
12010         // a call or store.
12011         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12012       // The store is dead, remove it.
12013       return Chain;
12014     }
12015   }
12016
12017   // If this is a store followed by a store with the same value to the same
12018   // location, then the store is dead/noop.
12019   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12020     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12021         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12022         ST1->isUnindexed() && !ST1->isVolatile()) {
12023       // The store is dead, remove it.
12024       return Chain;
12025     }
12026   }
12027
12028   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12029   // truncating store.  We can do this even if this is already a truncstore.
12030   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12031       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12032       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12033                             ST->getMemoryVT())) {
12034     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12035                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12036   }
12037
12038   // Only perform this optimization before the types are legal, because we
12039   // don't want to perform this optimization on every DAGCombine invocation.
12040   if (!LegalTypes) {
12041     bool EverChanged = false;
12042
12043     do {
12044       // There can be multiple store sequences on the same chain.
12045       // Keep trying to merge store sequences until we are unable to do so
12046       // or until we merge the last store on the chain.
12047       bool Changed = MergeConsecutiveStores(ST);
12048       EverChanged |= Changed;
12049       if (!Changed) break;
12050     } while (ST->getOpcode() != ISD::DELETED_NODE);
12051
12052     if (EverChanged)
12053       return SDValue(N, 0);
12054   }
12055
12056   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12057   //
12058   // Make sure to do this only after attempting to merge stores in order to
12059   //  avoid changing the types of some subset of stores due to visit order,
12060   //  preventing their merging.
12061   if (isa<ConstantFPSDNode>(Value)) {
12062     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12063       return NewSt;
12064   }
12065
12066   return ReduceLoadOpStoreWidth(N);
12067 }
12068
12069 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12070   SDValue InVec = N->getOperand(0);
12071   SDValue InVal = N->getOperand(1);
12072   SDValue EltNo = N->getOperand(2);
12073   SDLoc dl(N);
12074
12075   // If the inserted element is an UNDEF, just use the input vector.
12076   if (InVal.getOpcode() == ISD::UNDEF)
12077     return InVec;
12078
12079   EVT VT = InVec.getValueType();
12080
12081   // If we can't generate a legal BUILD_VECTOR, exit
12082   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12083     return SDValue();
12084
12085   // Check that we know which element is being inserted
12086   if (!isa<ConstantSDNode>(EltNo))
12087     return SDValue();
12088   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12089
12090   // Canonicalize insert_vector_elt dag nodes.
12091   // Example:
12092   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12093   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12094   //
12095   // Do this only if the child insert_vector node has one use; also
12096   // do this only if indices are both constants and Idx1 < Idx0.
12097   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12098       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12099     unsigned OtherElt =
12100       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12101     if (Elt < OtherElt) {
12102       // Swap nodes.
12103       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12104                                   InVec.getOperand(0), InVal, EltNo);
12105       AddToWorklist(NewOp.getNode());
12106       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12107                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12108     }
12109   }
12110
12111   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12112   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12113   // vector elements.
12114   SmallVector<SDValue, 8> Ops;
12115   // Do not combine these two vectors if the output vector will not replace
12116   // the input vector.
12117   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12118     Ops.append(InVec.getNode()->op_begin(),
12119                InVec.getNode()->op_end());
12120   } else if (InVec.getOpcode() == ISD::UNDEF) {
12121     unsigned NElts = VT.getVectorNumElements();
12122     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12123   } else {
12124     return SDValue();
12125   }
12126
12127   // Insert the element
12128   if (Elt < Ops.size()) {
12129     // All the operands of BUILD_VECTOR must have the same type;
12130     // we enforce that here.
12131     EVT OpVT = Ops[0].getValueType();
12132     if (InVal.getValueType() != OpVT)
12133       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12134                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12135                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12136     Ops[Elt] = InVal;
12137   }
12138
12139   // Return the new vector
12140   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
12141 }
12142
12143 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12144     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12145   EVT ResultVT = EVE->getValueType(0);
12146   EVT VecEltVT = InVecVT.getVectorElementType();
12147   unsigned Align = OriginalLoad->getAlignment();
12148   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12149       VecEltVT.getTypeForEVT(*DAG.getContext()));
12150
12151   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12152     return SDValue();
12153
12154   Align = NewAlign;
12155
12156   SDValue NewPtr = OriginalLoad->getBasePtr();
12157   SDValue Offset;
12158   EVT PtrType = NewPtr.getValueType();
12159   MachinePointerInfo MPI;
12160   SDLoc DL(EVE);
12161   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12162     int Elt = ConstEltNo->getZExtValue();
12163     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12164     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12165     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12166   } else {
12167     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12168     Offset = DAG.getNode(
12169         ISD::MUL, DL, PtrType, Offset,
12170         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12171     MPI = OriginalLoad->getPointerInfo();
12172   }
12173   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12174
12175   // The replacement we need to do here is a little tricky: we need to
12176   // replace an extractelement of a load with a load.
12177   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12178   // Note that this replacement assumes that the extractvalue is the only
12179   // use of the load; that's okay because we don't want to perform this
12180   // transformation in other cases anyway.
12181   SDValue Load;
12182   SDValue Chain;
12183   if (ResultVT.bitsGT(VecEltVT)) {
12184     // If the result type of vextract is wider than the load, then issue an
12185     // extending load instead.
12186     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12187                                                   VecEltVT)
12188                                    ? ISD::ZEXTLOAD
12189                                    : ISD::EXTLOAD;
12190     Load = DAG.getExtLoad(
12191         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12192         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12193         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12194     Chain = Load.getValue(1);
12195   } else {
12196     Load = DAG.getLoad(
12197         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12198         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12199         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12200     Chain = Load.getValue(1);
12201     if (ResultVT.bitsLT(VecEltVT))
12202       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12203     else
12204       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12205   }
12206   WorklistRemover DeadNodes(*this);
12207   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12208   SDValue To[] = { Load, Chain };
12209   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12210   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12211   // worklist explicitly as well.
12212   AddToWorklist(Load.getNode());
12213   AddUsersToWorklist(Load.getNode()); // Add users too
12214   // Make sure to revisit this node to clean it up; it will usually be dead.
12215   AddToWorklist(EVE);
12216   ++OpsNarrowed;
12217   return SDValue(EVE, 0);
12218 }
12219
12220 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12221   // (vextract (scalar_to_vector val, 0) -> val
12222   SDValue InVec = N->getOperand(0);
12223   EVT VT = InVec.getValueType();
12224   EVT NVT = N->getValueType(0);
12225
12226   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12227     // Check if the result type doesn't match the inserted element type. A
12228     // SCALAR_TO_VECTOR may truncate the inserted element and the
12229     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12230     SDValue InOp = InVec.getOperand(0);
12231     if (InOp.getValueType() != NVT) {
12232       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12233       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12234     }
12235     return InOp;
12236   }
12237
12238   SDValue EltNo = N->getOperand(1);
12239   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12240
12241   // extract_vector_elt (build_vector x, y), 1 -> y
12242   if (ConstEltNo &&
12243       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12244       TLI.isTypeLegal(VT) &&
12245       (InVec.hasOneUse() ||
12246        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12247     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12248     EVT InEltVT = Elt.getValueType();
12249
12250     // Sometimes build_vector's scalar input types do not match result type.
12251     if (NVT == InEltVT)
12252       return Elt;
12253
12254     // TODO: It may be useful to truncate if free if the build_vector implicitly
12255     // converts.
12256   }
12257
12258   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12259   // We only perform this optimization before the op legalization phase because
12260   // we may introduce new vector instructions which are not backed by TD
12261   // patterns. For example on AVX, extracting elements from a wide vector
12262   // without using extract_subvector. However, if we can find an underlying
12263   // scalar value, then we can always use that.
12264   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12265     int NumElem = VT.getVectorNumElements();
12266     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12267     // Find the new index to extract from.
12268     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12269
12270     // Extracting an undef index is undef.
12271     if (OrigElt == -1)
12272       return DAG.getUNDEF(NVT);
12273
12274     // Select the right vector half to extract from.
12275     SDValue SVInVec;
12276     if (OrigElt < NumElem) {
12277       SVInVec = InVec->getOperand(0);
12278     } else {
12279       SVInVec = InVec->getOperand(1);
12280       OrigElt -= NumElem;
12281     }
12282
12283     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12284       SDValue InOp = SVInVec.getOperand(OrigElt);
12285       if (InOp.getValueType() != NVT) {
12286         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12287         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12288       }
12289
12290       return InOp;
12291     }
12292
12293     // FIXME: We should handle recursing on other vector shuffles and
12294     // scalar_to_vector here as well.
12295
12296     if (!LegalOperations) {
12297       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12298       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12299                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12300     }
12301   }
12302
12303   bool BCNumEltsChanged = false;
12304   EVT ExtVT = VT.getVectorElementType();
12305   EVT LVT = ExtVT;
12306
12307   // If the result of load has to be truncated, then it's not necessarily
12308   // profitable.
12309   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12310     return SDValue();
12311
12312   if (InVec.getOpcode() == ISD::BITCAST) {
12313     // Don't duplicate a load with other uses.
12314     if (!InVec.hasOneUse())
12315       return SDValue();
12316
12317     EVT BCVT = InVec.getOperand(0).getValueType();
12318     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12319       return SDValue();
12320     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12321       BCNumEltsChanged = true;
12322     InVec = InVec.getOperand(0);
12323     ExtVT = BCVT.getVectorElementType();
12324   }
12325
12326   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12327   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12328       ISD::isNormalLoad(InVec.getNode()) &&
12329       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12330     SDValue Index = N->getOperand(1);
12331     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12332       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12333                                                            OrigLoad);
12334   }
12335
12336   // Perform only after legalization to ensure build_vector / vector_shuffle
12337   // optimizations have already been done.
12338   if (!LegalOperations) return SDValue();
12339
12340   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12341   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12342   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12343
12344   if (ConstEltNo) {
12345     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12346
12347     LoadSDNode *LN0 = nullptr;
12348     const ShuffleVectorSDNode *SVN = nullptr;
12349     if (ISD::isNormalLoad(InVec.getNode())) {
12350       LN0 = cast<LoadSDNode>(InVec);
12351     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12352                InVec.getOperand(0).getValueType() == ExtVT &&
12353                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12354       // Don't duplicate a load with other uses.
12355       if (!InVec.hasOneUse())
12356         return SDValue();
12357
12358       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12359     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12360       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12361       // =>
12362       // (load $addr+1*size)
12363
12364       // Don't duplicate a load with other uses.
12365       if (!InVec.hasOneUse())
12366         return SDValue();
12367
12368       // If the bit convert changed the number of elements, it is unsafe
12369       // to examine the mask.
12370       if (BCNumEltsChanged)
12371         return SDValue();
12372
12373       // Select the input vector, guarding against out of range extract vector.
12374       unsigned NumElems = VT.getVectorNumElements();
12375       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12376       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12377
12378       if (InVec.getOpcode() == ISD::BITCAST) {
12379         // Don't duplicate a load with other uses.
12380         if (!InVec.hasOneUse())
12381           return SDValue();
12382
12383         InVec = InVec.getOperand(0);
12384       }
12385       if (ISD::isNormalLoad(InVec.getNode())) {
12386         LN0 = cast<LoadSDNode>(InVec);
12387         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12388         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12389       }
12390     }
12391
12392     // Make sure we found a non-volatile load and the extractelement is
12393     // the only use.
12394     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12395       return SDValue();
12396
12397     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12398     if (Elt == -1)
12399       return DAG.getUNDEF(LVT);
12400
12401     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12402   }
12403
12404   return SDValue();
12405 }
12406
12407 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12408 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12409   // We perform this optimization post type-legalization because
12410   // the type-legalizer often scalarizes integer-promoted vectors.
12411   // Performing this optimization before may create bit-casts which
12412   // will be type-legalized to complex code sequences.
12413   // We perform this optimization only before the operation legalizer because we
12414   // may introduce illegal operations.
12415   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12416     return SDValue();
12417
12418   unsigned NumInScalars = N->getNumOperands();
12419   SDLoc dl(N);
12420   EVT VT = N->getValueType(0);
12421
12422   // Check to see if this is a BUILD_VECTOR of a bunch of values
12423   // which come from any_extend or zero_extend nodes. If so, we can create
12424   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12425   // optimizations. We do not handle sign-extend because we can't fill the sign
12426   // using shuffles.
12427   EVT SourceType = MVT::Other;
12428   bool AllAnyExt = true;
12429
12430   for (unsigned i = 0; i != NumInScalars; ++i) {
12431     SDValue In = N->getOperand(i);
12432     // Ignore undef inputs.
12433     if (In.getOpcode() == ISD::UNDEF) continue;
12434
12435     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12436     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12437
12438     // Abort if the element is not an extension.
12439     if (!ZeroExt && !AnyExt) {
12440       SourceType = MVT::Other;
12441       break;
12442     }
12443
12444     // The input is a ZeroExt or AnyExt. Check the original type.
12445     EVT InTy = In.getOperand(0).getValueType();
12446
12447     // Check that all of the widened source types are the same.
12448     if (SourceType == MVT::Other)
12449       // First time.
12450       SourceType = InTy;
12451     else if (InTy != SourceType) {
12452       // Multiple income types. Abort.
12453       SourceType = MVT::Other;
12454       break;
12455     }
12456
12457     // Check if all of the extends are ANY_EXTENDs.
12458     AllAnyExt &= AnyExt;
12459   }
12460
12461   // In order to have valid types, all of the inputs must be extended from the
12462   // same source type and all of the inputs must be any or zero extend.
12463   // Scalar sizes must be a power of two.
12464   EVT OutScalarTy = VT.getScalarType();
12465   bool ValidTypes = SourceType != MVT::Other &&
12466                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12467                  isPowerOf2_32(SourceType.getSizeInBits());
12468
12469   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12470   // turn into a single shuffle instruction.
12471   if (!ValidTypes)
12472     return SDValue();
12473
12474   bool isLE = DAG.getDataLayout().isLittleEndian();
12475   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12476   assert(ElemRatio > 1 && "Invalid element size ratio");
12477   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12478                                DAG.getConstant(0, SDLoc(N), SourceType);
12479
12480   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12481   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12482
12483   // Populate the new build_vector
12484   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12485     SDValue Cast = N->getOperand(i);
12486     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12487             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12488             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12489     SDValue In;
12490     if (Cast.getOpcode() == ISD::UNDEF)
12491       In = DAG.getUNDEF(SourceType);
12492     else
12493       In = Cast->getOperand(0);
12494     unsigned Index = isLE ? (i * ElemRatio) :
12495                             (i * ElemRatio + (ElemRatio - 1));
12496
12497     assert(Index < Ops.size() && "Invalid index");
12498     Ops[Index] = In;
12499   }
12500
12501   // The type of the new BUILD_VECTOR node.
12502   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12503   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12504          "Invalid vector size");
12505   // Check if the new vector type is legal.
12506   if (!isTypeLegal(VecVT)) return SDValue();
12507
12508   // Make the new BUILD_VECTOR.
12509   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12510
12511   // The new BUILD_VECTOR node has the potential to be further optimized.
12512   AddToWorklist(BV.getNode());
12513   // Bitcast to the desired type.
12514   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12515 }
12516
12517 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12518   EVT VT = N->getValueType(0);
12519
12520   unsigned NumInScalars = N->getNumOperands();
12521   SDLoc dl(N);
12522
12523   EVT SrcVT = MVT::Other;
12524   unsigned Opcode = ISD::DELETED_NODE;
12525   unsigned NumDefs = 0;
12526
12527   for (unsigned i = 0; i != NumInScalars; ++i) {
12528     SDValue In = N->getOperand(i);
12529     unsigned Opc = In.getOpcode();
12530
12531     if (Opc == ISD::UNDEF)
12532       continue;
12533
12534     // If all scalar values are floats and converted from integers.
12535     if (Opcode == ISD::DELETED_NODE &&
12536         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12537       Opcode = Opc;
12538     }
12539
12540     if (Opc != Opcode)
12541       return SDValue();
12542
12543     EVT InVT = In.getOperand(0).getValueType();
12544
12545     // If all scalar values are typed differently, bail out. It's chosen to
12546     // simplify BUILD_VECTOR of integer types.
12547     if (SrcVT == MVT::Other)
12548       SrcVT = InVT;
12549     if (SrcVT != InVT)
12550       return SDValue();
12551     NumDefs++;
12552   }
12553
12554   // If the vector has just one element defined, it's not worth to fold it into
12555   // a vectorized one.
12556   if (NumDefs < 2)
12557     return SDValue();
12558
12559   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12560          && "Should only handle conversion from integer to float.");
12561   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12562
12563   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12564
12565   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12566     return SDValue();
12567
12568   // Just because the floating-point vector type is legal does not necessarily
12569   // mean that the corresponding integer vector type is.
12570   if (!isTypeLegal(NVT))
12571     return SDValue();
12572
12573   SmallVector<SDValue, 8> Opnds;
12574   for (unsigned i = 0; i != NumInScalars; ++i) {
12575     SDValue In = N->getOperand(i);
12576
12577     if (In.getOpcode() == ISD::UNDEF)
12578       Opnds.push_back(DAG.getUNDEF(SrcVT));
12579     else
12580       Opnds.push_back(In.getOperand(0));
12581   }
12582   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12583   AddToWorklist(BV.getNode());
12584
12585   return DAG.getNode(Opcode, dl, VT, BV);
12586 }
12587
12588 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12589   unsigned NumInScalars = N->getNumOperands();
12590   SDLoc dl(N);
12591   EVT VT = N->getValueType(0);
12592
12593   // A vector built entirely of undefs is undef.
12594   if (ISD::allOperandsUndef(N))
12595     return DAG.getUNDEF(VT);
12596
12597   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12598     return V;
12599
12600   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12601     return V;
12602
12603   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12604   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12605   // at most two distinct vectors, turn this into a shuffle node.
12606
12607   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12608   if (!isTypeLegal(VT))
12609     return SDValue();
12610
12611   // May only combine to shuffle after legalize if shuffle is legal.
12612   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12613     return SDValue();
12614
12615   SDValue VecIn1, VecIn2;
12616   bool UsesZeroVector = false;
12617   for (unsigned i = 0; i != NumInScalars; ++i) {
12618     SDValue Op = N->getOperand(i);
12619     // Ignore undef inputs.
12620     if (Op.getOpcode() == ISD::UNDEF) continue;
12621
12622     // See if we can combine this build_vector into a blend with a zero vector.
12623     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12624       UsesZeroVector = true;
12625       continue;
12626     }
12627
12628     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12629     // constant index, bail out.
12630     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12631         !isa<ConstantSDNode>(Op.getOperand(1))) {
12632       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12633       break;
12634     }
12635
12636     // We allow up to two distinct input vectors.
12637     SDValue ExtractedFromVec = Op.getOperand(0);
12638     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12639       continue;
12640
12641     if (!VecIn1.getNode()) {
12642       VecIn1 = ExtractedFromVec;
12643     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12644       VecIn2 = ExtractedFromVec;
12645     } else {
12646       // Too many inputs.
12647       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12648       break;
12649     }
12650   }
12651
12652   // If everything is good, we can make a shuffle operation.
12653   if (VecIn1.getNode()) {
12654     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12655     SmallVector<int, 8> Mask;
12656     for (unsigned i = 0; i != NumInScalars; ++i) {
12657       unsigned Opcode = N->getOperand(i).getOpcode();
12658       if (Opcode == ISD::UNDEF) {
12659         Mask.push_back(-1);
12660         continue;
12661       }
12662
12663       // Operands can also be zero.
12664       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12665         assert(UsesZeroVector &&
12666                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12667                "Unexpected node found!");
12668         Mask.push_back(NumInScalars+i);
12669         continue;
12670       }
12671
12672       // If extracting from the first vector, just use the index directly.
12673       SDValue Extract = N->getOperand(i);
12674       SDValue ExtVal = Extract.getOperand(1);
12675       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12676       if (Extract.getOperand(0) == VecIn1) {
12677         Mask.push_back(ExtIndex);
12678         continue;
12679       }
12680
12681       // Otherwise, use InIdx + InputVecSize
12682       Mask.push_back(InNumElements + ExtIndex);
12683     }
12684
12685     // Avoid introducing illegal shuffles with zero.
12686     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12687       return SDValue();
12688
12689     // We can't generate a shuffle node with mismatched input and output types.
12690     // Attempt to transform a single input vector to the correct type.
12691     if ((VT != VecIn1.getValueType())) {
12692       // If the input vector type has a different base type to the output
12693       // vector type, bail out.
12694       EVT VTElemType = VT.getVectorElementType();
12695       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12696           (VecIn2.getNode() &&
12697            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12698         return SDValue();
12699
12700       // If the input vector is too small, widen it.
12701       // We only support widening of vectors which are half the size of the
12702       // output registers. For example XMM->YMM widening on X86 with AVX.
12703       EVT VecInT = VecIn1.getValueType();
12704       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12705         // If we only have one small input, widen it by adding undef values.
12706         if (!VecIn2.getNode())
12707           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12708                                DAG.getUNDEF(VecIn1.getValueType()));
12709         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12710           // If we have two small inputs of the same type, try to concat them.
12711           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12712           VecIn2 = SDValue(nullptr, 0);
12713         } else
12714           return SDValue();
12715       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12716         // If the input vector is too large, try to split it.
12717         // We don't support having two input vectors that are too large.
12718         // If the zero vector was used, we can not split the vector,
12719         // since we'd need 3 inputs.
12720         if (UsesZeroVector || VecIn2.getNode())
12721           return SDValue();
12722
12723         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12724           return SDValue();
12725
12726         // Try to replace VecIn1 with two extract_subvectors
12727         // No need to update the masks, they should still be correct.
12728         VecIn2 = DAG.getNode(
12729             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12730             DAG.getConstant(VT.getVectorNumElements(), dl,
12731                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12732         VecIn1 = DAG.getNode(
12733             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12734             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12735       } else
12736         return SDValue();
12737     }
12738
12739     if (UsesZeroVector)
12740       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12741                                 DAG.getConstantFP(0.0, dl, VT);
12742     else
12743       // If VecIn2 is unused then change it to undef.
12744       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12745
12746     // Check that we were able to transform all incoming values to the same
12747     // type.
12748     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12749         VecIn1.getValueType() != VT)
12750           return SDValue();
12751
12752     // Return the new VECTOR_SHUFFLE node.
12753     SDValue Ops[2];
12754     Ops[0] = VecIn1;
12755     Ops[1] = VecIn2;
12756     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12757   }
12758
12759   return SDValue();
12760 }
12761
12762 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12764   EVT OpVT = N->getOperand(0).getValueType();
12765
12766   // If the operands are legal vectors, leave them alone.
12767   if (TLI.isTypeLegal(OpVT))
12768     return SDValue();
12769
12770   SDLoc DL(N);
12771   EVT VT = N->getValueType(0);
12772   SmallVector<SDValue, 8> Ops;
12773
12774   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12775   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12776
12777   // Keep track of what we encounter.
12778   bool AnyInteger = false;
12779   bool AnyFP = false;
12780   for (const SDValue &Op : N->ops()) {
12781     if (ISD::BITCAST == Op.getOpcode() &&
12782         !Op.getOperand(0).getValueType().isVector())
12783       Ops.push_back(Op.getOperand(0));
12784     else if (ISD::UNDEF == Op.getOpcode())
12785       Ops.push_back(ScalarUndef);
12786     else
12787       return SDValue();
12788
12789     // Note whether we encounter an integer or floating point scalar.
12790     // If it's neither, bail out, it could be something weird like x86mmx.
12791     EVT LastOpVT = Ops.back().getValueType();
12792     if (LastOpVT.isFloatingPoint())
12793       AnyFP = true;
12794     else if (LastOpVT.isInteger())
12795       AnyInteger = true;
12796     else
12797       return SDValue();
12798   }
12799
12800   // If any of the operands is a floating point scalar bitcast to a vector,
12801   // use floating point types throughout, and bitcast everything.
12802   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12803   if (AnyFP) {
12804     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12805     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12806     if (AnyInteger) {
12807       for (SDValue &Op : Ops) {
12808         if (Op.getValueType() == SVT)
12809           continue;
12810         if (Op.getOpcode() == ISD::UNDEF)
12811           Op = ScalarUndef;
12812         else
12813           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12814       }
12815     }
12816   }
12817
12818   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12819                                VT.getSizeInBits() / SVT.getSizeInBits());
12820   return DAG.getNode(ISD::BITCAST, DL, VT,
12821                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12822 }
12823
12824 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12825 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12826 // most two distinct vectors the same size as the result, attempt to turn this
12827 // into a legal shuffle.
12828 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12829   EVT VT = N->getValueType(0);
12830   EVT OpVT = N->getOperand(0).getValueType();
12831   int NumElts = VT.getVectorNumElements();
12832   int NumOpElts = OpVT.getVectorNumElements();
12833
12834   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12835   SmallVector<int, 8> Mask;
12836
12837   for (SDValue Op : N->ops()) {
12838     // Peek through any bitcast.
12839     while (Op.getOpcode() == ISD::BITCAST)
12840       Op = Op.getOperand(0);
12841
12842     // UNDEF nodes convert to UNDEF shuffle mask values.
12843     if (Op.getOpcode() == ISD::UNDEF) {
12844       Mask.append((unsigned)NumOpElts, -1);
12845       continue;
12846     }
12847
12848     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12849       return SDValue();
12850
12851     // What vector are we extracting the subvector from and at what index?
12852     SDValue ExtVec = Op.getOperand(0);
12853
12854     // We want the EVT of the original extraction to correctly scale the
12855     // extraction index.
12856     EVT ExtVT = ExtVec.getValueType();
12857
12858     // Peek through any bitcast.
12859     while (ExtVec.getOpcode() == ISD::BITCAST)
12860       ExtVec = ExtVec.getOperand(0);
12861
12862     // UNDEF nodes convert to UNDEF shuffle mask values.
12863     if (ExtVec.getOpcode() == ISD::UNDEF) {
12864       Mask.append((unsigned)NumOpElts, -1);
12865       continue;
12866     }
12867
12868     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12869       return SDValue();
12870     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12871
12872     // Ensure that we are extracting a subvector from a vector the same
12873     // size as the result.
12874     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12875       return SDValue();
12876
12877     // Scale the subvector index to account for any bitcast.
12878     int NumExtElts = ExtVT.getVectorNumElements();
12879     if (0 == (NumExtElts % NumElts))
12880       ExtIdx /= (NumExtElts / NumElts);
12881     else if (0 == (NumElts % NumExtElts))
12882       ExtIdx *= (NumElts / NumExtElts);
12883     else
12884       return SDValue();
12885
12886     // At most we can reference 2 inputs in the final shuffle.
12887     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12888       SV0 = ExtVec;
12889       for (int i = 0; i != NumOpElts; ++i)
12890         Mask.push_back(i + ExtIdx);
12891     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12892       SV1 = ExtVec;
12893       for (int i = 0; i != NumOpElts; ++i)
12894         Mask.push_back(i + ExtIdx + NumElts);
12895     } else {
12896       return SDValue();
12897     }
12898   }
12899
12900   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12901     return SDValue();
12902
12903   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12904                               DAG.getBitcast(VT, SV1), Mask);
12905 }
12906
12907 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12908   // If we only have one input vector, we don't need to do any concatenation.
12909   if (N->getNumOperands() == 1)
12910     return N->getOperand(0);
12911
12912   // Check if all of the operands are undefs.
12913   EVT VT = N->getValueType(0);
12914   if (ISD::allOperandsUndef(N))
12915     return DAG.getUNDEF(VT);
12916
12917   // Optimize concat_vectors where all but the first of the vectors are undef.
12918   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12919         return Op.getOpcode() == ISD::UNDEF;
12920       })) {
12921     SDValue In = N->getOperand(0);
12922     assert(In.getValueType().isVector() && "Must concat vectors");
12923
12924     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12925     if (In->getOpcode() == ISD::BITCAST &&
12926         !In->getOperand(0)->getValueType(0).isVector()) {
12927       SDValue Scalar = In->getOperand(0);
12928
12929       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12930       // look through the trunc so we can still do the transform:
12931       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12932       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12933           !TLI.isTypeLegal(Scalar.getValueType()) &&
12934           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12935         Scalar = Scalar->getOperand(0);
12936
12937       EVT SclTy = Scalar->getValueType(0);
12938
12939       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12940         return SDValue();
12941
12942       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12943                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12944       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12945         return SDValue();
12946
12947       SDLoc dl = SDLoc(N);
12948       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12949       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12950     }
12951   }
12952
12953   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12954   // We have already tested above for an UNDEF only concatenation.
12955   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12956   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12957   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12958     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12959   };
12960   bool AllBuildVectorsOrUndefs =
12961       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12962   if (AllBuildVectorsOrUndefs) {
12963     SmallVector<SDValue, 8> Opnds;
12964     EVT SVT = VT.getScalarType();
12965
12966     EVT MinVT = SVT;
12967     if (!SVT.isFloatingPoint()) {
12968       // If BUILD_VECTOR are from built from integer, they may have different
12969       // operand types. Get the smallest type and truncate all operands to it.
12970       bool FoundMinVT = false;
12971       for (const SDValue &Op : N->ops())
12972         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12973           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12974           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12975           FoundMinVT = true;
12976         }
12977       assert(FoundMinVT && "Concat vector type mismatch");
12978     }
12979
12980     for (const SDValue &Op : N->ops()) {
12981       EVT OpVT = Op.getValueType();
12982       unsigned NumElts = OpVT.getVectorNumElements();
12983
12984       if (ISD::UNDEF == Op.getOpcode())
12985         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12986
12987       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12988         if (SVT.isFloatingPoint()) {
12989           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12990           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12991         } else {
12992           for (unsigned i = 0; i != NumElts; ++i)
12993             Opnds.push_back(
12994                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12995         }
12996       }
12997     }
12998
12999     assert(VT.getVectorNumElements() == Opnds.size() &&
13000            "Concat vector type mismatch");
13001     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
13002   }
13003
13004   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13005   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13006     return V;
13007
13008   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13009   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13010     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13011       return V;
13012
13013   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13014   // nodes often generate nop CONCAT_VECTOR nodes.
13015   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13016   // place the incoming vectors at the exact same location.
13017   SDValue SingleSource = SDValue();
13018   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13019
13020   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13021     SDValue Op = N->getOperand(i);
13022
13023     if (Op.getOpcode() == ISD::UNDEF)
13024       continue;
13025
13026     // Check if this is the identity extract:
13027     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13028       return SDValue();
13029
13030     // Find the single incoming vector for the extract_subvector.
13031     if (SingleSource.getNode()) {
13032       if (Op.getOperand(0) != SingleSource)
13033         return SDValue();
13034     } else {
13035       SingleSource = Op.getOperand(0);
13036
13037       // Check the source type is the same as the type of the result.
13038       // If not, this concat may extend the vector, so we can not
13039       // optimize it away.
13040       if (SingleSource.getValueType() != N->getValueType(0))
13041         return SDValue();
13042     }
13043
13044     unsigned IdentityIndex = i * PartNumElem;
13045     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13046     // The extract index must be constant.
13047     if (!CS)
13048       return SDValue();
13049
13050     // Check that we are reading from the identity index.
13051     if (CS->getZExtValue() != IdentityIndex)
13052       return SDValue();
13053   }
13054
13055   if (SingleSource.getNode())
13056     return SingleSource;
13057
13058   return SDValue();
13059 }
13060
13061 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13062   EVT NVT = N->getValueType(0);
13063   SDValue V = N->getOperand(0);
13064
13065   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13066     // Combine:
13067     //    (extract_subvec (concat V1, V2, ...), i)
13068     // Into:
13069     //    Vi if possible
13070     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13071     // type.
13072     if (V->getOperand(0).getValueType() != NVT)
13073       return SDValue();
13074     unsigned Idx = N->getConstantOperandVal(1);
13075     unsigned NumElems = NVT.getVectorNumElements();
13076     assert((Idx % NumElems) == 0 &&
13077            "IDX in concat is not a multiple of the result vector length.");
13078     return V->getOperand(Idx / NumElems);
13079   }
13080
13081   // Skip bitcasting
13082   if (V->getOpcode() == ISD::BITCAST)
13083     V = V.getOperand(0);
13084
13085   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13086     SDLoc dl(N);
13087     // Handle only simple case where vector being inserted and vector
13088     // being extracted are of same type, and are half size of larger vectors.
13089     EVT BigVT = V->getOperand(0).getValueType();
13090     EVT SmallVT = V->getOperand(1).getValueType();
13091     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13092       return SDValue();
13093
13094     // Only handle cases where both indexes are constants with the same type.
13095     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13096     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13097
13098     if (InsIdx && ExtIdx &&
13099         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13100         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13101       // Combine:
13102       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13103       // Into:
13104       //    indices are equal or bit offsets are equal => V1
13105       //    otherwise => (extract_subvec V1, ExtIdx)
13106       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13107           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13108         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13109       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13110                          DAG.getNode(ISD::BITCAST, dl,
13111                                      N->getOperand(0).getValueType(),
13112                                      V->getOperand(0)), N->getOperand(1));
13113     }
13114   }
13115
13116   return SDValue();
13117 }
13118
13119 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13120                                                  SDValue V, SelectionDAG &DAG) {
13121   SDLoc DL(V);
13122   EVT VT = V.getValueType();
13123
13124   switch (V.getOpcode()) {
13125   default:
13126     return V;
13127
13128   case ISD::CONCAT_VECTORS: {
13129     EVT OpVT = V->getOperand(0).getValueType();
13130     int OpSize = OpVT.getVectorNumElements();
13131     SmallBitVector OpUsedElements(OpSize, false);
13132     bool FoundSimplification = false;
13133     SmallVector<SDValue, 4> NewOps;
13134     NewOps.reserve(V->getNumOperands());
13135     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13136       SDValue Op = V->getOperand(i);
13137       bool OpUsed = false;
13138       for (int j = 0; j < OpSize; ++j)
13139         if (UsedElements[i * OpSize + j]) {
13140           OpUsedElements[j] = true;
13141           OpUsed = true;
13142         }
13143       NewOps.push_back(
13144           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13145                  : DAG.getUNDEF(OpVT));
13146       FoundSimplification |= Op == NewOps.back();
13147       OpUsedElements.reset();
13148     }
13149     if (FoundSimplification)
13150       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13151     return V;
13152   }
13153
13154   case ISD::INSERT_SUBVECTOR: {
13155     SDValue BaseV = V->getOperand(0);
13156     SDValue SubV = V->getOperand(1);
13157     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13158     if (!IdxN)
13159       return V;
13160
13161     int SubSize = SubV.getValueType().getVectorNumElements();
13162     int Idx = IdxN->getZExtValue();
13163     bool SubVectorUsed = false;
13164     SmallBitVector SubUsedElements(SubSize, false);
13165     for (int i = 0; i < SubSize; ++i)
13166       if (UsedElements[i + Idx]) {
13167         SubVectorUsed = true;
13168         SubUsedElements[i] = true;
13169         UsedElements[i + Idx] = false;
13170       }
13171
13172     // Now recurse on both the base and sub vectors.
13173     SDValue SimplifiedSubV =
13174         SubVectorUsed
13175             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13176             : DAG.getUNDEF(SubV.getValueType());
13177     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13178     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13179       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13180                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13181     return V;
13182   }
13183   }
13184 }
13185
13186 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13187                                        SDValue N1, SelectionDAG &DAG) {
13188   EVT VT = SVN->getValueType(0);
13189   int NumElts = VT.getVectorNumElements();
13190   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13191   for (int M : SVN->getMask())
13192     if (M >= 0 && M < NumElts)
13193       N0UsedElements[M] = true;
13194     else if (M >= NumElts)
13195       N1UsedElements[M - NumElts] = true;
13196
13197   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13198   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13199   if (S0 == N0 && S1 == N1)
13200     return SDValue();
13201
13202   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13203 }
13204
13205 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13206 // or turn a shuffle of a single concat into simpler shuffle then concat.
13207 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13208   EVT VT = N->getValueType(0);
13209   unsigned NumElts = VT.getVectorNumElements();
13210
13211   SDValue N0 = N->getOperand(0);
13212   SDValue N1 = N->getOperand(1);
13213   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13214
13215   SmallVector<SDValue, 4> Ops;
13216   EVT ConcatVT = N0.getOperand(0).getValueType();
13217   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13218   unsigned NumConcats = NumElts / NumElemsPerConcat;
13219
13220   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13221   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13222   // half vector elements.
13223   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13224       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13225                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13226     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13227                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13228     N1 = DAG.getUNDEF(ConcatVT);
13229     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13230   }
13231
13232   // Look at every vector that's inserted. We're looking for exact
13233   // subvector-sized copies from a concatenated vector
13234   for (unsigned I = 0; I != NumConcats; ++I) {
13235     // Make sure we're dealing with a copy.
13236     unsigned Begin = I * NumElemsPerConcat;
13237     bool AllUndef = true, NoUndef = true;
13238     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13239       if (SVN->getMaskElt(J) >= 0)
13240         AllUndef = false;
13241       else
13242         NoUndef = false;
13243     }
13244
13245     if (NoUndef) {
13246       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13247         return SDValue();
13248
13249       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13250         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13251           return SDValue();
13252
13253       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13254       if (FirstElt < N0.getNumOperands())
13255         Ops.push_back(N0.getOperand(FirstElt));
13256       else
13257         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13258
13259     } else if (AllUndef) {
13260       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13261     } else { // Mixed with general masks and undefs, can't do optimization.
13262       return SDValue();
13263     }
13264   }
13265
13266   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13267 }
13268
13269 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13270   EVT VT = N->getValueType(0);
13271   unsigned NumElts = VT.getVectorNumElements();
13272
13273   SDValue N0 = N->getOperand(0);
13274   SDValue N1 = N->getOperand(1);
13275
13276   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13277
13278   // Canonicalize shuffle undef, undef -> undef
13279   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13280     return DAG.getUNDEF(VT);
13281
13282   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13283
13284   // Canonicalize shuffle v, v -> v, undef
13285   if (N0 == N1) {
13286     SmallVector<int, 8> NewMask;
13287     for (unsigned i = 0; i != NumElts; ++i) {
13288       int Idx = SVN->getMaskElt(i);
13289       if (Idx >= (int)NumElts) Idx -= NumElts;
13290       NewMask.push_back(Idx);
13291     }
13292     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13293                                 &NewMask[0]);
13294   }
13295
13296   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13297   if (N0.getOpcode() == ISD::UNDEF) {
13298     SmallVector<int, 8> NewMask;
13299     for (unsigned i = 0; i != NumElts; ++i) {
13300       int Idx = SVN->getMaskElt(i);
13301       if (Idx >= 0) {
13302         if (Idx >= (int)NumElts)
13303           Idx -= NumElts;
13304         else
13305           Idx = -1; // remove reference to lhs
13306       }
13307       NewMask.push_back(Idx);
13308     }
13309     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13310                                 &NewMask[0]);
13311   }
13312
13313   // Remove references to rhs if it is undef
13314   if (N1.getOpcode() == ISD::UNDEF) {
13315     bool Changed = false;
13316     SmallVector<int, 8> NewMask;
13317     for (unsigned i = 0; i != NumElts; ++i) {
13318       int Idx = SVN->getMaskElt(i);
13319       if (Idx >= (int)NumElts) {
13320         Idx = -1;
13321         Changed = true;
13322       }
13323       NewMask.push_back(Idx);
13324     }
13325     if (Changed)
13326       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13327   }
13328
13329   // If it is a splat, check if the argument vector is another splat or a
13330   // build_vector.
13331   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13332     SDNode *V = N0.getNode();
13333
13334     // If this is a bit convert that changes the element type of the vector but
13335     // not the number of vector elements, look through it.  Be careful not to
13336     // look though conversions that change things like v4f32 to v2f64.
13337     if (V->getOpcode() == ISD::BITCAST) {
13338       SDValue ConvInput = V->getOperand(0);
13339       if (ConvInput.getValueType().isVector() &&
13340           ConvInput.getValueType().getVectorNumElements() == NumElts)
13341         V = ConvInput.getNode();
13342     }
13343
13344     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13345       assert(V->getNumOperands() == NumElts &&
13346              "BUILD_VECTOR has wrong number of operands");
13347       SDValue Base;
13348       bool AllSame = true;
13349       for (unsigned i = 0; i != NumElts; ++i) {
13350         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13351           Base = V->getOperand(i);
13352           break;
13353         }
13354       }
13355       // Splat of <u, u, u, u>, return <u, u, u, u>
13356       if (!Base.getNode())
13357         return N0;
13358       for (unsigned i = 0; i != NumElts; ++i) {
13359         if (V->getOperand(i) != Base) {
13360           AllSame = false;
13361           break;
13362         }
13363       }
13364       // Splat of <x, x, x, x>, return <x, x, x, x>
13365       if (AllSame)
13366         return N0;
13367
13368       // Canonicalize any other splat as a build_vector.
13369       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13370       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13371       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13372                                   V->getValueType(0), Ops);
13373
13374       // We may have jumped through bitcasts, so the type of the
13375       // BUILD_VECTOR may not match the type of the shuffle.
13376       if (V->getValueType(0) != VT)
13377         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13378       return NewBV;
13379     }
13380   }
13381
13382   // There are various patterns used to build up a vector from smaller vectors,
13383   // subvectors, or elements. Scan chains of these and replace unused insertions
13384   // or components with undef.
13385   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13386     return S;
13387
13388   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13389       Level < AfterLegalizeVectorOps &&
13390       (N1.getOpcode() == ISD::UNDEF ||
13391       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13392        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13393     SDValue V = partitionShuffleOfConcats(N, DAG);
13394
13395     if (V.getNode())
13396       return V;
13397   }
13398
13399   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13400   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13401   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13402     SmallVector<SDValue, 8> Ops;
13403     for (int M : SVN->getMask()) {
13404       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13405       if (M >= 0) {
13406         int Idx = M % NumElts;
13407         SDValue &S = (M < (int)NumElts ? N0 : N1);
13408         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13409           Op = S.getOperand(Idx);
13410         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13411           if (Idx == 0)
13412             Op = S.getOperand(0);
13413         } else {
13414           // Operand can't be combined - bail out.
13415           break;
13416         }
13417       }
13418       Ops.push_back(Op);
13419     }
13420     if (Ops.size() == VT.getVectorNumElements()) {
13421       // BUILD_VECTOR requires all inputs to be of the same type, find the
13422       // maximum type and extend them all.
13423       EVT SVT = VT.getScalarType();
13424       if (SVT.isInteger())
13425         for (SDValue &Op : Ops)
13426           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13427       if (SVT != VT.getScalarType())
13428         for (SDValue &Op : Ops)
13429           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13430                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13431                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13432       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13433     }
13434   }
13435
13436   // If this shuffle only has a single input that is a bitcasted shuffle,
13437   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13438   // back to their original types.
13439   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13440       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13441       TLI.isTypeLegal(VT)) {
13442
13443     // Peek through the bitcast only if there is one user.
13444     SDValue BC0 = N0;
13445     while (BC0.getOpcode() == ISD::BITCAST) {
13446       if (!BC0.hasOneUse())
13447         break;
13448       BC0 = BC0.getOperand(0);
13449     }
13450
13451     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13452       if (Scale == 1)
13453         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13454
13455       SmallVector<int, 8> NewMask;
13456       for (int M : Mask)
13457         for (int s = 0; s != Scale; ++s)
13458           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13459       return NewMask;
13460     };
13461
13462     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13463       EVT SVT = VT.getScalarType();
13464       EVT InnerVT = BC0->getValueType(0);
13465       EVT InnerSVT = InnerVT.getScalarType();
13466
13467       // Determine which shuffle works with the smaller scalar type.
13468       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13469       EVT ScaleSVT = ScaleVT.getScalarType();
13470
13471       if (TLI.isTypeLegal(ScaleVT) &&
13472           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13473           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13474
13475         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13476         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13477
13478         // Scale the shuffle masks to the smaller scalar type.
13479         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13480         SmallVector<int, 8> InnerMask =
13481             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13482         SmallVector<int, 8> OuterMask =
13483             ScaleShuffleMask(SVN->getMask(), OuterScale);
13484
13485         // Merge the shuffle masks.
13486         SmallVector<int, 8> NewMask;
13487         for (int M : OuterMask)
13488           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13489
13490         // Test for shuffle mask legality over both commutations.
13491         SDValue SV0 = BC0->getOperand(0);
13492         SDValue SV1 = BC0->getOperand(1);
13493         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13494         if (!LegalMask) {
13495           std::swap(SV0, SV1);
13496           ShuffleVectorSDNode::commuteMask(NewMask);
13497           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13498         }
13499
13500         if (LegalMask) {
13501           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13502           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13503           return DAG.getNode(
13504               ISD::BITCAST, SDLoc(N), VT,
13505               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13506         }
13507       }
13508     }
13509   }
13510
13511   // Canonicalize shuffles according to rules:
13512   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13513   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13514   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13515   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13516       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13517       TLI.isTypeLegal(VT)) {
13518     // The incoming shuffle must be of the same type as the result of the
13519     // current shuffle.
13520     assert(N1->getOperand(0).getValueType() == VT &&
13521            "Shuffle types don't match");
13522
13523     SDValue SV0 = N1->getOperand(0);
13524     SDValue SV1 = N1->getOperand(1);
13525     bool HasSameOp0 = N0 == SV0;
13526     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13527     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13528       // Commute the operands of this shuffle so that next rule
13529       // will trigger.
13530       return DAG.getCommutedVectorShuffle(*SVN);
13531   }
13532
13533   // Try to fold according to rules:
13534   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13535   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13536   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13537   // Don't try to fold shuffles with illegal type.
13538   // Only fold if this shuffle is the only user of the other shuffle.
13539   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13540       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13541     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13542
13543     // The incoming shuffle must be of the same type as the result of the
13544     // current shuffle.
13545     assert(OtherSV->getOperand(0).getValueType() == VT &&
13546            "Shuffle types don't match");
13547
13548     SDValue SV0, SV1;
13549     SmallVector<int, 4> Mask;
13550     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13551     // operand, and SV1 as the second operand.
13552     for (unsigned i = 0; i != NumElts; ++i) {
13553       int Idx = SVN->getMaskElt(i);
13554       if (Idx < 0) {
13555         // Propagate Undef.
13556         Mask.push_back(Idx);
13557         continue;
13558       }
13559
13560       SDValue CurrentVec;
13561       if (Idx < (int)NumElts) {
13562         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13563         // shuffle mask to identify which vector is actually referenced.
13564         Idx = OtherSV->getMaskElt(Idx);
13565         if (Idx < 0) {
13566           // Propagate Undef.
13567           Mask.push_back(Idx);
13568           continue;
13569         }
13570
13571         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13572                                            : OtherSV->getOperand(1);
13573       } else {
13574         // This shuffle index references an element within N1.
13575         CurrentVec = N1;
13576       }
13577
13578       // Simple case where 'CurrentVec' is UNDEF.
13579       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13580         Mask.push_back(-1);
13581         continue;
13582       }
13583
13584       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13585       // will be the first or second operand of the combined shuffle.
13586       Idx = Idx % NumElts;
13587       if (!SV0.getNode() || SV0 == CurrentVec) {
13588         // Ok. CurrentVec is the left hand side.
13589         // Update the mask accordingly.
13590         SV0 = CurrentVec;
13591         Mask.push_back(Idx);
13592         continue;
13593       }
13594
13595       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13596       if (SV1.getNode() && SV1 != CurrentVec)
13597         return SDValue();
13598
13599       // Ok. CurrentVec is the right hand side.
13600       // Update the mask accordingly.
13601       SV1 = CurrentVec;
13602       Mask.push_back(Idx + NumElts);
13603     }
13604
13605     // Check if all indices in Mask are Undef. In case, propagate Undef.
13606     bool isUndefMask = true;
13607     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13608       isUndefMask &= Mask[i] < 0;
13609
13610     if (isUndefMask)
13611       return DAG.getUNDEF(VT);
13612
13613     if (!SV0.getNode())
13614       SV0 = DAG.getUNDEF(VT);
13615     if (!SV1.getNode())
13616       SV1 = DAG.getUNDEF(VT);
13617
13618     // Avoid introducing shuffles with illegal mask.
13619     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13620       ShuffleVectorSDNode::commuteMask(Mask);
13621
13622       if (!TLI.isShuffleMaskLegal(Mask, VT))
13623         return SDValue();
13624
13625       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13626       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13627       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13628       std::swap(SV0, SV1);
13629     }
13630
13631     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13632     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13633     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13634     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13635   }
13636
13637   return SDValue();
13638 }
13639
13640 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13641   SDValue InVal = N->getOperand(0);
13642   EVT VT = N->getValueType(0);
13643
13644   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13645   // with a VECTOR_SHUFFLE.
13646   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13647     SDValue InVec = InVal->getOperand(0);
13648     SDValue EltNo = InVal->getOperand(1);
13649
13650     // FIXME: We could support implicit truncation if the shuffle can be
13651     // scaled to a smaller vector scalar type.
13652     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13653     if (C0 && VT == InVec.getValueType() &&
13654         VT.getScalarType() == InVal.getValueType()) {
13655       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13656       int Elt = C0->getZExtValue();
13657       NewMask[0] = Elt;
13658
13659       if (TLI.isShuffleMaskLegal(NewMask, VT))
13660         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13661                                     NewMask);
13662     }
13663   }
13664
13665   return SDValue();
13666 }
13667
13668 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13669   SDValue N0 = N->getOperand(0);
13670   SDValue N2 = N->getOperand(2);
13671
13672   // If the input vector is a concatenation, and the insert replaces
13673   // one of the halves, we can optimize into a single concat_vectors.
13674   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13675       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13676     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13677     EVT VT = N->getValueType(0);
13678
13679     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13680     // (concat_vectors Z, Y)
13681     if (InsIdx == 0)
13682       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13683                          N->getOperand(1), N0.getOperand(1));
13684
13685     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13686     // (concat_vectors X, Z)
13687     if (InsIdx == VT.getVectorNumElements()/2)
13688       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13689                          N0.getOperand(0), N->getOperand(1));
13690   }
13691
13692   return SDValue();
13693 }
13694
13695 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13696   SDValue N0 = N->getOperand(0);
13697
13698   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13699   if (N0->getOpcode() == ISD::FP16_TO_FP)
13700     return N0->getOperand(0);
13701
13702   return SDValue();
13703 }
13704
13705 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13706   SDValue N0 = N->getOperand(0);
13707
13708   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13709   if (N0->getOpcode() == ISD::AND) {
13710     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13711     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13712       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13713                          N0.getOperand(0));
13714     }
13715   }
13716
13717   return SDValue();
13718 }
13719
13720 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13721 /// with the destination vector and a zero vector.
13722 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13723 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13724 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13725   EVT VT = N->getValueType(0);
13726   SDValue LHS = N->getOperand(0);
13727   SDValue RHS = N->getOperand(1);
13728   SDLoc dl(N);
13729
13730   // Make sure we're not running after operation legalization where it
13731   // may have custom lowered the vector shuffles.
13732   if (LegalOperations)
13733     return SDValue();
13734
13735   if (N->getOpcode() != ISD::AND)
13736     return SDValue();
13737
13738   if (RHS.getOpcode() == ISD::BITCAST)
13739     RHS = RHS.getOperand(0);
13740
13741   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13742     return SDValue();
13743
13744   EVT RVT = RHS.getValueType();
13745   unsigned NumElts = RHS.getNumOperands();
13746
13747   // Attempt to create a valid clear mask, splitting the mask into
13748   // sub elements and checking to see if each is
13749   // all zeros or all ones - suitable for shuffle masking.
13750   auto BuildClearMask = [&](int Split) {
13751     int NumSubElts = NumElts * Split;
13752     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13753
13754     SmallVector<int, 8> Indices;
13755     for (int i = 0; i != NumSubElts; ++i) {
13756       int EltIdx = i / Split;
13757       int SubIdx = i % Split;
13758       SDValue Elt = RHS.getOperand(EltIdx);
13759       if (Elt.getOpcode() == ISD::UNDEF) {
13760         Indices.push_back(-1);
13761         continue;
13762       }
13763
13764       APInt Bits;
13765       if (isa<ConstantSDNode>(Elt))
13766         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13767       else if (isa<ConstantFPSDNode>(Elt))
13768         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13769       else
13770         return SDValue();
13771
13772       // Extract the sub element from the constant bit mask.
13773       if (DAG.getDataLayout().isBigEndian()) {
13774         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13775       } else {
13776         Bits = Bits.lshr(SubIdx * NumSubBits);
13777       }
13778
13779       if (Split > 1)
13780         Bits = Bits.trunc(NumSubBits);
13781
13782       if (Bits.isAllOnesValue())
13783         Indices.push_back(i);
13784       else if (Bits == 0)
13785         Indices.push_back(i + NumSubElts);
13786       else
13787         return SDValue();
13788     }
13789
13790     // Let's see if the target supports this vector_shuffle.
13791     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13792     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13793     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13794       return SDValue();
13795
13796     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13797     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13798                                                    DAG.getBitcast(ClearVT, LHS),
13799                                                    Zero, &Indices[0]));
13800   };
13801
13802   // Determine maximum split level (byte level masking).
13803   int MaxSplit = 1;
13804   if (RVT.getScalarSizeInBits() % 8 == 0)
13805     MaxSplit = RVT.getScalarSizeInBits() / 8;
13806
13807   for (int Split = 1; Split <= MaxSplit; ++Split)
13808     if (RVT.getScalarSizeInBits() % Split == 0)
13809       if (SDValue S = BuildClearMask(Split))
13810         return S;
13811
13812   return SDValue();
13813 }
13814
13815 /// Visit a binary vector operation, like ADD.
13816 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13817   assert(N->getValueType(0).isVector() &&
13818          "SimplifyVBinOp only works on vectors!");
13819
13820   SDValue LHS = N->getOperand(0);
13821   SDValue RHS = N->getOperand(1);
13822   SDValue Ops[] = {LHS, RHS};
13823
13824   // See if we can constant fold the vector operation.
13825   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13826           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13827     return Fold;
13828
13829   // Try to convert a constant mask AND into a shuffle clear mask.
13830   if (SDValue Shuffle = XformToShuffleWithZero(N))
13831     return Shuffle;
13832
13833   // Type legalization might introduce new shuffles in the DAG.
13834   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13835   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13836   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13837       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13838       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13839       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13840     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13841     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13842
13843     if (SVN0->getMask().equals(SVN1->getMask())) {
13844       EVT VT = N->getValueType(0);
13845       SDValue UndefVector = LHS.getOperand(1);
13846       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13847                                      LHS.getOperand(0), RHS.getOperand(0),
13848                                      N->getFlags());
13849       AddUsersToWorklist(N);
13850       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13851                                   &SVN0->getMask()[0]);
13852     }
13853   }
13854
13855   return SDValue();
13856 }
13857
13858 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13859                                     SDValue N1, SDValue N2){
13860   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13861
13862   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13863                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13864
13865   // If we got a simplified select_cc node back from SimplifySelectCC, then
13866   // break it down into a new SETCC node, and a new SELECT node, and then return
13867   // the SELECT node, since we were called with a SELECT node.
13868   if (SCC.getNode()) {
13869     // Check to see if we got a select_cc back (to turn into setcc/select).
13870     // Otherwise, just return whatever node we got back, like fabs.
13871     if (SCC.getOpcode() == ISD::SELECT_CC) {
13872       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13873                                   N0.getValueType(),
13874                                   SCC.getOperand(0), SCC.getOperand(1),
13875                                   SCC.getOperand(4));
13876       AddToWorklist(SETCC.getNode());
13877       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13878                            SCC.getOperand(2), SCC.getOperand(3));
13879     }
13880
13881     return SCC;
13882   }
13883   return SDValue();
13884 }
13885
13886 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13887 /// being selected between, see if we can simplify the select.  Callers of this
13888 /// should assume that TheSelect is deleted if this returns true.  As such, they
13889 /// should return the appropriate thing (e.g. the node) back to the top-level of
13890 /// the DAG combiner loop to avoid it being looked at.
13891 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13892                                     SDValue RHS) {
13893
13894   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13895   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13896   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13897     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13898       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13899       SDValue Sqrt = RHS;
13900       ISD::CondCode CC;
13901       SDValue CmpLHS;
13902       const ConstantFPSDNode *NegZero = nullptr;
13903
13904       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13905         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13906         CmpLHS = TheSelect->getOperand(0);
13907         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13908       } else {
13909         // SELECT or VSELECT
13910         SDValue Cmp = TheSelect->getOperand(0);
13911         if (Cmp.getOpcode() == ISD::SETCC) {
13912           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13913           CmpLHS = Cmp.getOperand(0);
13914           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13915         }
13916       }
13917       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13918           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13919           CC == ISD::SETULT || CC == ISD::SETLT)) {
13920         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13921         CombineTo(TheSelect, Sqrt);
13922         return true;
13923       }
13924     }
13925   }
13926   // Cannot simplify select with vector condition
13927   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13928
13929   // If this is a select from two identical things, try to pull the operation
13930   // through the select.
13931   if (LHS.getOpcode() != RHS.getOpcode() ||
13932       !LHS.hasOneUse() || !RHS.hasOneUse())
13933     return false;
13934
13935   // If this is a load and the token chain is identical, replace the select
13936   // of two loads with a load through a select of the address to load from.
13937   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13938   // constants have been dropped into the constant pool.
13939   if (LHS.getOpcode() == ISD::LOAD) {
13940     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13941     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13942
13943     // Token chains must be identical.
13944     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13945         // Do not let this transformation reduce the number of volatile loads.
13946         LLD->isVolatile() || RLD->isVolatile() ||
13947         // FIXME: If either is a pre/post inc/dec load,
13948         // we'd need to split out the address adjustment.
13949         LLD->isIndexed() || RLD->isIndexed() ||
13950         // If this is an EXTLOAD, the VT's must match.
13951         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13952         // If this is an EXTLOAD, the kind of extension must match.
13953         (LLD->getExtensionType() != RLD->getExtensionType() &&
13954          // The only exception is if one of the extensions is anyext.
13955          LLD->getExtensionType() != ISD::EXTLOAD &&
13956          RLD->getExtensionType() != ISD::EXTLOAD) ||
13957         // FIXME: this discards src value information.  This is
13958         // over-conservative. It would be beneficial to be able to remember
13959         // both potential memory locations.  Since we are discarding
13960         // src value info, don't do the transformation if the memory
13961         // locations are not in the default address space.
13962         LLD->getPointerInfo().getAddrSpace() != 0 ||
13963         RLD->getPointerInfo().getAddrSpace() != 0 ||
13964         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13965                                       LLD->getBasePtr().getValueType()))
13966       return false;
13967
13968     // Check that the select condition doesn't reach either load.  If so,
13969     // folding this will induce a cycle into the DAG.  If not, this is safe to
13970     // xform, so create a select of the addresses.
13971     SDValue Addr;
13972     if (TheSelect->getOpcode() == ISD::SELECT) {
13973       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13974       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13975           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13976         return false;
13977       // The loads must not depend on one another.
13978       if (LLD->isPredecessorOf(RLD) ||
13979           RLD->isPredecessorOf(LLD))
13980         return false;
13981       Addr = DAG.getSelect(SDLoc(TheSelect),
13982                            LLD->getBasePtr().getValueType(),
13983                            TheSelect->getOperand(0), LLD->getBasePtr(),
13984                            RLD->getBasePtr());
13985     } else {  // Otherwise SELECT_CC
13986       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13987       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13988
13989       if ((LLD->hasAnyUseOfValue(1) &&
13990            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13991           (RLD->hasAnyUseOfValue(1) &&
13992            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13993         return false;
13994
13995       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13996                          LLD->getBasePtr().getValueType(),
13997                          TheSelect->getOperand(0),
13998                          TheSelect->getOperand(1),
13999                          LLD->getBasePtr(), RLD->getBasePtr(),
14000                          TheSelect->getOperand(4));
14001     }
14002
14003     SDValue Load;
14004     // It is safe to replace the two loads if they have different alignments,
14005     // but the new load must be the minimum (most restrictive) alignment of the
14006     // inputs.
14007     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
14008     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14009     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14010       Load = DAG.getLoad(TheSelect->getValueType(0),
14011                          SDLoc(TheSelect),
14012                          // FIXME: Discards pointer and AA info.
14013                          LLD->getChain(), Addr, MachinePointerInfo(),
14014                          LLD->isVolatile(), LLD->isNonTemporal(),
14015                          isInvariant, Alignment);
14016     } else {
14017       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14018                             RLD->getExtensionType() : LLD->getExtensionType(),
14019                             SDLoc(TheSelect),
14020                             TheSelect->getValueType(0),
14021                             // FIXME: Discards pointer and AA info.
14022                             LLD->getChain(), Addr, MachinePointerInfo(),
14023                             LLD->getMemoryVT(), LLD->isVolatile(),
14024                             LLD->isNonTemporal(), isInvariant, Alignment);
14025     }
14026
14027     // Users of the select now use the result of the load.
14028     CombineTo(TheSelect, Load);
14029
14030     // Users of the old loads now use the new load's chain.  We know the
14031     // old-load value is dead now.
14032     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14033     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14034     return true;
14035   }
14036
14037   return false;
14038 }
14039
14040 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14041 /// where 'cond' is the comparison specified by CC.
14042 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
14043                                       SDValue N2, SDValue N3,
14044                                       ISD::CondCode CC, bool NotExtCompare) {
14045   // (x ? y : y) -> y.
14046   if (N2 == N3) return N2;
14047
14048   EVT VT = N2.getValueType();
14049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14050   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14051
14052   // Determine if the condition we're dealing with is constant
14053   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14054                               N0, N1, CC, DL, false);
14055   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14056
14057   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14058     // fold select_cc true, x, y -> x
14059     // fold select_cc false, x, y -> y
14060     return !SCCC->isNullValue() ? N2 : N3;
14061   }
14062
14063   // Check to see if we can simplify the select into an fabs node
14064   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14065     // Allow either -0.0 or 0.0
14066     if (CFP->isZero()) {
14067       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14068       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14069           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14070           N2 == N3.getOperand(0))
14071         return DAG.getNode(ISD::FABS, DL, VT, N0);
14072
14073       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14074       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14075           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14076           N2.getOperand(0) == N3)
14077         return DAG.getNode(ISD::FABS, DL, VT, N3);
14078     }
14079   }
14080
14081   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14082   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14083   // in it.  This is a win when the constant is not otherwise available because
14084   // it replaces two constant pool loads with one.  We only do this if the FP
14085   // type is known to be legal, because if it isn't, then we are before legalize
14086   // types an we want the other legalization to happen first (e.g. to avoid
14087   // messing with soft float) and if the ConstantFP is not legal, because if
14088   // it is legal, we may not need to store the FP constant in a constant pool.
14089   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14090     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14091       if (TLI.isTypeLegal(N2.getValueType()) &&
14092           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14093                TargetLowering::Legal &&
14094            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14095            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14096           // If both constants have multiple uses, then we won't need to do an
14097           // extra load, they are likely around in registers for other users.
14098           (TV->hasOneUse() || FV->hasOneUse())) {
14099         Constant *Elts[] = {
14100           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14101           const_cast<ConstantFP*>(TV->getConstantFPValue())
14102         };
14103         Type *FPTy = Elts[0]->getType();
14104         const DataLayout &TD = DAG.getDataLayout();
14105
14106         // Create a ConstantArray of the two constants.
14107         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14108         SDValue CPIdx =
14109             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14110                                 TD.getPrefTypeAlignment(FPTy));
14111         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14112
14113         // Get the offsets to the 0 and 1 element of the array so that we can
14114         // select between them.
14115         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14116         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14117         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14118
14119         SDValue Cond = DAG.getSetCC(DL,
14120                                     getSetCCResultType(N0.getValueType()),
14121                                     N0, N1, CC);
14122         AddToWorklist(Cond.getNode());
14123         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14124                                           Cond, One, Zero);
14125         AddToWorklist(CstOffset.getNode());
14126         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14127                             CstOffset);
14128         AddToWorklist(CPIdx.getNode());
14129         return DAG.getLoad(
14130             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14131             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14132             false, false, false, Alignment);
14133       }
14134     }
14135
14136   // Check to see if we can perform the "gzip trick", transforming
14137   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14138   if (isNullConstant(N3) && CC == ISD::SETLT &&
14139       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14140        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14141     EVT XType = N0.getValueType();
14142     EVT AType = N2.getValueType();
14143     if (XType.bitsGE(AType)) {
14144       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14145       // single-bit constant.
14146       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14147         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14148         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14149         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14150                                        getShiftAmountTy(N0.getValueType()));
14151         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14152                                     XType, N0, ShCt);
14153         AddToWorklist(Shift.getNode());
14154
14155         if (XType.bitsGT(AType)) {
14156           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14157           AddToWorklist(Shift.getNode());
14158         }
14159
14160         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14161       }
14162
14163       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14164                                   XType, N0,
14165                                   DAG.getConstant(XType.getSizeInBits() - 1,
14166                                                   SDLoc(N0),
14167                                          getShiftAmountTy(N0.getValueType())));
14168       AddToWorklist(Shift.getNode());
14169
14170       if (XType.bitsGT(AType)) {
14171         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14172         AddToWorklist(Shift.getNode());
14173       }
14174
14175       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14176     }
14177   }
14178
14179   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14180   // where y is has a single bit set.
14181   // A plaintext description would be, we can turn the SELECT_CC into an AND
14182   // when the condition can be materialized as an all-ones register.  Any
14183   // single bit-test can be materialized as an all-ones register with
14184   // shift-left and shift-right-arith.
14185   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14186       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14187     SDValue AndLHS = N0->getOperand(0);
14188     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14189     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14190       // Shift the tested bit over the sign bit.
14191       APInt AndMask = ConstAndRHS->getAPIntValue();
14192       SDValue ShlAmt =
14193         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14194                         getShiftAmountTy(AndLHS.getValueType()));
14195       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14196
14197       // Now arithmetic right shift it all the way over, so the result is either
14198       // all-ones, or zero.
14199       SDValue ShrAmt =
14200         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14201                         getShiftAmountTy(Shl.getValueType()));
14202       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14203
14204       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14205     }
14206   }
14207
14208   // fold select C, 16, 0 -> shl C, 4
14209   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14210       TLI.getBooleanContents(N0.getValueType()) ==
14211           TargetLowering::ZeroOrOneBooleanContent) {
14212
14213     // If the caller doesn't want us to simplify this into a zext of a compare,
14214     // don't do it.
14215     if (NotExtCompare && N2C->isOne())
14216       return SDValue();
14217
14218     // Get a SetCC of the condition
14219     // NOTE: Don't create a SETCC if it's not legal on this target.
14220     if (!LegalOperations ||
14221         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14222       SDValue Temp, SCC;
14223       // cast from setcc result type to select result type
14224       if (LegalTypes) {
14225         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14226                             N0, N1, CC);
14227         if (N2.getValueType().bitsLT(SCC.getValueType()))
14228           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14229                                         N2.getValueType());
14230         else
14231           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14232                              N2.getValueType(), SCC);
14233       } else {
14234         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14235         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14236                            N2.getValueType(), SCC);
14237       }
14238
14239       AddToWorklist(SCC.getNode());
14240       AddToWorklist(Temp.getNode());
14241
14242       if (N2C->isOne())
14243         return Temp;
14244
14245       // shl setcc result by log2 n2c
14246       return DAG.getNode(
14247           ISD::SHL, DL, N2.getValueType(), Temp,
14248           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14249                           getShiftAmountTy(Temp.getValueType())));
14250     }
14251   }
14252
14253   // Check to see if this is an integer abs.
14254   // select_cc setg[te] X,  0,  X, -X ->
14255   // select_cc setgt    X, -1,  X, -X ->
14256   // select_cc setl[te] X,  0, -X,  X ->
14257   // select_cc setlt    X,  1, -X,  X ->
14258   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14259   if (N1C) {
14260     ConstantSDNode *SubC = nullptr;
14261     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14262          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14263         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14264       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14265     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14266               (N1C->isOne() && CC == ISD::SETLT)) &&
14267              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14268       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14269
14270     EVT XType = N0.getValueType();
14271     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14272       SDLoc DL(N0);
14273       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14274                                   N0,
14275                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14276                                          getShiftAmountTy(N0.getValueType())));
14277       SDValue Add = DAG.getNode(ISD::ADD, DL,
14278                                 XType, N0, Shift);
14279       AddToWorklist(Shift.getNode());
14280       AddToWorklist(Add.getNode());
14281       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14282     }
14283   }
14284
14285   return SDValue();
14286 }
14287
14288 /// This is a stub for TargetLowering::SimplifySetCC.
14289 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14290                                    SDValue N1, ISD::CondCode Cond,
14291                                    SDLoc DL, bool foldBooleans) {
14292   TargetLowering::DAGCombinerInfo
14293     DagCombineInfo(DAG, Level, false, this);
14294   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14295 }
14296
14297 /// Given an ISD::SDIV node expressing a divide by constant, return
14298 /// a DAG expression to select that will generate the same value by multiplying
14299 /// by a magic number.
14300 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14301 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14302   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14303   if (!C)
14304     return SDValue();
14305
14306   // Avoid division by zero.
14307   if (C->isNullValue())
14308     return SDValue();
14309
14310   std::vector<SDNode*> Built;
14311   SDValue S =
14312       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14313
14314   for (SDNode *N : Built)
14315     AddToWorklist(N);
14316   return S;
14317 }
14318
14319 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14320 /// DAG expression that will generate the same value by right shifting.
14321 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14322   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14323   if (!C)
14324     return SDValue();
14325
14326   // Avoid division by zero.
14327   if (C->isNullValue())
14328     return SDValue();
14329
14330   std::vector<SDNode *> Built;
14331   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14332
14333   for (SDNode *N : Built)
14334     AddToWorklist(N);
14335   return S;
14336 }
14337
14338 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14339 /// expression that will generate the same value by multiplying by a magic
14340 /// number.
14341 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14342 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14343   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14344   if (!C)
14345     return SDValue();
14346
14347   // Avoid division by zero.
14348   if (C->isNullValue())
14349     return SDValue();
14350
14351   std::vector<SDNode*> Built;
14352   SDValue S =
14353       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14354
14355   for (SDNode *N : Built)
14356     AddToWorklist(N);
14357   return S;
14358 }
14359
14360 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14361   if (Level >= AfterLegalizeDAG)
14362     return SDValue();
14363
14364   // Expose the DAG combiner to the target combiner implementations.
14365   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14366
14367   unsigned Iterations = 0;
14368   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14369     if (Iterations) {
14370       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14371       // For the reciprocal, we need to find the zero of the function:
14372       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14373       //     =>
14374       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14375       //     does not require additional intermediate precision]
14376       EVT VT = Op.getValueType();
14377       SDLoc DL(Op);
14378       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14379
14380       AddToWorklist(Est.getNode());
14381
14382       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14383       for (unsigned i = 0; i < Iterations; ++i) {
14384         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14385         AddToWorklist(NewEst.getNode());
14386
14387         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14388         AddToWorklist(NewEst.getNode());
14389
14390         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14391         AddToWorklist(NewEst.getNode());
14392
14393         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14394         AddToWorklist(Est.getNode());
14395       }
14396     }
14397     return Est;
14398   }
14399
14400   return SDValue();
14401 }
14402
14403 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14404 /// For the reciprocal sqrt, we need to find the zero of the function:
14405 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14406 ///     =>
14407 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14408 /// As a result, we precompute A/2 prior to the iteration loop.
14409 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14410                                           unsigned Iterations,
14411                                           SDNodeFlags *Flags) {
14412   EVT VT = Arg.getValueType();
14413   SDLoc DL(Arg);
14414   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14415
14416   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14417   // this entire sequence requires only one FP constant.
14418   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14419   AddToWorklist(HalfArg.getNode());
14420
14421   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14422   AddToWorklist(HalfArg.getNode());
14423
14424   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14425   for (unsigned i = 0; i < Iterations; ++i) {
14426     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14427     AddToWorklist(NewEst.getNode());
14428
14429     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14430     AddToWorklist(NewEst.getNode());
14431
14432     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14433     AddToWorklist(NewEst.getNode());
14434
14435     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14436     AddToWorklist(Est.getNode());
14437   }
14438   return Est;
14439 }
14440
14441 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14442 /// For the reciprocal sqrt, we need to find the zero of the function:
14443 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14444 ///     =>
14445 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14446 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14447                                           unsigned Iterations,
14448                                           SDNodeFlags *Flags) {
14449   EVT VT = Arg.getValueType();
14450   SDLoc DL(Arg);
14451   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14452   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14453
14454   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14455   for (unsigned i = 0; i < Iterations; ++i) {
14456     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14457     AddToWorklist(HalfEst.getNode());
14458
14459     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14460     AddToWorklist(Est.getNode());
14461
14462     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14463     AddToWorklist(Est.getNode());
14464
14465     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14466     AddToWorklist(Est.getNode());
14467
14468     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14469     AddToWorklist(Est.getNode());
14470   }
14471   return Est;
14472 }
14473
14474 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14475   if (Level >= AfterLegalizeDAG)
14476     return SDValue();
14477
14478   // Expose the DAG combiner to the target combiner implementations.
14479   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14480   unsigned Iterations = 0;
14481   bool UseOneConstNR = false;
14482   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14483     AddToWorklist(Est.getNode());
14484     if (Iterations) {
14485       Est = UseOneConstNR ?
14486         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14487         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14488     }
14489     return Est;
14490   }
14491
14492   return SDValue();
14493 }
14494
14495 /// Return true if base is a frame index, which is known not to alias with
14496 /// anything but itself.  Provides base object and offset as results.
14497 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14498                            const GlobalValue *&GV, const void *&CV) {
14499   // Assume it is a primitive operation.
14500   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14501
14502   // If it's an adding a simple constant then integrate the offset.
14503   if (Base.getOpcode() == ISD::ADD) {
14504     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14505       Base = Base.getOperand(0);
14506       Offset += C->getZExtValue();
14507     }
14508   }
14509
14510   // Return the underlying GlobalValue, and update the Offset.  Return false
14511   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14512   // by multiple nodes with different offsets.
14513   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14514     GV = G->getGlobal();
14515     Offset += G->getOffset();
14516     return false;
14517   }
14518
14519   // Return the underlying Constant value, and update the Offset.  Return false
14520   // for ConstantSDNodes since the same constant pool entry may be represented
14521   // by multiple nodes with different offsets.
14522   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14523     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14524                                          : (const void *)C->getConstVal();
14525     Offset += C->getOffset();
14526     return false;
14527   }
14528   // If it's any of the following then it can't alias with anything but itself.
14529   return isa<FrameIndexSDNode>(Base);
14530 }
14531
14532 /// Return true if there is any possibility that the two addresses overlap.
14533 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14534   // If they are the same then they must be aliases.
14535   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14536
14537   // If they are both volatile then they cannot be reordered.
14538   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14539
14540   // If one operation reads from invariant memory, and the other may store, they
14541   // cannot alias. These should really be checking the equivalent of mayWrite,
14542   // but it only matters for memory nodes other than load /store.
14543   if (Op0->isInvariant() && Op1->writeMem())
14544     return false;
14545
14546   if (Op1->isInvariant() && Op0->writeMem())
14547     return false;
14548
14549   // Gather base node and offset information.
14550   SDValue Base1, Base2;
14551   int64_t Offset1, Offset2;
14552   const GlobalValue *GV1, *GV2;
14553   const void *CV1, *CV2;
14554   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14555                                       Base1, Offset1, GV1, CV1);
14556   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14557                                       Base2, Offset2, GV2, CV2);
14558
14559   // If they have a same base address then check to see if they overlap.
14560   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14561     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14562              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14563
14564   // It is possible for different frame indices to alias each other, mostly
14565   // when tail call optimization reuses return address slots for arguments.
14566   // To catch this case, look up the actual index of frame indices to compute
14567   // the real alias relationship.
14568   if (isFrameIndex1 && isFrameIndex2) {
14569     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14570     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14571     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14572     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14573              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14574   }
14575
14576   // Otherwise, if we know what the bases are, and they aren't identical, then
14577   // we know they cannot alias.
14578   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14579     return false;
14580
14581   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14582   // compared to the size and offset of the access, we may be able to prove they
14583   // do not alias.  This check is conservative for now to catch cases created by
14584   // splitting vector types.
14585   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14586       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14587       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14588        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14589       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14590     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14591     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14592
14593     // There is no overlap between these relatively aligned accesses of similar
14594     // size, return no alias.
14595     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14596         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14597       return false;
14598   }
14599
14600   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14601                    ? CombinerGlobalAA
14602                    : DAG.getSubtarget().useAA();
14603 #ifndef NDEBUG
14604   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14605       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14606     UseAA = false;
14607 #endif
14608   if (UseAA &&
14609       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14610     // Use alias analysis information.
14611     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14612                                  Op1->getSrcValueOffset());
14613     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14614         Op0->getSrcValueOffset() - MinOffset;
14615     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14616         Op1->getSrcValueOffset() - MinOffset;
14617     AliasResult AAResult =
14618         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14619                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14620                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14621                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14622     if (AAResult == NoAlias)
14623       return false;
14624   }
14625
14626   // Otherwise we have to assume they alias.
14627   return true;
14628 }
14629
14630 /// Walk up chain skipping non-aliasing memory nodes,
14631 /// looking for aliasing nodes and adding them to the Aliases vector.
14632 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14633                                    SmallVectorImpl<SDValue> &Aliases) {
14634   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14635   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14636
14637   // Get alias information for node.
14638   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14639
14640   // Starting off.
14641   Chains.push_back(OriginalChain);
14642   unsigned Depth = 0;
14643
14644   // Look at each chain and determine if it is an alias.  If so, add it to the
14645   // aliases list.  If not, then continue up the chain looking for the next
14646   // candidate.
14647   while (!Chains.empty()) {
14648     SDValue Chain = Chains.pop_back_val();
14649
14650     // For TokenFactor nodes, look at each operand and only continue up the
14651     // chain until we reach the depth limit.
14652     //
14653     // FIXME: The depth check could be made to return the last non-aliasing
14654     // chain we found before we hit a tokenfactor rather than the original
14655     // chain.
14656     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14657       Aliases.clear();
14658       Aliases.push_back(OriginalChain);
14659       return;
14660     }
14661
14662     // Don't bother if we've been before.
14663     if (!Visited.insert(Chain.getNode()).second)
14664       continue;
14665
14666     switch (Chain.getOpcode()) {
14667     case ISD::EntryToken:
14668       // Entry token is ideal chain operand, but handled in FindBetterChain.
14669       break;
14670
14671     case ISD::LOAD:
14672     case ISD::STORE: {
14673       // Get alias information for Chain.
14674       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14675           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14676
14677       // If chain is alias then stop here.
14678       if (!(IsLoad && IsOpLoad) &&
14679           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14680         Aliases.push_back(Chain);
14681       } else {
14682         // Look further up the chain.
14683         Chains.push_back(Chain.getOperand(0));
14684         ++Depth;
14685       }
14686       break;
14687     }
14688
14689     case ISD::TokenFactor:
14690       // We have to check each of the operands of the token factor for "small"
14691       // token factors, so we queue them up.  Adding the operands to the queue
14692       // (stack) in reverse order maintains the original order and increases the
14693       // likelihood that getNode will find a matching token factor (CSE.)
14694       if (Chain.getNumOperands() > 16) {
14695         Aliases.push_back(Chain);
14696         break;
14697       }
14698       for (unsigned n = Chain.getNumOperands(); n;)
14699         Chains.push_back(Chain.getOperand(--n));
14700       ++Depth;
14701       break;
14702
14703     default:
14704       // For all other instructions we will just have to take what we can get.
14705       Aliases.push_back(Chain);
14706       break;
14707     }
14708   }
14709
14710   // We need to be careful here to also search for aliases through the
14711   // value operand of a store, etc. Consider the following situation:
14712   //   Token1 = ...
14713   //   L1 = load Token1, %52
14714   //   S1 = store Token1, L1, %51
14715   //   L2 = load Token1, %52+8
14716   //   S2 = store Token1, L2, %51+8
14717   //   Token2 = Token(S1, S2)
14718   //   L3 = load Token2, %53
14719   //   S3 = store Token2, L3, %52
14720   //   L4 = load Token2, %53+8
14721   //   S4 = store Token2, L4, %52+8
14722   // If we search for aliases of S3 (which loads address %52), and we look
14723   // only through the chain, then we'll miss the trivial dependence on L1
14724   // (which also loads from %52). We then might change all loads and
14725   // stores to use Token1 as their chain operand, which could result in
14726   // copying %53 into %52 before copying %52 into %51 (which should
14727   // happen first).
14728   //
14729   // The problem is, however, that searching for such data dependencies
14730   // can become expensive, and the cost is not directly related to the
14731   // chain depth. Instead, we'll rule out such configurations here by
14732   // insisting that we've visited all chain users (except for users
14733   // of the original chain, which is not necessary). When doing this,
14734   // we need to look through nodes we don't care about (otherwise, things
14735   // like register copies will interfere with trivial cases).
14736
14737   SmallVector<const SDNode *, 16> Worklist;
14738   for (const SDNode *N : Visited)
14739     if (N != OriginalChain.getNode())
14740       Worklist.push_back(N);
14741
14742   while (!Worklist.empty()) {
14743     const SDNode *M = Worklist.pop_back_val();
14744
14745     // We have already visited M, and want to make sure we've visited any uses
14746     // of M that we care about. For uses that we've not visisted, and don't
14747     // care about, queue them to the worklist.
14748
14749     for (SDNode::use_iterator UI = M->use_begin(),
14750          UIE = M->use_end(); UI != UIE; ++UI)
14751       if (UI.getUse().getValueType() == MVT::Other &&
14752           Visited.insert(*UI).second) {
14753         if (isa<MemSDNode>(*UI)) {
14754           // We've not visited this use, and we care about it (it could have an
14755           // ordering dependency with the original node).
14756           Aliases.clear();
14757           Aliases.push_back(OriginalChain);
14758           return;
14759         }
14760
14761         // We've not visited this use, but we don't care about it. Mark it as
14762         // visited and enqueue it to the worklist.
14763         Worklist.push_back(*UI);
14764       }
14765   }
14766 }
14767
14768 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14769 /// (aliasing node.)
14770 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14771   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14772
14773   // Accumulate all the aliases to this node.
14774   GatherAllAliases(N, OldChain, Aliases);
14775
14776   // If no operands then chain to entry token.
14777   if (Aliases.size() == 0)
14778     return DAG.getEntryNode();
14779
14780   // If a single operand then chain to it.  We don't need to revisit it.
14781   if (Aliases.size() == 1)
14782     return Aliases[0];
14783
14784   // Construct a custom tailored token factor.
14785   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14786 }
14787
14788 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14789   // This holds the base pointer, index, and the offset in bytes from the base
14790   // pointer.
14791   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14792
14793   // We must have a base and an offset.
14794   if (!BasePtr.Base.getNode())
14795     return false;
14796
14797   // Do not handle stores to undef base pointers.
14798   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14799     return false;
14800
14801   SmallVector<StoreSDNode *, 8> ChainedStores;
14802   ChainedStores.push_back(St);
14803
14804   // Walk up the chain and look for nodes with offsets from the same
14805   // base pointer. Stop when reaching an instruction with a different kind
14806   // or instruction which has a different base pointer.
14807   StoreSDNode *Index = St;
14808   while (Index) {
14809     // If the chain has more than one use, then we can't reorder the mem ops.
14810     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14811       break;
14812
14813     if (Index->isVolatile() || Index->isIndexed())
14814       break;
14815
14816     // Find the base pointer and offset for this memory node.
14817     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14818
14819     // Check that the base pointer is the same as the original one.
14820     if (!Ptr.equalBaseIndex(BasePtr))
14821       break;
14822
14823     // Find the next memory operand in the chain. If the next operand in the
14824     // chain is a store then move up and continue the scan with the next
14825     // memory operand. If the next operand is a load save it and use alias
14826     // information to check if it interferes with anything.
14827     SDNode *NextInChain = Index->getChain().getNode();
14828     while (true) {
14829       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14830         // We found a store node. Use it for the next iteration.
14831         ChainedStores.push_back(STn);
14832         Index = STn;
14833         break;
14834       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14835         NextInChain = Ldn->getChain().getNode();
14836         continue;
14837       } else {
14838         Index = nullptr;
14839         break;
14840       }
14841     }
14842   }
14843
14844   bool MadeChange = false;
14845   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14846
14847   for (StoreSDNode *ChainedStore : ChainedStores) {
14848     SDValue Chain = ChainedStore->getChain();
14849     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14850
14851     if (Chain != BetterChain) {
14852       MadeChange = true;
14853       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14854     }
14855   }
14856
14857   // Do all replacements after finding the replacements to make to avoid making
14858   // the chains more complicated by introducing new TokenFactors.
14859   for (auto Replacement : BetterChains)
14860     replaceStoreChain(Replacement.first, Replacement.second);
14861
14862   return MadeChange;
14863 }
14864
14865 /// This is the entry point for the file.
14866 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14867                            CodeGenOpt::Level OptLevel) {
14868   /// This is the main entry point to this class.
14869   DAGCombiner(*this, AA, OptLevel).Run(Level);
14870 }