[SelectionDAGBuilder] Set NoUnsignedWrap for inbounds gep and load/store offsets.
[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   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
928     return false;
929
930   // Revisit the node.
931   AddToWorklist(Op.getNode());
932
933   // Replace the old value with the new one.
934   ++NodesCombined;
935   DEBUG(dbgs() << "\nReplacing.2 ";
936         TLO.Old.getNode()->dump(&DAG);
937         dbgs() << "\nWith: ";
938         TLO.New.getNode()->dump(&DAG);
939         dbgs() << '\n');
940
941   CommitTargetLoweringOpt(TLO);
942   return true;
943 }
944
945 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
946   SDLoc dl(Load);
947   EVT VT = Load->getValueType(0);
948   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
949
950   DEBUG(dbgs() << "\nReplacing.9 ";
951         Load->dump(&DAG);
952         dbgs() << "\nWith: ";
953         Trunc.getNode()->dump(&DAG);
954         dbgs() << '\n');
955   WorklistRemover DeadNodes(*this);
956   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
957   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
958   deleteAndRecombine(Load);
959   AddToWorklist(Trunc.getNode());
960 }
961
962 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
963   Replace = false;
964   SDLoc dl(Op);
965   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
966     EVT MemVT = LD->getMemoryVT();
967     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
968       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
969                                                        : ISD::EXTLOAD)
970       : LD->getExtensionType();
971     Replace = true;
972     return DAG.getExtLoad(ExtType, dl, PVT,
973                           LD->getChain(), LD->getBasePtr(),
974                           MemVT, LD->getMemOperand());
975   }
976
977   unsigned Opc = Op.getOpcode();
978   switch (Opc) {
979   default: break;
980   case ISD::AssertSext:
981     return DAG.getNode(ISD::AssertSext, dl, PVT,
982                        SExtPromoteOperand(Op.getOperand(0), PVT),
983                        Op.getOperand(1));
984   case ISD::AssertZext:
985     return DAG.getNode(ISD::AssertZext, dl, PVT,
986                        ZExtPromoteOperand(Op.getOperand(0), PVT),
987                        Op.getOperand(1));
988   case ISD::Constant: {
989     unsigned ExtOpc =
990       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
991     return DAG.getNode(ExtOpc, dl, PVT, Op);
992   }
993   }
994
995   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
996     return SDValue();
997   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
998 }
999
1000 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1001   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1002     return SDValue();
1003   EVT OldVT = Op.getValueType();
1004   SDLoc dl(Op);
1005   bool Replace = false;
1006   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1007   if (!NewOp.getNode())
1008     return SDValue();
1009   AddToWorklist(NewOp.getNode());
1010
1011   if (Replace)
1012     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1013   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1014                      DAG.getValueType(OldVT));
1015 }
1016
1017 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1018   EVT OldVT = Op.getValueType();
1019   SDLoc dl(Op);
1020   bool Replace = false;
1021   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1022   if (!NewOp.getNode())
1023     return SDValue();
1024   AddToWorklist(NewOp.getNode());
1025
1026   if (Replace)
1027     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1028   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1029 }
1030
1031 /// Promote the specified integer binary operation if the target indicates it is
1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1033 /// i32 since i16 instructions are longer.
1034 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1035   if (!LegalOperations)
1036     return SDValue();
1037
1038   EVT VT = Op.getValueType();
1039   if (VT.isVector() || !VT.isInteger())
1040     return SDValue();
1041
1042   // If operation type is 'undesirable', e.g. i16 on x86, consider
1043   // promoting it.
1044   unsigned Opc = Op.getOpcode();
1045   if (TLI.isTypeDesirableForOp(Opc, VT))
1046     return SDValue();
1047
1048   EVT PVT = VT;
1049   // Consult target whether it is a good idea to promote this operation and
1050   // what's the right type to promote it to.
1051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052     assert(PVT != VT && "Don't know what type to promote to!");
1053
1054     bool Replace0 = false;
1055     SDValue N0 = Op.getOperand(0);
1056     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1057     if (!NN0.getNode())
1058       return SDValue();
1059
1060     bool Replace1 = false;
1061     SDValue N1 = Op.getOperand(1);
1062     SDValue NN1;
1063     if (N0 == N1)
1064       NN1 = NN0;
1065     else {
1066       NN1 = PromoteOperand(N1, PVT, Replace1);
1067       if (!NN1.getNode())
1068         return SDValue();
1069     }
1070
1071     AddToWorklist(NN0.getNode());
1072     if (NN1.getNode())
1073       AddToWorklist(NN1.getNode());
1074
1075     if (Replace0)
1076       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1077     if (Replace1)
1078       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1079
1080     DEBUG(dbgs() << "\nPromoting ";
1081           Op.getNode()->dump(&DAG));
1082     SDLoc dl(Op);
1083     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1084                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1085   }
1086   return SDValue();
1087 }
1088
1089 /// Promote the specified integer shift operation if the target indicates it is
1090 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1091 /// i32 since i16 instructions are longer.
1092 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1093   if (!LegalOperations)
1094     return SDValue();
1095
1096   EVT VT = Op.getValueType();
1097   if (VT.isVector() || !VT.isInteger())
1098     return SDValue();
1099
1100   // If operation type is 'undesirable', e.g. i16 on x86, consider
1101   // promoting it.
1102   unsigned Opc = Op.getOpcode();
1103   if (TLI.isTypeDesirableForOp(Opc, VT))
1104     return SDValue();
1105
1106   EVT PVT = VT;
1107   // Consult target whether it is a good idea to promote this operation and
1108   // what's the right type to promote it to.
1109   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1110     assert(PVT != VT && "Don't know what type to promote to!");
1111
1112     bool Replace = false;
1113     SDValue N0 = Op.getOperand(0);
1114     if (Opc == ISD::SRA)
1115       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1116     else if (Opc == ISD::SRL)
1117       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1118     else
1119       N0 = PromoteOperand(N0, PVT, Replace);
1120     if (!N0.getNode())
1121       return SDValue();
1122
1123     AddToWorklist(N0.getNode());
1124     if (Replace)
1125       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1126
1127     DEBUG(dbgs() << "\nPromoting ";
1128           Op.getNode()->dump(&DAG));
1129     SDLoc dl(Op);
1130     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1131                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1132   }
1133   return SDValue();
1134 }
1135
1136 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1137   if (!LegalOperations)
1138     return SDValue();
1139
1140   EVT VT = Op.getValueType();
1141   if (VT.isVector() || !VT.isInteger())
1142     return SDValue();
1143
1144   // If operation type is 'undesirable', e.g. i16 on x86, consider
1145   // promoting it.
1146   unsigned Opc = Op.getOpcode();
1147   if (TLI.isTypeDesirableForOp(Opc, VT))
1148     return SDValue();
1149
1150   EVT PVT = VT;
1151   // Consult target whether it is a good idea to promote this operation and
1152   // what's the right type to promote it to.
1153   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1154     assert(PVT != VT && "Don't know what type to promote to!");
1155     // fold (aext (aext x)) -> (aext x)
1156     // fold (aext (zext x)) -> (zext x)
1157     // fold (aext (sext x)) -> (sext x)
1158     DEBUG(dbgs() << "\nPromoting ";
1159           Op.getNode()->dump(&DAG));
1160     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1161   }
1162   return SDValue();
1163 }
1164
1165 bool DAGCombiner::PromoteLoad(SDValue Op) {
1166   if (!LegalOperations)
1167     return false;
1168
1169   EVT VT = Op.getValueType();
1170   if (VT.isVector() || !VT.isInteger())
1171     return false;
1172
1173   // If operation type is 'undesirable', e.g. i16 on x86, consider
1174   // promoting it.
1175   unsigned Opc = Op.getOpcode();
1176   if (TLI.isTypeDesirableForOp(Opc, VT))
1177     return false;
1178
1179   EVT PVT = VT;
1180   // Consult target whether it is a good idea to promote this operation and
1181   // what's the right type to promote it to.
1182   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1183     assert(PVT != VT && "Don't know what type to promote to!");
1184
1185     SDLoc dl(Op);
1186     SDNode *N = Op.getNode();
1187     LoadSDNode *LD = cast<LoadSDNode>(N);
1188     EVT MemVT = LD->getMemoryVT();
1189     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1190       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1191                                                        : ISD::EXTLOAD)
1192       : LD->getExtensionType();
1193     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1194                                    LD->getChain(), LD->getBasePtr(),
1195                                    MemVT, LD->getMemOperand());
1196     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1197
1198     DEBUG(dbgs() << "\nPromoting ";
1199           N->dump(&DAG);
1200           dbgs() << "\nTo: ";
1201           Result.getNode()->dump(&DAG);
1202           dbgs() << '\n');
1203     WorklistRemover DeadNodes(*this);
1204     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1205     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1206     deleteAndRecombine(N);
1207     AddToWorklist(Result.getNode());
1208     return true;
1209   }
1210   return false;
1211 }
1212
1213 /// \brief Recursively delete a node which has no uses and any operands for
1214 /// which it is the only use.
1215 ///
1216 /// Note that this both deletes the nodes and removes them from the worklist.
1217 /// It also adds any nodes who have had a user deleted to the worklist as they
1218 /// may now have only one use and subject to other combines.
1219 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1220   if (!N->use_empty())
1221     return false;
1222
1223   SmallSetVector<SDNode *, 16> Nodes;
1224   Nodes.insert(N);
1225   do {
1226     N = Nodes.pop_back_val();
1227     if (!N)
1228       continue;
1229
1230     if (N->use_empty()) {
1231       for (const SDValue &ChildN : N->op_values())
1232         Nodes.insert(ChildN.getNode());
1233
1234       removeFromWorklist(N);
1235       DAG.DeleteNode(N);
1236     } else {
1237       AddToWorklist(N);
1238     }
1239   } while (!Nodes.empty());
1240   return true;
1241 }
1242
1243 //===----------------------------------------------------------------------===//
1244 //  Main DAG Combiner implementation
1245 //===----------------------------------------------------------------------===//
1246
1247 void DAGCombiner::Run(CombineLevel AtLevel) {
1248   // set the instance variables, so that the various visit routines may use it.
1249   Level = AtLevel;
1250   LegalOperations = Level >= AfterLegalizeVectorOps;
1251   LegalTypes = Level >= AfterLegalizeTypes;
1252
1253   // Add all the dag nodes to the worklist.
1254   for (SDNode &Node : DAG.allnodes())
1255     AddToWorklist(&Node);
1256
1257   // Create a dummy node (which is not added to allnodes), that adds a reference
1258   // to the root node, preventing it from being deleted, and tracking any
1259   // changes of the root.
1260   HandleSDNode Dummy(DAG.getRoot());
1261
1262   // while the worklist isn't empty, find a node and
1263   // try and combine it.
1264   while (!WorklistMap.empty()) {
1265     SDNode *N;
1266     // The Worklist holds the SDNodes in order, but it may contain null entries.
1267     do {
1268       N = Worklist.pop_back_val();
1269     } while (!N);
1270
1271     bool GoodWorklistEntry = WorklistMap.erase(N);
1272     (void)GoodWorklistEntry;
1273     assert(GoodWorklistEntry &&
1274            "Found a worklist entry without a corresponding map entry!");
1275
1276     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1277     // N is deleted from the DAG, since they too may now be dead or may have a
1278     // reduced number of uses, allowing other xforms.
1279     if (recursivelyDeleteUnusedNodes(N))
1280       continue;
1281
1282     WorklistRemover DeadNodes(*this);
1283
1284     // If this combine is running after legalizing the DAG, re-legalize any
1285     // nodes pulled off the worklist.
1286     if (Level == AfterLegalizeDAG) {
1287       SmallSetVector<SDNode *, 16> UpdatedNodes;
1288       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1289
1290       for (SDNode *LN : UpdatedNodes) {
1291         AddToWorklist(LN);
1292         AddUsersToWorklist(LN);
1293       }
1294       if (!NIsValid)
1295         continue;
1296     }
1297
1298     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1299
1300     // Add any operands of the new node which have not yet been combined to the
1301     // worklist as well. Because the worklist uniques things already, this
1302     // won't repeatedly process the same operand.
1303     CombinedNodes.insert(N);
1304     for (const SDValue &ChildN : N->op_values())
1305       if (!CombinedNodes.count(ChildN.getNode()))
1306         AddToWorklist(ChildN.getNode());
1307
1308     SDValue RV = combine(N);
1309
1310     if (!RV.getNode())
1311       continue;
1312
1313     ++NodesCombined;
1314
1315     // If we get back the same node we passed in, rather than a new node or
1316     // zero, we know that the node must have defined multiple values and
1317     // CombineTo was used.  Since CombineTo takes care of the worklist
1318     // mechanics for us, we have no work to do in this case.
1319     if (RV.getNode() == N)
1320       continue;
1321
1322     assert(N->getOpcode() != ISD::DELETED_NODE &&
1323            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1324            "Node was deleted but visit returned new node!");
1325
1326     DEBUG(dbgs() << " ... into: ";
1327           RV.getNode()->dump(&DAG));
1328
1329     // Transfer debug value.
1330     DAG.TransferDbgValues(SDValue(N, 0), RV);
1331     if (N->getNumValues() == RV.getNode()->getNumValues())
1332       DAG.ReplaceAllUsesWith(N, RV.getNode());
1333     else {
1334       assert(N->getValueType(0) == RV.getValueType() &&
1335              N->getNumValues() == 1 && "Type mismatch");
1336       SDValue OpV = RV;
1337       DAG.ReplaceAllUsesWith(N, &OpV);
1338     }
1339
1340     // Push the new node and any users onto the worklist
1341     AddToWorklist(RV.getNode());
1342     AddUsersToWorklist(RV.getNode());
1343
1344     // Finally, if the node is now dead, remove it from the graph.  The node
1345     // may not be dead if the replacement process recursively simplified to
1346     // something else needing this node. This will also take care of adding any
1347     // operands which have lost a user to the worklist.
1348     recursivelyDeleteUnusedNodes(N);
1349   }
1350
1351   // If the root changed (e.g. it was a dead load, update the root).
1352   DAG.setRoot(Dummy.getValue());
1353   DAG.RemoveDeadNodes();
1354 }
1355
1356 SDValue DAGCombiner::visit(SDNode *N) {
1357   switch (N->getOpcode()) {
1358   default: break;
1359   case ISD::TokenFactor:        return visitTokenFactor(N);
1360   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1361   case ISD::ADD:                return visitADD(N);
1362   case ISD::SUB:                return visitSUB(N);
1363   case ISD::ADDC:               return visitADDC(N);
1364   case ISD::SUBC:               return visitSUBC(N);
1365   case ISD::ADDE:               return visitADDE(N);
1366   case ISD::SUBE:               return visitSUBE(N);
1367   case ISD::MUL:                return visitMUL(N);
1368   case ISD::SDIV:               return visitSDIV(N);
1369   case ISD::UDIV:               return visitUDIV(N);
1370   case ISD::SREM:
1371   case ISD::UREM:               return visitREM(N);
1372   case ISD::MULHU:              return visitMULHU(N);
1373   case ISD::MULHS:              return visitMULHS(N);
1374   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1375   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1376   case ISD::SMULO:              return visitSMULO(N);
1377   case ISD::UMULO:              return visitUMULO(N);
1378   case ISD::SMIN:
1379   case ISD::SMAX:
1380   case ISD::UMIN:
1381   case ISD::UMAX:               return visitIMINMAX(N);
1382   case ISD::AND:                return visitAND(N);
1383   case ISD::OR:                 return visitOR(N);
1384   case ISD::XOR:                return visitXOR(N);
1385   case ISD::SHL:                return visitSHL(N);
1386   case ISD::SRA:                return visitSRA(N);
1387   case ISD::SRL:                return visitSRL(N);
1388   case ISD::ROTR:
1389   case ISD::ROTL:               return visitRotate(N);
1390   case ISD::BSWAP:              return visitBSWAP(N);
1391   case ISD::CTLZ:               return visitCTLZ(N);
1392   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1393   case ISD::CTTZ:               return visitCTTZ(N);
1394   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1395   case ISD::CTPOP:              return visitCTPOP(N);
1396   case ISD::SELECT:             return visitSELECT(N);
1397   case ISD::VSELECT:            return visitVSELECT(N);
1398   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1399   case ISD::SETCC:              return visitSETCC(N);
1400   case ISD::SETCCE:             return visitSETCCE(N);
1401   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1402   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1403   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1404   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1405   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1406   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1407   case ISD::BITCAST:            return visitBITCAST(N);
1408   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1409   case ISD::FADD:               return visitFADD(N);
1410   case ISD::FSUB:               return visitFSUB(N);
1411   case ISD::FMUL:               return visitFMUL(N);
1412   case ISD::FMA:                return visitFMA(N);
1413   case ISD::FDIV:               return visitFDIV(N);
1414   case ISD::FREM:               return visitFREM(N);
1415   case ISD::FSQRT:              return visitFSQRT(N);
1416   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1417   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1418   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1419   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1420   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1421   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1422   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1423   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1424   case ISD::FNEG:               return visitFNEG(N);
1425   case ISD::FABS:               return visitFABS(N);
1426   case ISD::FFLOOR:             return visitFFLOOR(N);
1427   case ISD::FMINNUM:            return visitFMINNUM(N);
1428   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1429   case ISD::FCEIL:              return visitFCEIL(N);
1430   case ISD::FTRUNC:             return visitFTRUNC(N);
1431   case ISD::BRCOND:             return visitBRCOND(N);
1432   case ISD::BR_CC:              return visitBR_CC(N);
1433   case ISD::LOAD:               return visitLOAD(N);
1434   case ISD::STORE:              return visitSTORE(N);
1435   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1436   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1437   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1438   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1439   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1440   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1441   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1442   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1443   case ISD::MGATHER:            return visitMGATHER(N);
1444   case ISD::MLOAD:              return visitMLOAD(N);
1445   case ISD::MSCATTER:           return visitMSCATTER(N);
1446   case ISD::MSTORE:             return visitMSTORE(N);
1447   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1448   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1449   }
1450   return SDValue();
1451 }
1452
1453 SDValue DAGCombiner::combine(SDNode *N) {
1454   SDValue RV = visit(N);
1455
1456   // If nothing happened, try a target-specific DAG combine.
1457   if (!RV.getNode()) {
1458     assert(N->getOpcode() != ISD::DELETED_NODE &&
1459            "Node was deleted but visit returned NULL!");
1460
1461     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1462         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1463
1464       // Expose the DAG combiner to the target combiner impls.
1465       TargetLowering::DAGCombinerInfo
1466         DagCombineInfo(DAG, Level, false, this);
1467
1468       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1469     }
1470   }
1471
1472   // If nothing happened still, try promoting the operation.
1473   if (!RV.getNode()) {
1474     switch (N->getOpcode()) {
1475     default: break;
1476     case ISD::ADD:
1477     case ISD::SUB:
1478     case ISD::MUL:
1479     case ISD::AND:
1480     case ISD::OR:
1481     case ISD::XOR:
1482       RV = PromoteIntBinOp(SDValue(N, 0));
1483       break;
1484     case ISD::SHL:
1485     case ISD::SRA:
1486     case ISD::SRL:
1487       RV = PromoteIntShiftOp(SDValue(N, 0));
1488       break;
1489     case ISD::SIGN_EXTEND:
1490     case ISD::ZERO_EXTEND:
1491     case ISD::ANY_EXTEND:
1492       RV = PromoteExtend(SDValue(N, 0));
1493       break;
1494     case ISD::LOAD:
1495       if (PromoteLoad(SDValue(N, 0)))
1496         RV = SDValue(N, 0);
1497       break;
1498     }
1499   }
1500
1501   // If N is a commutative binary node, try commuting it to enable more
1502   // sdisel CSE.
1503   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1504       N->getNumValues() == 1) {
1505     SDValue N0 = N->getOperand(0);
1506     SDValue N1 = N->getOperand(1);
1507
1508     // Constant operands are canonicalized to RHS.
1509     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1510       SDValue Ops[] = {N1, N0};
1511       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1512                                             N->getFlags());
1513       if (CSENode)
1514         return SDValue(CSENode, 0);
1515     }
1516   }
1517
1518   return RV;
1519 }
1520
1521 /// Given a node, return its input chain if it has one, otherwise return a null
1522 /// sd operand.
1523 static SDValue getInputChainForNode(SDNode *N) {
1524   if (unsigned NumOps = N->getNumOperands()) {
1525     if (N->getOperand(0).getValueType() == MVT::Other)
1526       return N->getOperand(0);
1527     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1528       return N->getOperand(NumOps-1);
1529     for (unsigned i = 1; i < NumOps-1; ++i)
1530       if (N->getOperand(i).getValueType() == MVT::Other)
1531         return N->getOperand(i);
1532   }
1533   return SDValue();
1534 }
1535
1536 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1537   // If N has two operands, where one has an input chain equal to the other,
1538   // the 'other' chain is redundant.
1539   if (N->getNumOperands() == 2) {
1540     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1541       return N->getOperand(0);
1542     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1543       return N->getOperand(1);
1544   }
1545
1546   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1547   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1548   SmallPtrSet<SDNode*, 16> SeenOps;
1549   bool Changed = false;             // If we should replace this token factor.
1550
1551   // Start out with this token factor.
1552   TFs.push_back(N);
1553
1554   // Iterate through token factors.  The TFs grows when new token factors are
1555   // encountered.
1556   for (unsigned i = 0; i < TFs.size(); ++i) {
1557     SDNode *TF = TFs[i];
1558
1559     // Check each of the operands.
1560     for (const SDValue &Op : TF->op_values()) {
1561
1562       switch (Op.getOpcode()) {
1563       case ISD::EntryToken:
1564         // Entry tokens don't need to be added to the list. They are
1565         // redundant.
1566         Changed = true;
1567         break;
1568
1569       case ISD::TokenFactor:
1570         if (Op.hasOneUse() &&
1571             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1572           // Queue up for processing.
1573           TFs.push_back(Op.getNode());
1574           // Clean up in case the token factor is removed.
1575           AddToWorklist(Op.getNode());
1576           Changed = true;
1577           break;
1578         }
1579         // Fall thru
1580
1581       default:
1582         // Only add if it isn't already in the list.
1583         if (SeenOps.insert(Op.getNode()).second)
1584           Ops.push_back(Op);
1585         else
1586           Changed = true;
1587         break;
1588       }
1589     }
1590   }
1591
1592   SDValue Result;
1593
1594   // If we've changed things around then replace token factor.
1595   if (Changed) {
1596     if (Ops.empty()) {
1597       // The entry token is the only possible outcome.
1598       Result = DAG.getEntryNode();
1599     } else {
1600       // New and improved token factor.
1601       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1602     }
1603
1604     // Add users to worklist if AA is enabled, since it may introduce
1605     // a lot of new chained token factors while removing memory deps.
1606     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1607       : DAG.getSubtarget().useAA();
1608     return CombineTo(N, Result, UseAA /*add to worklist*/);
1609   }
1610
1611   return Result;
1612 }
1613
1614 /// MERGE_VALUES can always be eliminated.
1615 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1616   WorklistRemover DeadNodes(*this);
1617   // Replacing results may cause a different MERGE_VALUES to suddenly
1618   // be CSE'd with N, and carry its uses with it. Iterate until no
1619   // uses remain, to ensure that the node can be safely deleted.
1620   // First add the users of this node to the work list so that they
1621   // can be tried again once they have new operands.
1622   AddUsersToWorklist(N);
1623   do {
1624     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1625       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1626   } while (!N->use_empty());
1627   deleteAndRecombine(N);
1628   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1629 }
1630
1631 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1632 /// ContantSDNode pointer else nullptr.
1633 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1634   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1635   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1636 }
1637
1638 SDValue DAGCombiner::visitADD(SDNode *N) {
1639   SDValue N0 = N->getOperand(0);
1640   SDValue N1 = N->getOperand(1);
1641   EVT VT = N0.getValueType();
1642
1643   // fold vector ops
1644   if (VT.isVector()) {
1645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1646       return FoldedVOp;
1647
1648     // fold (add x, 0) -> x, vector edition
1649     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1650       return N0;
1651     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1652       return N1;
1653   }
1654
1655   // fold (add x, undef) -> undef
1656   if (N0.getOpcode() == ISD::UNDEF)
1657     return N0;
1658   if (N1.getOpcode() == ISD::UNDEF)
1659     return N1;
1660   // fold (add c1, c2) -> c1+c2
1661   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1662   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1663   if (N0C && N1C)
1664     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1665   // canonicalize constant to RHS
1666   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1667      !isConstantIntBuildVectorOrConstantInt(N1))
1668     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1669   // fold (add x, 0) -> x
1670   if (isNullConstant(N1))
1671     return N0;
1672   // fold (add Sym, c) -> Sym+c
1673   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1674     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1675         GA->getOpcode() == ISD::GlobalAddress)
1676       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1677                                   GA->getOffset() +
1678                                     (uint64_t)N1C->getSExtValue());
1679   // fold ((c1-A)+c2) -> (c1+c2)-A
1680   if (N1C && N0.getOpcode() == ISD::SUB)
1681     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1682       SDLoc DL(N);
1683       return DAG.getNode(ISD::SUB, DL, VT,
1684                          DAG.getConstant(N1C->getAPIntValue()+
1685                                          N0C->getAPIntValue(), DL, VT),
1686                          N0.getOperand(1));
1687     }
1688   // reassociate add
1689   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1690     return RADD;
1691   // fold ((0-A) + B) -> B-A
1692   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1694   // fold (A + (0-B)) -> A-B
1695   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1696     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1697   // fold (A+(B-A)) -> B
1698   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1699     return N1.getOperand(0);
1700   // fold ((B-A)+A) -> B
1701   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1702     return N0.getOperand(0);
1703   // fold (A+(B-(A+C))) to (B-C)
1704   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1705       N0 == N1.getOperand(1).getOperand(0))
1706     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1707                        N1.getOperand(1).getOperand(1));
1708   // fold (A+(B-(C+A))) to (B-C)
1709   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1710       N0 == N1.getOperand(1).getOperand(1))
1711     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1712                        N1.getOperand(1).getOperand(0));
1713   // fold (A+((B-A)+or-C)) to (B+or-C)
1714   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1715       N1.getOperand(0).getOpcode() == ISD::SUB &&
1716       N0 == N1.getOperand(0).getOperand(1))
1717     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1718                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1719
1720   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1721   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1722     SDValue N00 = N0.getOperand(0);
1723     SDValue N01 = N0.getOperand(1);
1724     SDValue N10 = N1.getOperand(0);
1725     SDValue N11 = N1.getOperand(1);
1726
1727     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1728       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1729                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1730                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1731   }
1732
1733   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1734     return SDValue(N, 0);
1735
1736   // fold (a+b) -> (a|b) iff a and b share no bits.
1737   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1738       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1739     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1740
1741   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1742   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1743       isNullConstant(N1.getOperand(0).getOperand(0)))
1744     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1745                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1746                                    N1.getOperand(0).getOperand(1),
1747                                    N1.getOperand(1)));
1748   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1749       isNullConstant(N0.getOperand(0).getOperand(0)))
1750     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1751                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1752                                    N0.getOperand(0).getOperand(1),
1753                                    N0.getOperand(1)));
1754
1755   if (N1.getOpcode() == ISD::AND) {
1756     SDValue AndOp0 = N1.getOperand(0);
1757     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1758     unsigned DestBits = VT.getScalarType().getSizeInBits();
1759
1760     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1761     // and similar xforms where the inner op is either ~0 or 0.
1762     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1763       SDLoc DL(N);
1764       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1765     }
1766   }
1767
1768   // add (sext i1), X -> sub X, (zext i1)
1769   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1770       N0.getOperand(0).getValueType() == MVT::i1 &&
1771       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1772     SDLoc DL(N);
1773     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1774     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1775   }
1776
1777   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1778   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1779     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1780     if (TN->getVT() == MVT::i1) {
1781       SDLoc DL(N);
1782       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1783                                  DAG.getConstant(1, DL, VT));
1784       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1785     }
1786   }
1787
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitADDC(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   EVT VT = N0.getValueType();
1795
1796   // If the flag result is dead, turn this into an ADD.
1797   if (!N->hasAnyUseOfValue(1))
1798     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1799                      DAG.getNode(ISD::CARRY_FALSE,
1800                                  SDLoc(N), MVT::Glue));
1801
1802   // canonicalize constant to RHS.
1803   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1804   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805   if (N0C && !N1C)
1806     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1807
1808   // fold (addc x, 0) -> x + no carry out
1809   if (isNullConstant(N1))
1810     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1811                                         SDLoc(N), MVT::Glue));
1812
1813   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1814   APInt LHSZero, LHSOne;
1815   APInt RHSZero, RHSOne;
1816   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1817
1818   if (LHSZero.getBoolValue()) {
1819     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1820
1821     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1822     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1823     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1824       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1825                        DAG.getNode(ISD::CARRY_FALSE,
1826                                    SDLoc(N), MVT::Glue));
1827   }
1828
1829   return SDValue();
1830 }
1831
1832 SDValue DAGCombiner::visitADDE(SDNode *N) {
1833   SDValue N0 = N->getOperand(0);
1834   SDValue N1 = N->getOperand(1);
1835   SDValue CarryIn = N->getOperand(2);
1836
1837   // canonicalize constant to RHS
1838   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1839   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1840   if (N0C && !N1C)
1841     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1842                        N1, N0, CarryIn);
1843
1844   // fold (adde x, y, false) -> (addc x, y)
1845   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1846     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1847
1848   return SDValue();
1849 }
1850
1851 // Since it may not be valid to emit a fold to zero for vector initializers
1852 // check if we can before folding.
1853 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1854                              SelectionDAG &DAG,
1855                              bool LegalOperations, bool LegalTypes) {
1856   if (!VT.isVector())
1857     return DAG.getConstant(0, DL, VT);
1858   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1859     return DAG.getConstant(0, DL, VT);
1860   return SDValue();
1861 }
1862
1863 SDValue DAGCombiner::visitSUB(SDNode *N) {
1864   SDValue N0 = N->getOperand(0);
1865   SDValue N1 = N->getOperand(1);
1866   EVT VT = N0.getValueType();
1867
1868   // fold vector ops
1869   if (VT.isVector()) {
1870     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1871       return FoldedVOp;
1872
1873     // fold (sub x, 0) -> x, vector edition
1874     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1875       return N0;
1876   }
1877
1878   // fold (sub x, x) -> 0
1879   // FIXME: Refactor this and xor and other similar operations together.
1880   if (N0 == N1)
1881     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1882   // fold (sub c1, c2) -> c1-c2
1883   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1884   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1885   if (N0C && N1C)
1886     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1887   // fold (sub x, c) -> (add x, -c)
1888   if (N1C) {
1889     SDLoc DL(N);
1890     return DAG.getNode(ISD::ADD, DL, VT, N0,
1891                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1892   }
1893   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1894   if (isAllOnesConstant(N0))
1895     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1896   // fold A-(A-B) -> B
1897   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1898     return N1.getOperand(1);
1899   // fold (A+B)-A -> B
1900   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1901     return N0.getOperand(1);
1902   // fold (A+B)-B -> A
1903   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1904     return N0.getOperand(0);
1905   // fold C2-(A+C1) -> (C2-C1)-A
1906   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1907     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1908   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1909     SDLoc DL(N);
1910     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1911                                    DL, VT);
1912     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1913                        N1.getOperand(0));
1914   }
1915   // fold ((A+(B+or-C))-B) -> A+or-C
1916   if (N0.getOpcode() == ISD::ADD &&
1917       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1918        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1919       N0.getOperand(1).getOperand(0) == N1)
1920     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1921                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1922   // fold ((A+(C+B))-B) -> A+C
1923   if (N0.getOpcode() == ISD::ADD &&
1924       N0.getOperand(1).getOpcode() == ISD::ADD &&
1925       N0.getOperand(1).getOperand(1) == N1)
1926     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1927                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1928   // fold ((A-(B-C))-C) -> A-B
1929   if (N0.getOpcode() == ISD::SUB &&
1930       N0.getOperand(1).getOpcode() == ISD::SUB &&
1931       N0.getOperand(1).getOperand(1) == N1)
1932     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1933                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1934
1935   // If either operand of a sub is undef, the result is undef
1936   if (N0.getOpcode() == ISD::UNDEF)
1937     return N0;
1938   if (N1.getOpcode() == ISD::UNDEF)
1939     return N1;
1940
1941   // If the relocation model supports it, consider symbol offsets.
1942   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1943     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1944       // fold (sub Sym, c) -> Sym-c
1945       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1946         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1947                                     GA->getOffset() -
1948                                       (uint64_t)N1C->getSExtValue());
1949       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1950       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1951         if (GA->getGlobal() == GB->getGlobal())
1952           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1953                                  SDLoc(N), VT);
1954     }
1955
1956   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1957   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1958     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1959     if (TN->getVT() == MVT::i1) {
1960       SDLoc DL(N);
1961       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1962                                  DAG.getConstant(1, DL, VT));
1963       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1964     }
1965   }
1966
1967   return SDValue();
1968 }
1969
1970 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1971   SDValue N0 = N->getOperand(0);
1972   SDValue N1 = N->getOperand(1);
1973   EVT VT = N0.getValueType();
1974   SDLoc DL(N);
1975
1976   // If the flag result is dead, turn this into an SUB.
1977   if (!N->hasAnyUseOfValue(1))
1978     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1979                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1980
1981   // fold (subc x, x) -> 0 + no borrow
1982   if (N0 == N1)
1983     return CombineTo(N, DAG.getConstant(0, DL, VT),
1984                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1985
1986   // fold (subc x, 0) -> x + no borrow
1987   if (isNullConstant(N1))
1988     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1989
1990   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1991   if (isAllOnesConstant(N0))
1992     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1993                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1994
1995   return SDValue();
1996 }
1997
1998 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1999   SDValue N0 = N->getOperand(0);
2000   SDValue N1 = N->getOperand(1);
2001   SDValue CarryIn = N->getOperand(2);
2002
2003   // fold (sube x, y, false) -> (subc x, y)
2004   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2005     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2006
2007   return SDValue();
2008 }
2009
2010 SDValue DAGCombiner::visitMUL(SDNode *N) {
2011   SDValue N0 = N->getOperand(0);
2012   SDValue N1 = N->getOperand(1);
2013   EVT VT = N0.getValueType();
2014
2015   // fold (mul x, undef) -> 0
2016   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2017     return DAG.getConstant(0, SDLoc(N), VT);
2018
2019   bool N0IsConst = false;
2020   bool N1IsConst = false;
2021   bool N1IsOpaqueConst = false;
2022   bool N0IsOpaqueConst = false;
2023   APInt ConstValue0, ConstValue1;
2024   // fold vector ops
2025   if (VT.isVector()) {
2026     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2027       return FoldedVOp;
2028
2029     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2030     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2031   } else {
2032     N0IsConst = isa<ConstantSDNode>(N0);
2033     if (N0IsConst) {
2034       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2035       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2036     }
2037     N1IsConst = isa<ConstantSDNode>(N1);
2038     if (N1IsConst) {
2039       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2040       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2041     }
2042   }
2043
2044   // fold (mul c1, c2) -> c1*c2
2045   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2046     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2047                                       N0.getNode(), N1.getNode());
2048
2049   // canonicalize constant to RHS (vector doesn't have to splat)
2050   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2051      !isConstantIntBuildVectorOrConstantInt(N1))
2052     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2053   // fold (mul x, 0) -> 0
2054   if (N1IsConst && ConstValue1 == 0)
2055     return N1;
2056   // We require a splat of the entire scalar bit width for non-contiguous
2057   // bit patterns.
2058   bool IsFullSplat =
2059     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2060   // fold (mul x, 1) -> x
2061   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2062     return N0;
2063   // fold (mul x, -1) -> 0-x
2064   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2065     SDLoc DL(N);
2066     return DAG.getNode(ISD::SUB, DL, VT,
2067                        DAG.getConstant(0, DL, VT), N0);
2068   }
2069   // fold (mul x, (1 << c)) -> x << c
2070   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2071       IsFullSplat) {
2072     SDLoc DL(N);
2073     return DAG.getNode(ISD::SHL, DL, VT, N0,
2074                        DAG.getConstant(ConstValue1.logBase2(), DL,
2075                                        getShiftAmountTy(N0.getValueType())));
2076   }
2077   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2078   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2079       IsFullSplat) {
2080     unsigned Log2Val = (-ConstValue1).logBase2();
2081     SDLoc DL(N);
2082     // FIXME: If the input is something that is easily negated (e.g. a
2083     // single-use add), we should put the negate there.
2084     return DAG.getNode(ISD::SUB, DL, VT,
2085                        DAG.getConstant(0, DL, VT),
2086                        DAG.getNode(ISD::SHL, DL, VT, N0,
2087                             DAG.getConstant(Log2Val, DL,
2088                                       getShiftAmountTy(N0.getValueType()))));
2089   }
2090
2091   APInt Val;
2092   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2093   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2094       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2095                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2096     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2097                              N1, N0.getOperand(1));
2098     AddToWorklist(C3.getNode());
2099     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2100                        N0.getOperand(0), C3);
2101   }
2102
2103   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2104   // use.
2105   {
2106     SDValue Sh(nullptr,0), Y(nullptr,0);
2107     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2108     if (N0.getOpcode() == ISD::SHL &&
2109         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2110                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2111         N0.getNode()->hasOneUse()) {
2112       Sh = N0; Y = N1;
2113     } else if (N1.getOpcode() == ISD::SHL &&
2114                isa<ConstantSDNode>(N1.getOperand(1)) &&
2115                N1.getNode()->hasOneUse()) {
2116       Sh = N1; Y = N0;
2117     }
2118
2119     if (Sh.getNode()) {
2120       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2121                                 Sh.getOperand(0), Y);
2122       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2123                          Mul, Sh.getOperand(1));
2124     }
2125   }
2126
2127   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2128   if (isConstantIntBuildVectorOrConstantInt(N1) &&
2129       N0.getOpcode() == ISD::ADD &&
2130       isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2131       isMulAddWithConstProfitable(N, N0, N1))
2132       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2133                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2134                                      N0.getOperand(0), N1),
2135                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2136                                      N0.getOperand(1), N1));
2137
2138   // reassociate mul
2139   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2140     return RMUL;
2141
2142   return SDValue();
2143 }
2144
2145 /// Return true if divmod libcall is available.
2146 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2147                                      const TargetLowering &TLI) {
2148   RTLIB::Libcall LC;
2149   switch (Node->getSimpleValueType(0).SimpleTy) {
2150   default: return false; // No libcall for vector types.
2151   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2152   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2153   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2154   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2155   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2156   }
2157
2158   return TLI.getLibcallName(LC) != nullptr;
2159 }
2160
2161 /// Issue divrem if both quotient and remainder are needed.
2162 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2163   if (Node->use_empty())
2164     return SDValue(); // This is a dead node, leave it alone.
2165
2166   EVT VT = Node->getValueType(0);
2167   if (!TLI.isTypeLegal(VT))
2168     return SDValue();
2169
2170   unsigned Opcode = Node->getOpcode();
2171   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2172
2173   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2174   // If DIVREM is going to get expanded into a libcall,
2175   // but there is no libcall available, then don't combine.
2176   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2177       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2178     return SDValue();
2179
2180   // If div is legal, it's better to do the normal expansion
2181   unsigned OtherOpcode = 0;
2182   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2183     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2184     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2185       return SDValue();
2186   } else {
2187     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2188     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2189       return SDValue();
2190   }
2191
2192   SDValue Op0 = Node->getOperand(0);
2193   SDValue Op1 = Node->getOperand(1);
2194   SDValue combined;
2195   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2196          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2197     SDNode *User = *UI;
2198     if (User == Node || User->use_empty())
2199       continue;
2200     // Convert the other matching node(s), too;
2201     // otherwise, the DIVREM may get target-legalized into something
2202     // target-specific that we won't be able to recognize.
2203     unsigned UserOpc = User->getOpcode();
2204     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2205         User->getOperand(0) == Op0 &&
2206         User->getOperand(1) == Op1) {
2207       if (!combined) {
2208         if (UserOpc == OtherOpcode) {
2209           SDVTList VTs = DAG.getVTList(VT, VT);
2210           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2211         } else if (UserOpc == DivRemOpc) {
2212           combined = SDValue(User, 0);
2213         } else {
2214           assert(UserOpc == Opcode);
2215           continue;
2216         }
2217       }
2218       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2219         CombineTo(User, combined);
2220       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2221         CombineTo(User, combined.getValue(1));
2222     }
2223   }
2224   return combined;
2225 }
2226
2227 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2228   SDValue N0 = N->getOperand(0);
2229   SDValue N1 = N->getOperand(1);
2230   EVT VT = N->getValueType(0);
2231
2232   // fold vector ops
2233   if (VT.isVector())
2234     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2235       return FoldedVOp;
2236
2237   SDLoc DL(N);
2238
2239   // fold (sdiv c1, c2) -> c1/c2
2240   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2241   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2242   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2243     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2244   // fold (sdiv X, 1) -> X
2245   if (N1C && N1C->isOne())
2246     return N0;
2247   // fold (sdiv X, -1) -> 0-X
2248   if (N1C && N1C->isAllOnesValue())
2249     return DAG.getNode(ISD::SUB, DL, VT,
2250                        DAG.getConstant(0, DL, VT), N0);
2251
2252   // If we know the sign bits of both operands are zero, strength reduce to a
2253   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2254   if (!VT.isVector()) {
2255     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2256       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2257   }
2258
2259   // fold (sdiv X, pow2) -> simple ops after legalize
2260   // FIXME: We check for the exact bit here because the generic lowering gives
2261   // better results in that case. The target-specific lowering should learn how
2262   // to handle exact sdivs efficiently.
2263   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2264       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2265       (N1C->getAPIntValue().isPowerOf2() ||
2266        (-N1C->getAPIntValue()).isPowerOf2())) {
2267     // Target-specific implementation of sdiv x, pow2.
2268     if (SDValue Res = BuildSDIVPow2(N))
2269       return Res;
2270
2271     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2272
2273     // Splat the sign bit into the register
2274     SDValue SGN =
2275         DAG.getNode(ISD::SRA, DL, VT, N0,
2276                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2277                                     getShiftAmountTy(N0.getValueType())));
2278     AddToWorklist(SGN.getNode());
2279
2280     // Add (N0 < 0) ? abs2 - 1 : 0;
2281     SDValue SRL =
2282         DAG.getNode(ISD::SRL, DL, VT, SGN,
2283                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2284                                     getShiftAmountTy(SGN.getValueType())));
2285     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2286     AddToWorklist(SRL.getNode());
2287     AddToWorklist(ADD.getNode());    // Divide by pow2
2288     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2289                   DAG.getConstant(lg2, DL,
2290                                   getShiftAmountTy(ADD.getValueType())));
2291
2292     // If we're dividing by a positive value, we're done.  Otherwise, we must
2293     // negate the result.
2294     if (N1C->getAPIntValue().isNonNegative())
2295       return SRA;
2296
2297     AddToWorklist(SRA.getNode());
2298     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2299   }
2300
2301   // If integer divide is expensive and we satisfy the requirements, emit an
2302   // alternate sequence.  Targets may check function attributes for size/speed
2303   // trade-offs.
2304   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2305   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2306     if (SDValue Op = BuildSDIV(N))
2307       return Op;
2308
2309   // sdiv, srem -> sdivrem
2310   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2311   // Otherwise, we break the simplification logic in visitREM().
2312   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2313     if (SDValue DivRem = useDivRem(N))
2314         return DivRem;
2315
2316   // undef / X -> 0
2317   if (N0.getOpcode() == ISD::UNDEF)
2318     return DAG.getConstant(0, DL, VT);
2319   // X / undef -> undef
2320   if (N1.getOpcode() == ISD::UNDEF)
2321     return N1;
2322
2323   return SDValue();
2324 }
2325
2326 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2327   SDValue N0 = N->getOperand(0);
2328   SDValue N1 = N->getOperand(1);
2329   EVT VT = N->getValueType(0);
2330
2331   // fold vector ops
2332   if (VT.isVector())
2333     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2334       return FoldedVOp;
2335
2336   SDLoc DL(N);
2337
2338   // fold (udiv c1, c2) -> c1/c2
2339   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2340   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2341   if (N0C && N1C)
2342     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2343                                                     N0C, N1C))
2344       return Folded;
2345   // fold (udiv x, (1 << c)) -> x >>u c
2346   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2347     return DAG.getNode(ISD::SRL, DL, VT, N0,
2348                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2349                                        getShiftAmountTy(N0.getValueType())));
2350
2351   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2352   if (N1.getOpcode() == ISD::SHL) {
2353     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2354       if (SHC->getAPIntValue().isPowerOf2()) {
2355         EVT ADDVT = N1.getOperand(1).getValueType();
2356         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2357                                   N1.getOperand(1),
2358                                   DAG.getConstant(SHC->getAPIntValue()
2359                                                                   .logBase2(),
2360                                                   DL, ADDVT));
2361         AddToWorklist(Add.getNode());
2362         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2363       }
2364     }
2365   }
2366
2367   // fold (udiv x, c) -> alternate
2368   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2369   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2370     if (SDValue Op = BuildUDIV(N))
2371       return Op;
2372
2373   // sdiv, srem -> sdivrem
2374   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2375   // Otherwise, we break the simplification logic in visitREM().
2376   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2377     if (SDValue DivRem = useDivRem(N))
2378         return DivRem;
2379
2380   // undef / X -> 0
2381   if (N0.getOpcode() == ISD::UNDEF)
2382     return DAG.getConstant(0, DL, VT);
2383   // X / undef -> undef
2384   if (N1.getOpcode() == ISD::UNDEF)
2385     return N1;
2386
2387   return SDValue();
2388 }
2389
2390 // handles ISD::SREM and ISD::UREM
2391 SDValue DAGCombiner::visitREM(SDNode *N) {
2392   unsigned Opcode = N->getOpcode();
2393   SDValue N0 = N->getOperand(0);
2394   SDValue N1 = N->getOperand(1);
2395   EVT VT = N->getValueType(0);
2396   bool isSigned = (Opcode == ISD::SREM);
2397   SDLoc DL(N);
2398
2399   // fold (rem c1, c2) -> c1%c2
2400   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2401   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2402   if (N0C && N1C)
2403     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2404       return Folded;
2405
2406   if (isSigned) {
2407     // If we know the sign bits of both operands are zero, strength reduce to a
2408     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2409     if (!VT.isVector()) {
2410       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2411         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2412     }
2413   } else {
2414     // fold (urem x, pow2) -> (and x, pow2-1)
2415     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2416         N1C->getAPIntValue().isPowerOf2()) {
2417       return DAG.getNode(ISD::AND, DL, VT, N0,
2418                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2419     }
2420     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2421     if (N1.getOpcode() == ISD::SHL) {
2422       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2423         if (SHC->getAPIntValue().isPowerOf2()) {
2424           SDValue Add =
2425             DAG.getNode(ISD::ADD, DL, VT, N1,
2426                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2427                                  VT));
2428           AddToWorklist(Add.getNode());
2429           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2430         }
2431       }
2432     }
2433   }
2434
2435   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2436
2437   // If X/C can be simplified by the division-by-constant logic, lower
2438   // X%C to the equivalent of X-X/C*C.
2439   // To avoid mangling nodes, this simplification requires that the combine()
2440   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2441   // against this by skipping the simplification if isIntDivCheap().  When
2442   // div is not cheap, combine will not return a DIVREM.  Regardless,
2443   // checking cheapness here makes sense since the simplification results in
2444   // fatter code.
2445   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2446     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2447     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2448     AddToWorklist(Div.getNode());
2449     SDValue OptimizedDiv = combine(Div.getNode());
2450     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2451       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2452              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2453       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2454       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2455       AddToWorklist(Mul.getNode());
2456       return Sub;
2457     }
2458   }
2459
2460   // sdiv, srem -> sdivrem
2461   if (SDValue DivRem = useDivRem(N))
2462     return DivRem.getValue(1);
2463
2464   // undef % X -> 0
2465   if (N0.getOpcode() == ISD::UNDEF)
2466     return DAG.getConstant(0, DL, VT);
2467   // X % undef -> undef
2468   if (N1.getOpcode() == ISD::UNDEF)
2469     return N1;
2470
2471   return SDValue();
2472 }
2473
2474 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2475   SDValue N0 = N->getOperand(0);
2476   SDValue N1 = N->getOperand(1);
2477   EVT VT = N->getValueType(0);
2478   SDLoc DL(N);
2479
2480   // fold (mulhs x, 0) -> 0
2481   if (isNullConstant(N1))
2482     return N1;
2483   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2484   if (isOneConstant(N1)) {
2485     SDLoc DL(N);
2486     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2487                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2488                                        DL,
2489                                        getShiftAmountTy(N0.getValueType())));
2490   }
2491   // fold (mulhs x, undef) -> 0
2492   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2493     return DAG.getConstant(0, SDLoc(N), VT);
2494
2495   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2496   // plus a shift.
2497   if (VT.isSimple() && !VT.isVector()) {
2498     MVT Simple = VT.getSimpleVT();
2499     unsigned SimpleSize = Simple.getSizeInBits();
2500     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2501     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2502       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2503       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2504       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2505       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2506             DAG.getConstant(SimpleSize, DL,
2507                             getShiftAmountTy(N1.getValueType())));
2508       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2509     }
2510   }
2511
2512   return SDValue();
2513 }
2514
2515 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2516   SDValue N0 = N->getOperand(0);
2517   SDValue N1 = N->getOperand(1);
2518   EVT VT = N->getValueType(0);
2519   SDLoc DL(N);
2520
2521   // fold (mulhu x, 0) -> 0
2522   if (isNullConstant(N1))
2523     return N1;
2524   // fold (mulhu x, 1) -> 0
2525   if (isOneConstant(N1))
2526     return DAG.getConstant(0, DL, N0.getValueType());
2527   // fold (mulhu x, undef) -> 0
2528   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2529     return DAG.getConstant(0, DL, VT);
2530
2531   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2532   // plus a shift.
2533   if (VT.isSimple() && !VT.isVector()) {
2534     MVT Simple = VT.getSimpleVT();
2535     unsigned SimpleSize = Simple.getSizeInBits();
2536     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2537     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2538       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2539       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2540       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2541       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2542             DAG.getConstant(SimpleSize, DL,
2543                             getShiftAmountTy(N1.getValueType())));
2544       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2545     }
2546   }
2547
2548   return SDValue();
2549 }
2550
2551 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2552 /// give the opcodes for the two computations that are being performed. Return
2553 /// true if a simplification was made.
2554 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2555                                                 unsigned HiOp) {
2556   // If the high half is not needed, just compute the low half.
2557   bool HiExists = N->hasAnyUseOfValue(1);
2558   if (!HiExists &&
2559       (!LegalOperations ||
2560        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2561     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2562     return CombineTo(N, Res, Res);
2563   }
2564
2565   // If the low half is not needed, just compute the high half.
2566   bool LoExists = N->hasAnyUseOfValue(0);
2567   if (!LoExists &&
2568       (!LegalOperations ||
2569        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2570     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2571     return CombineTo(N, Res, Res);
2572   }
2573
2574   // If both halves are used, return as it is.
2575   if (LoExists && HiExists)
2576     return SDValue();
2577
2578   // If the two computed results can be simplified separately, separate them.
2579   if (LoExists) {
2580     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2581     AddToWorklist(Lo.getNode());
2582     SDValue LoOpt = combine(Lo.getNode());
2583     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2584         (!LegalOperations ||
2585          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2586       return CombineTo(N, LoOpt, LoOpt);
2587   }
2588
2589   if (HiExists) {
2590     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2591     AddToWorklist(Hi.getNode());
2592     SDValue HiOpt = combine(Hi.getNode());
2593     if (HiOpt.getNode() && HiOpt != Hi &&
2594         (!LegalOperations ||
2595          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2596       return CombineTo(N, HiOpt, HiOpt);
2597   }
2598
2599   return SDValue();
2600 }
2601
2602 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2603   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2604     return Res;
2605
2606   EVT VT = N->getValueType(0);
2607   SDLoc DL(N);
2608
2609   // If the type is twice as wide is legal, transform the mulhu to a wider
2610   // multiply plus a shift.
2611   if (VT.isSimple() && !VT.isVector()) {
2612     MVT Simple = VT.getSimpleVT();
2613     unsigned SimpleSize = Simple.getSizeInBits();
2614     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2615     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2616       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2617       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2618       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2619       // Compute the high part as N1.
2620       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2621             DAG.getConstant(SimpleSize, DL,
2622                             getShiftAmountTy(Lo.getValueType())));
2623       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2624       // Compute the low part as N0.
2625       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2626       return CombineTo(N, Lo, Hi);
2627     }
2628   }
2629
2630   return SDValue();
2631 }
2632
2633 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2634   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2635     return Res;
2636
2637   EVT VT = N->getValueType(0);
2638   SDLoc DL(N);
2639
2640   // If the type is twice as wide is legal, transform the mulhu to a wider
2641   // multiply plus a shift.
2642   if (VT.isSimple() && !VT.isVector()) {
2643     MVT Simple = VT.getSimpleVT();
2644     unsigned SimpleSize = Simple.getSizeInBits();
2645     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2646     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2647       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2648       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2649       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2650       // Compute the high part as N1.
2651       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2652             DAG.getConstant(SimpleSize, DL,
2653                             getShiftAmountTy(Lo.getValueType())));
2654       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2655       // Compute the low part as N0.
2656       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2657       return CombineTo(N, Lo, Hi);
2658     }
2659   }
2660
2661   return SDValue();
2662 }
2663
2664 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2665   // (smulo x, 2) -> (saddo x, x)
2666   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2667     if (C2->getAPIntValue() == 2)
2668       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2669                          N->getOperand(0), N->getOperand(0));
2670
2671   return SDValue();
2672 }
2673
2674 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2675   // (umulo x, 2) -> (uaddo x, x)
2676   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2677     if (C2->getAPIntValue() == 2)
2678       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2679                          N->getOperand(0), N->getOperand(0));
2680
2681   return SDValue();
2682 }
2683
2684 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2685   SDValue N0 = N->getOperand(0);
2686   SDValue N1 = N->getOperand(1);
2687   EVT VT = N0.getValueType();
2688
2689   // fold vector ops
2690   if (VT.isVector())
2691     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2692       return FoldedVOp;
2693
2694   // fold (add c1, c2) -> c1+c2
2695   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2696   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2697   if (N0C && N1C)
2698     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2699
2700   // canonicalize constant to RHS
2701   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2702      !isConstantIntBuildVectorOrConstantInt(N1))
2703     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2704
2705   return SDValue();
2706 }
2707
2708 /// If this is a binary operator with two operands of the same opcode, try to
2709 /// simplify it.
2710 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2711   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2712   EVT VT = N0.getValueType();
2713   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2714
2715   // Bail early if none of these transforms apply.
2716   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2717
2718   // For each of OP in AND/OR/XOR:
2719   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2720   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2721   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2722   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2723   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2724   //
2725   // do not sink logical op inside of a vector extend, since it may combine
2726   // into a vsetcc.
2727   EVT Op0VT = N0.getOperand(0).getValueType();
2728   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2729        N0.getOpcode() == ISD::SIGN_EXTEND ||
2730        N0.getOpcode() == ISD::BSWAP ||
2731        // Avoid infinite looping with PromoteIntBinOp.
2732        (N0.getOpcode() == ISD::ANY_EXTEND &&
2733         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2734        (N0.getOpcode() == ISD::TRUNCATE &&
2735         (!TLI.isZExtFree(VT, Op0VT) ||
2736          !TLI.isTruncateFree(Op0VT, VT)) &&
2737         TLI.isTypeLegal(Op0VT))) &&
2738       !VT.isVector() &&
2739       Op0VT == N1.getOperand(0).getValueType() &&
2740       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2741     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2742                                  N0.getOperand(0).getValueType(),
2743                                  N0.getOperand(0), N1.getOperand(0));
2744     AddToWorklist(ORNode.getNode());
2745     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2746   }
2747
2748   // For each of OP in SHL/SRL/SRA/AND...
2749   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2750   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2751   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2752   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2753        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2754       N0.getOperand(1) == N1.getOperand(1)) {
2755     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2756                                  N0.getOperand(0).getValueType(),
2757                                  N0.getOperand(0), N1.getOperand(0));
2758     AddToWorklist(ORNode.getNode());
2759     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2760                        ORNode, N0.getOperand(1));
2761   }
2762
2763   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2764   // Only perform this optimization after type legalization and before
2765   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2766   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2767   // we don't want to undo this promotion.
2768   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2769   // on scalars.
2770   if ((N0.getOpcode() == ISD::BITCAST ||
2771        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2772       Level == AfterLegalizeTypes) {
2773     SDValue In0 = N0.getOperand(0);
2774     SDValue In1 = N1.getOperand(0);
2775     EVT In0Ty = In0.getValueType();
2776     EVT In1Ty = In1.getValueType();
2777     SDLoc DL(N);
2778     // If both incoming values are integers, and the original types are the
2779     // same.
2780     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2781       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2782       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2783       AddToWorklist(Op.getNode());
2784       return BC;
2785     }
2786   }
2787
2788   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2789   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2790   // If both shuffles use the same mask, and both shuffle within a single
2791   // vector, then it is worthwhile to move the swizzle after the operation.
2792   // The type-legalizer generates this pattern when loading illegal
2793   // vector types from memory. In many cases this allows additional shuffle
2794   // optimizations.
2795   // There are other cases where moving the shuffle after the xor/and/or
2796   // is profitable even if shuffles don't perform a swizzle.
2797   // If both shuffles use the same mask, and both shuffles have the same first
2798   // or second operand, then it might still be profitable to move the shuffle
2799   // after the xor/and/or operation.
2800   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2801     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2802     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2803
2804     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2805            "Inputs to shuffles are not the same type");
2806
2807     // Check that both shuffles use the same mask. The masks are known to be of
2808     // the same length because the result vector type is the same.
2809     // Check also that shuffles have only one use to avoid introducing extra
2810     // instructions.
2811     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2812         SVN0->getMask().equals(SVN1->getMask())) {
2813       SDValue ShOp = N0->getOperand(1);
2814
2815       // Don't try to fold this node if it requires introducing a
2816       // build vector of all zeros that might be illegal at this stage.
2817       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2818         if (!LegalTypes)
2819           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2820         else
2821           ShOp = SDValue();
2822       }
2823
2824       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2825       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2826       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2827       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2828         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2829                                       N0->getOperand(0), N1->getOperand(0));
2830         AddToWorklist(NewNode.getNode());
2831         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2832                                     &SVN0->getMask()[0]);
2833       }
2834
2835       // Don't try to fold this node if it requires introducing a
2836       // build vector of all zeros that might be illegal at this stage.
2837       ShOp = N0->getOperand(0);
2838       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2839         if (!LegalTypes)
2840           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2841         else
2842           ShOp = SDValue();
2843       }
2844
2845       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2846       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2847       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2848       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2849         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2850                                       N0->getOperand(1), N1->getOperand(1));
2851         AddToWorklist(NewNode.getNode());
2852         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2853                                     &SVN0->getMask()[0]);
2854       }
2855     }
2856   }
2857
2858   return SDValue();
2859 }
2860
2861 /// This contains all DAGCombine rules which reduce two values combined by
2862 /// an And operation to a single value. This makes them reusable in the context
2863 /// of visitSELECT(). Rules involving constants are not included as
2864 /// visitSELECT() already handles those cases.
2865 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2866                                   SDNode *LocReference) {
2867   EVT VT = N1.getValueType();
2868
2869   // fold (and x, undef) -> 0
2870   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2871     return DAG.getConstant(0, SDLoc(LocReference), VT);
2872   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2873   SDValue LL, LR, RL, RR, CC0, CC1;
2874   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2875     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2876     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2877
2878     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2879         LL.getValueType().isInteger()) {
2880       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2881       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2882         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2883                                      LR.getValueType(), LL, RL);
2884         AddToWorklist(ORNode.getNode());
2885         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2886       }
2887       if (isAllOnesConstant(LR)) {
2888         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2889         if (Op1 == ISD::SETEQ) {
2890           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2891                                         LR.getValueType(), LL, RL);
2892           AddToWorklist(ANDNode.getNode());
2893           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2894         }
2895         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2896         if (Op1 == ISD::SETGT) {
2897           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2898                                        LR.getValueType(), LL, RL);
2899           AddToWorklist(ORNode.getNode());
2900           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2901         }
2902       }
2903     }
2904     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2905     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2906         Op0 == Op1 && LL.getValueType().isInteger() &&
2907       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2908                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2909       SDLoc DL(N0);
2910       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2911                                     LL, DAG.getConstant(1, DL,
2912                                                         LL.getValueType()));
2913       AddToWorklist(ADDNode.getNode());
2914       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2915                           DAG.getConstant(2, DL, LL.getValueType()),
2916                           ISD::SETUGE);
2917     }
2918     // canonicalize equivalent to ll == rl
2919     if (LL == RR && LR == RL) {
2920       Op1 = ISD::getSetCCSwappedOperands(Op1);
2921       std::swap(RL, RR);
2922     }
2923     if (LL == RL && LR == RR) {
2924       bool isInteger = LL.getValueType().isInteger();
2925       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2926       if (Result != ISD::SETCC_INVALID &&
2927           (!LegalOperations ||
2928            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2929             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2930         EVT CCVT = getSetCCResultType(LL.getValueType());
2931         if (N0.getValueType() == CCVT ||
2932             (!LegalOperations && N0.getValueType() == MVT::i1))
2933           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2934                               LL, LR, Result);
2935       }
2936     }
2937   }
2938
2939   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2940       VT.getSizeInBits() <= 64) {
2941     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2942       APInt ADDC = ADDI->getAPIntValue();
2943       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2944         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2945         // immediate for an add, but it is legal if its top c2 bits are set,
2946         // transform the ADD so the immediate doesn't need to be materialized
2947         // in a register.
2948         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2949           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2950                                              SRLI->getZExtValue());
2951           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2952             ADDC |= Mask;
2953             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2954               SDLoc DL(N0);
2955               SDValue NewAdd =
2956                 DAG.getNode(ISD::ADD, DL, VT,
2957                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2958               CombineTo(N0.getNode(), NewAdd);
2959               // Return N so it doesn't get rechecked!
2960               return SDValue(LocReference, 0);
2961             }
2962           }
2963         }
2964       }
2965     }
2966   }
2967
2968   return SDValue();
2969 }
2970
2971 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
2972                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
2973                                    bool &NarrowLoad) {
2974   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
2975
2976   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
2977     return false;
2978
2979   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2980   LoadedVT = LoadN->getMemoryVT();
2981
2982   if (ExtVT == LoadedVT &&
2983       (!LegalOperations ||
2984        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
2985     // ZEXTLOAD will match without needing to change the size of the value being
2986     // loaded.
2987     NarrowLoad = false;
2988     return true;
2989   }
2990
2991   // Do not change the width of a volatile load.
2992   if (LoadN->isVolatile())
2993     return false;
2994
2995   // Do not generate loads of non-round integer types since these can
2996   // be expensive (and would be wrong if the type is not byte sized).
2997   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
2998     return false;
2999
3000   if (LegalOperations &&
3001       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3002     return false;
3003
3004   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3005     return false;
3006
3007   NarrowLoad = true;
3008   return true;
3009 }
3010
3011 SDValue DAGCombiner::visitAND(SDNode *N) {
3012   SDValue N0 = N->getOperand(0);
3013   SDValue N1 = N->getOperand(1);
3014   EVT VT = N1.getValueType();
3015
3016   // fold vector ops
3017   if (VT.isVector()) {
3018     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3019       return FoldedVOp;
3020
3021     // fold (and x, 0) -> 0, vector edition
3022     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3023       // do not return N0, because undef node may exist in N0
3024       return DAG.getConstant(
3025           APInt::getNullValue(
3026               N0.getValueType().getScalarType().getSizeInBits()),
3027           SDLoc(N), N0.getValueType());
3028     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3029       // do not return N1, because undef node may exist in N1
3030       return DAG.getConstant(
3031           APInt::getNullValue(
3032               N1.getValueType().getScalarType().getSizeInBits()),
3033           SDLoc(N), N1.getValueType());
3034
3035     // fold (and x, -1) -> x, vector edition
3036     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3037       return N1;
3038     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3039       return N0;
3040   }
3041
3042   // fold (and c1, c2) -> c1&c2
3043   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3044   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3045   if (N0C && N1C && !N1C->isOpaque())
3046     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3047   // canonicalize constant to RHS
3048   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3049      !isConstantIntBuildVectorOrConstantInt(N1))
3050     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3051   // fold (and x, -1) -> x
3052   if (isAllOnesConstant(N1))
3053     return N0;
3054   // if (and x, c) is known to be zero, return 0
3055   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3056   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3057                                    APInt::getAllOnesValue(BitWidth)))
3058     return DAG.getConstant(0, SDLoc(N), VT);
3059   // reassociate and
3060   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3061     return RAND;
3062   // fold (and (or x, C), D) -> D if (C & D) == D
3063   if (N1C && N0.getOpcode() == ISD::OR)
3064     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3065       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3066         return N1;
3067   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3068   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3069     SDValue N0Op0 = N0.getOperand(0);
3070     APInt Mask = ~N1C->getAPIntValue();
3071     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3072     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3073       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3074                                  N0.getValueType(), N0Op0);
3075
3076       // Replace uses of the AND with uses of the Zero extend node.
3077       CombineTo(N, Zext);
3078
3079       // We actually want to replace all uses of the any_extend with the
3080       // zero_extend, to avoid duplicating things.  This will later cause this
3081       // AND to be folded.
3082       CombineTo(N0.getNode(), Zext);
3083       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3084     }
3085   }
3086   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3087   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3088   // already be zero by virtue of the width of the base type of the load.
3089   //
3090   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3091   // more cases.
3092   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3093        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3094       N0.getOpcode() == ISD::LOAD) {
3095     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3096                                          N0 : N0.getOperand(0) );
3097
3098     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3099     // This can be a pure constant or a vector splat, in which case we treat the
3100     // vector as a scalar and use the splat value.
3101     APInt Constant = APInt::getNullValue(1);
3102     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3103       Constant = C->getAPIntValue();
3104     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3105       APInt SplatValue, SplatUndef;
3106       unsigned SplatBitSize;
3107       bool HasAnyUndefs;
3108       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3109                                              SplatBitSize, HasAnyUndefs);
3110       if (IsSplat) {
3111         // Undef bits can contribute to a possible optimisation if set, so
3112         // set them.
3113         SplatValue |= SplatUndef;
3114
3115         // The splat value may be something like "0x00FFFFFF", which means 0 for
3116         // the first vector value and FF for the rest, repeating. We need a mask
3117         // that will apply equally to all members of the vector, so AND all the
3118         // lanes of the constant together.
3119         EVT VT = Vector->getValueType(0);
3120         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3121
3122         // If the splat value has been compressed to a bitlength lower
3123         // than the size of the vector lane, we need to re-expand it to
3124         // the lane size.
3125         if (BitWidth > SplatBitSize)
3126           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3127                SplatBitSize < BitWidth;
3128                SplatBitSize = SplatBitSize * 2)
3129             SplatValue |= SplatValue.shl(SplatBitSize);
3130
3131         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3132         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3133         if (SplatBitSize % BitWidth == 0) {
3134           Constant = APInt::getAllOnesValue(BitWidth);
3135           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3136             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3137         }
3138       }
3139     }
3140
3141     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3142     // actually legal and isn't going to get expanded, else this is a false
3143     // optimisation.
3144     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3145                                                     Load->getValueType(0),
3146                                                     Load->getMemoryVT());
3147
3148     // Resize the constant to the same size as the original memory access before
3149     // extension. If it is still the AllOnesValue then this AND is completely
3150     // unneeded.
3151     Constant =
3152       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3153
3154     bool B;
3155     switch (Load->getExtensionType()) {
3156     default: B = false; break;
3157     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3158     case ISD::ZEXTLOAD:
3159     case ISD::NON_EXTLOAD: B = true; break;
3160     }
3161
3162     if (B && Constant.isAllOnesValue()) {
3163       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3164       // preserve semantics once we get rid of the AND.
3165       SDValue NewLoad(Load, 0);
3166       if (Load->getExtensionType() == ISD::EXTLOAD) {
3167         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3168                               Load->getValueType(0), SDLoc(Load),
3169                               Load->getChain(), Load->getBasePtr(),
3170                               Load->getOffset(), Load->getMemoryVT(),
3171                               Load->getMemOperand());
3172         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3173         if (Load->getNumValues() == 3) {
3174           // PRE/POST_INC loads have 3 values.
3175           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3176                            NewLoad.getValue(2) };
3177           CombineTo(Load, To, 3, true);
3178         } else {
3179           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3180         }
3181       }
3182
3183       // Fold the AND away, taking care not to fold to the old load node if we
3184       // replaced it.
3185       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3186
3187       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3188     }
3189   }
3190
3191   // fold (and (load x), 255) -> (zextload x, i8)
3192   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3193   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3194   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3195               (N0.getOpcode() == ISD::ANY_EXTEND &&
3196                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3197     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3198     LoadSDNode *LN0 = HasAnyExt
3199       ? cast<LoadSDNode>(N0.getOperand(0))
3200       : cast<LoadSDNode>(N0);
3201     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3202         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3203       auto NarrowLoad = false;
3204       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3205       EVT ExtVT, LoadedVT;
3206       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3207                            NarrowLoad)) {
3208         if (!NarrowLoad) {
3209           SDValue NewLoad =
3210             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3211                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3212                            LN0->getMemOperand());
3213           AddToWorklist(N);
3214           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3215           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3216         } else {
3217           EVT PtrType = LN0->getOperand(1).getValueType();
3218
3219           unsigned Alignment = LN0->getAlignment();
3220           SDValue NewPtr = LN0->getBasePtr();
3221
3222           // For big endian targets, we need to add an offset to the pointer
3223           // to load the correct bytes.  For little endian systems, we merely
3224           // need to read fewer bytes from the same pointer.
3225           if (DAG.getDataLayout().isBigEndian()) {
3226             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3227             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3228             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3229             SDLoc DL(LN0);
3230             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3231                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3232             Alignment = MinAlign(Alignment, PtrOff);
3233           }
3234
3235           AddToWorklist(NewPtr.getNode());
3236
3237           SDValue Load =
3238             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3239                            LN0->getChain(), NewPtr,
3240                            LN0->getPointerInfo(),
3241                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3242                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3243           AddToWorklist(N);
3244           CombineTo(LN0, Load, Load.getValue(1));
3245           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3246         }
3247       }
3248     }
3249   }
3250
3251   if (SDValue Combined = visitANDLike(N0, N1, N))
3252     return Combined;
3253
3254   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3255   if (N0.getOpcode() == N1.getOpcode())
3256     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3257       return Tmp;
3258
3259   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3260   // fold (and (sra)) -> (and (srl)) when possible.
3261   if (!VT.isVector() &&
3262       SimplifyDemandedBits(SDValue(N, 0)))
3263     return SDValue(N, 0);
3264
3265   // fold (zext_inreg (extload x)) -> (zextload x)
3266   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3267     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3268     EVT MemVT = LN0->getMemoryVT();
3269     // If we zero all the possible extended bits, then we can turn this into
3270     // a zextload if we are running before legalize or the operation is legal.
3271     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3272     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3273                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3274         ((!LegalOperations && !LN0->isVolatile()) ||
3275          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3276       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3277                                        LN0->getChain(), LN0->getBasePtr(),
3278                                        MemVT, LN0->getMemOperand());
3279       AddToWorklist(N);
3280       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3281       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3282     }
3283   }
3284   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3285   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3286       N0.hasOneUse()) {
3287     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3288     EVT MemVT = LN0->getMemoryVT();
3289     // If we zero all the possible extended bits, then we can turn this into
3290     // a zextload if we are running before legalize or the operation is legal.
3291     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3292     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3293                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3294         ((!LegalOperations && !LN0->isVolatile()) ||
3295          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3296       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3297                                        LN0->getChain(), LN0->getBasePtr(),
3298                                        MemVT, LN0->getMemOperand());
3299       AddToWorklist(N);
3300       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3301       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3302     }
3303   }
3304   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3305   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3306     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3307                                        N0.getOperand(1), false);
3308     if (BSwap.getNode())
3309       return BSwap;
3310   }
3311
3312   return SDValue();
3313 }
3314
3315 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3316 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3317                                         bool DemandHighBits) {
3318   if (!LegalOperations)
3319     return SDValue();
3320
3321   EVT VT = N->getValueType(0);
3322   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3323     return SDValue();
3324   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3325     return SDValue();
3326
3327   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3328   bool LookPassAnd0 = false;
3329   bool LookPassAnd1 = false;
3330   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3331       std::swap(N0, N1);
3332   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3333       std::swap(N0, N1);
3334   if (N0.getOpcode() == ISD::AND) {
3335     if (!N0.getNode()->hasOneUse())
3336       return SDValue();
3337     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3338     if (!N01C || N01C->getZExtValue() != 0xFF00)
3339       return SDValue();
3340     N0 = N0.getOperand(0);
3341     LookPassAnd0 = true;
3342   }
3343
3344   if (N1.getOpcode() == ISD::AND) {
3345     if (!N1.getNode()->hasOneUse())
3346       return SDValue();
3347     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3348     if (!N11C || N11C->getZExtValue() != 0xFF)
3349       return SDValue();
3350     N1 = N1.getOperand(0);
3351     LookPassAnd1 = true;
3352   }
3353
3354   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3355     std::swap(N0, N1);
3356   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3357     return SDValue();
3358   if (!N0.getNode()->hasOneUse() ||
3359       !N1.getNode()->hasOneUse())
3360     return SDValue();
3361
3362   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3363   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3364   if (!N01C || !N11C)
3365     return SDValue();
3366   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3367     return SDValue();
3368
3369   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3370   SDValue N00 = N0->getOperand(0);
3371   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3372     if (!N00.getNode()->hasOneUse())
3373       return SDValue();
3374     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3375     if (!N001C || N001C->getZExtValue() != 0xFF)
3376       return SDValue();
3377     N00 = N00.getOperand(0);
3378     LookPassAnd0 = true;
3379   }
3380
3381   SDValue N10 = N1->getOperand(0);
3382   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3383     if (!N10.getNode()->hasOneUse())
3384       return SDValue();
3385     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3386     if (!N101C || N101C->getZExtValue() != 0xFF00)
3387       return SDValue();
3388     N10 = N10.getOperand(0);
3389     LookPassAnd1 = true;
3390   }
3391
3392   if (N00 != N10)
3393     return SDValue();
3394
3395   // Make sure everything beyond the low halfword gets set to zero since the SRL
3396   // 16 will clear the top bits.
3397   unsigned OpSizeInBits = VT.getSizeInBits();
3398   if (DemandHighBits && OpSizeInBits > 16) {
3399     // If the left-shift isn't masked out then the only way this is a bswap is
3400     // if all bits beyond the low 8 are 0. In that case the entire pattern
3401     // reduces to a left shift anyway: leave it for other parts of the combiner.
3402     if (!LookPassAnd0)
3403       return SDValue();
3404
3405     // However, if the right shift isn't masked out then it might be because
3406     // it's not needed. See if we can spot that too.
3407     if (!LookPassAnd1 &&
3408         !DAG.MaskedValueIsZero(
3409             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3410       return SDValue();
3411   }
3412
3413   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3414   if (OpSizeInBits > 16) {
3415     SDLoc DL(N);
3416     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3417                       DAG.getConstant(OpSizeInBits - 16, DL,
3418                                       getShiftAmountTy(VT)));
3419   }
3420   return Res;
3421 }
3422
3423 /// Return true if the specified node is an element that makes up a 32-bit
3424 /// packed halfword byteswap.
3425 /// ((x & 0x000000ff) << 8) |
3426 /// ((x & 0x0000ff00) >> 8) |
3427 /// ((x & 0x00ff0000) << 8) |
3428 /// ((x & 0xff000000) >> 8)
3429 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3430   if (!N.getNode()->hasOneUse())
3431     return false;
3432
3433   unsigned Opc = N.getOpcode();
3434   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3435     return false;
3436
3437   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3438   if (!N1C)
3439     return false;
3440
3441   unsigned Num;
3442   switch (N1C->getZExtValue()) {
3443   default:
3444     return false;
3445   case 0xFF:       Num = 0; break;
3446   case 0xFF00:     Num = 1; break;
3447   case 0xFF0000:   Num = 2; break;
3448   case 0xFF000000: Num = 3; break;
3449   }
3450
3451   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3452   SDValue N0 = N.getOperand(0);
3453   if (Opc == ISD::AND) {
3454     if (Num == 0 || Num == 2) {
3455       // (x >> 8) & 0xff
3456       // (x >> 8) & 0xff0000
3457       if (N0.getOpcode() != ISD::SRL)
3458         return false;
3459       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3460       if (!C || C->getZExtValue() != 8)
3461         return false;
3462     } else {
3463       // (x << 8) & 0xff00
3464       // (x << 8) & 0xff000000
3465       if (N0.getOpcode() != ISD::SHL)
3466         return false;
3467       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3468       if (!C || C->getZExtValue() != 8)
3469         return false;
3470     }
3471   } else if (Opc == ISD::SHL) {
3472     // (x & 0xff) << 8
3473     // (x & 0xff0000) << 8
3474     if (Num != 0 && Num != 2)
3475       return false;
3476     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3477     if (!C || C->getZExtValue() != 8)
3478       return false;
3479   } else { // Opc == ISD::SRL
3480     // (x & 0xff00) >> 8
3481     // (x & 0xff000000) >> 8
3482     if (Num != 1 && Num != 3)
3483       return false;
3484     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3485     if (!C || C->getZExtValue() != 8)
3486       return false;
3487   }
3488
3489   if (Parts[Num])
3490     return false;
3491
3492   Parts[Num] = N0.getOperand(0).getNode();
3493   return true;
3494 }
3495
3496 /// Match a 32-bit packed halfword bswap. That is
3497 /// ((x & 0x000000ff) << 8) |
3498 /// ((x & 0x0000ff00) >> 8) |
3499 /// ((x & 0x00ff0000) << 8) |
3500 /// ((x & 0xff000000) >> 8)
3501 /// => (rotl (bswap x), 16)
3502 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3503   if (!LegalOperations)
3504     return SDValue();
3505
3506   EVT VT = N->getValueType(0);
3507   if (VT != MVT::i32)
3508     return SDValue();
3509   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3510     return SDValue();
3511
3512   // Look for either
3513   // (or (or (and), (and)), (or (and), (and)))
3514   // (or (or (or (and), (and)), (and)), (and))
3515   if (N0.getOpcode() != ISD::OR)
3516     return SDValue();
3517   SDValue N00 = N0.getOperand(0);
3518   SDValue N01 = N0.getOperand(1);
3519   SDNode *Parts[4] = {};
3520
3521   if (N1.getOpcode() == ISD::OR &&
3522       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3523     // (or (or (and), (and)), (or (and), (and)))
3524     SDValue N000 = N00.getOperand(0);
3525     if (!isBSwapHWordElement(N000, Parts))
3526       return SDValue();
3527
3528     SDValue N001 = N00.getOperand(1);
3529     if (!isBSwapHWordElement(N001, Parts))
3530       return SDValue();
3531     SDValue N010 = N01.getOperand(0);
3532     if (!isBSwapHWordElement(N010, Parts))
3533       return SDValue();
3534     SDValue N011 = N01.getOperand(1);
3535     if (!isBSwapHWordElement(N011, Parts))
3536       return SDValue();
3537   } else {
3538     // (or (or (or (and), (and)), (and)), (and))
3539     if (!isBSwapHWordElement(N1, Parts))
3540       return SDValue();
3541     if (!isBSwapHWordElement(N01, Parts))
3542       return SDValue();
3543     if (N00.getOpcode() != ISD::OR)
3544       return SDValue();
3545     SDValue N000 = N00.getOperand(0);
3546     if (!isBSwapHWordElement(N000, Parts))
3547       return SDValue();
3548     SDValue N001 = N00.getOperand(1);
3549     if (!isBSwapHWordElement(N001, Parts))
3550       return SDValue();
3551   }
3552
3553   // Make sure the parts are all coming from the same node.
3554   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3555     return SDValue();
3556
3557   SDLoc DL(N);
3558   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3559                               SDValue(Parts[0], 0));
3560
3561   // Result of the bswap should be rotated by 16. If it's not legal, then
3562   // do  (x << 16) | (x >> 16).
3563   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3564   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3565     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3566   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3567     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3568   return DAG.getNode(ISD::OR, DL, VT,
3569                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3570                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3571 }
3572
3573 /// This contains all DAGCombine rules which reduce two values combined by
3574 /// an Or operation to a single value \see visitANDLike().
3575 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3576   EVT VT = N1.getValueType();
3577   // fold (or x, undef) -> -1
3578   if (!LegalOperations &&
3579       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3580     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3581     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3582                            SDLoc(LocReference), VT);
3583   }
3584   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3585   SDValue LL, LR, RL, RR, CC0, CC1;
3586   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3587     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3588     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3589
3590     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3591       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3592       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3593       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3594         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3595                                      LR.getValueType(), LL, RL);
3596         AddToWorklist(ORNode.getNode());
3597         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3598       }
3599       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3600       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3601       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3602         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3603                                       LR.getValueType(), LL, RL);
3604         AddToWorklist(ANDNode.getNode());
3605         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3606       }
3607     }
3608     // canonicalize equivalent to ll == rl
3609     if (LL == RR && LR == RL) {
3610       Op1 = ISD::getSetCCSwappedOperands(Op1);
3611       std::swap(RL, RR);
3612     }
3613     if (LL == RL && LR == RR) {
3614       bool isInteger = LL.getValueType().isInteger();
3615       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3616       if (Result != ISD::SETCC_INVALID &&
3617           (!LegalOperations ||
3618            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3619             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3620         EVT CCVT = getSetCCResultType(LL.getValueType());
3621         if (N0.getValueType() == CCVT ||
3622             (!LegalOperations && N0.getValueType() == MVT::i1))
3623           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3624                               LL, LR, Result);
3625       }
3626     }
3627   }
3628
3629   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3630   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3631       // Don't increase # computations.
3632       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3633     // We can only do this xform if we know that bits from X that are set in C2
3634     // but not in C1 are already zero.  Likewise for Y.
3635     if (const ConstantSDNode *N0O1C =
3636         getAsNonOpaqueConstant(N0.getOperand(1))) {
3637       if (const ConstantSDNode *N1O1C =
3638           getAsNonOpaqueConstant(N1.getOperand(1))) {
3639         // We can only do this xform if we know that bits from X that are set in
3640         // C2 but not in C1 are already zero.  Likewise for Y.
3641         const APInt &LHSMask = N0O1C->getAPIntValue();
3642         const APInt &RHSMask = N1O1C->getAPIntValue();
3643
3644         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3645             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3646           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3647                                   N0.getOperand(0), N1.getOperand(0));
3648           SDLoc DL(LocReference);
3649           return DAG.getNode(ISD::AND, DL, VT, X,
3650                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3651         }
3652       }
3653     }
3654   }
3655
3656   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3657   if (N0.getOpcode() == ISD::AND &&
3658       N1.getOpcode() == ISD::AND &&
3659       N0.getOperand(0) == N1.getOperand(0) &&
3660       // Don't increase # computations.
3661       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3662     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3663                             N0.getOperand(1), N1.getOperand(1));
3664     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3665   }
3666
3667   return SDValue();
3668 }
3669
3670 SDValue DAGCombiner::visitOR(SDNode *N) {
3671   SDValue N0 = N->getOperand(0);
3672   SDValue N1 = N->getOperand(1);
3673   EVT VT = N1.getValueType();
3674
3675   // fold vector ops
3676   if (VT.isVector()) {
3677     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3678       return FoldedVOp;
3679
3680     // fold (or x, 0) -> x, vector edition
3681     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3682       return N1;
3683     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3684       return N0;
3685
3686     // fold (or x, -1) -> -1, vector edition
3687     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3688       // do not return N0, because undef node may exist in N0
3689       return DAG.getConstant(
3690           APInt::getAllOnesValue(
3691               N0.getValueType().getScalarType().getSizeInBits()),
3692           SDLoc(N), N0.getValueType());
3693     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3694       // do not return N1, because undef node may exist in N1
3695       return DAG.getConstant(
3696           APInt::getAllOnesValue(
3697               N1.getValueType().getScalarType().getSizeInBits()),
3698           SDLoc(N), N1.getValueType());
3699
3700     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3701     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3702     // Do this only if the resulting shuffle is legal.
3703     if (isa<ShuffleVectorSDNode>(N0) &&
3704         isa<ShuffleVectorSDNode>(N1) &&
3705         // Avoid folding a node with illegal type.
3706         TLI.isTypeLegal(VT) &&
3707         N0->getOperand(1) == N1->getOperand(1) &&
3708         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3709       bool CanFold = true;
3710       unsigned NumElts = VT.getVectorNumElements();
3711       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3712       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3713       // We construct two shuffle masks:
3714       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3715       // and N1 as the second operand.
3716       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3717       // and N0 as the second operand.
3718       // We do this because OR is commutable and therefore there might be
3719       // two ways to fold this node into a shuffle.
3720       SmallVector<int,4> Mask1;
3721       SmallVector<int,4> Mask2;
3722
3723       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3724         int M0 = SV0->getMaskElt(i);
3725         int M1 = SV1->getMaskElt(i);
3726
3727         // Both shuffle indexes are undef. Propagate Undef.
3728         if (M0 < 0 && M1 < 0) {
3729           Mask1.push_back(M0);
3730           Mask2.push_back(M0);
3731           continue;
3732         }
3733
3734         if (M0 < 0 || M1 < 0 ||
3735             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3736             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3737           CanFold = false;
3738           break;
3739         }
3740
3741         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3742         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3743       }
3744
3745       if (CanFold) {
3746         // Fold this sequence only if the resulting shuffle is 'legal'.
3747         if (TLI.isShuffleMaskLegal(Mask1, VT))
3748           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3749                                       N1->getOperand(0), &Mask1[0]);
3750         if (TLI.isShuffleMaskLegal(Mask2, VT))
3751           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3752                                       N0->getOperand(0), &Mask2[0]);
3753       }
3754     }
3755   }
3756
3757   // fold (or c1, c2) -> c1|c2
3758   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3759   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3760   if (N0C && N1C && !N1C->isOpaque())
3761     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3762   // canonicalize constant to RHS
3763   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3764      !isConstantIntBuildVectorOrConstantInt(N1))
3765     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3766   // fold (or x, 0) -> x
3767   if (isNullConstant(N1))
3768     return N0;
3769   // fold (or x, -1) -> -1
3770   if (isAllOnesConstant(N1))
3771     return N1;
3772   // fold (or x, c) -> c iff (x & ~c) == 0
3773   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3774     return N1;
3775
3776   if (SDValue Combined = visitORLike(N0, N1, N))
3777     return Combined;
3778
3779   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3780   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3781     return BSwap;
3782   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3783     return BSwap;
3784
3785   // reassociate or
3786   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3787     return ROR;
3788   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3789   // iff (c1 & c2) == 0.
3790   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3791              isa<ConstantSDNode>(N0.getOperand(1))) {
3792     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3793     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3794       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3795                                                    N1C, C1))
3796         return DAG.getNode(
3797             ISD::AND, SDLoc(N), VT,
3798             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3799       return SDValue();
3800     }
3801   }
3802   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3803   if (N0.getOpcode() == N1.getOpcode())
3804     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3805       return Tmp;
3806
3807   // See if this is some rotate idiom.
3808   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3809     return SDValue(Rot, 0);
3810
3811   // Simplify the operands using demanded-bits information.
3812   if (!VT.isVector() &&
3813       SimplifyDemandedBits(SDValue(N, 0)))
3814     return SDValue(N, 0);
3815
3816   return SDValue();
3817 }
3818
3819 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3820 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3821   if (Op.getOpcode() == ISD::AND) {
3822     if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3823       Mask = Op.getOperand(1);
3824       Op = Op.getOperand(0);
3825     } else {
3826       return false;
3827     }
3828   }
3829
3830   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3831     Shift = Op;
3832     return true;
3833   }
3834
3835   return false;
3836 }
3837
3838 // Return true if we can prove that, whenever Neg and Pos are both in the
3839 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3840 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3841 //
3842 //     (or (shift1 X, Neg), (shift2 X, Pos))
3843 //
3844 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3845 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3846 // to consider shift amounts with defined behavior.
3847 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3848   // If EltSize is a power of 2 then:
3849   //
3850   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3851   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3852   //
3853   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3854   // for the stronger condition:
3855   //
3856   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3857   //
3858   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3859   // we can just replace Neg with Neg' for the rest of the function.
3860   //
3861   // In other cases we check for the even stronger condition:
3862   //
3863   //     Neg == EltSize - Pos                                    [B]
3864   //
3865   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3866   // behavior if Pos == 0 (and consequently Neg == EltSize).
3867   //
3868   // We could actually use [A] whenever EltSize is a power of 2, but the
3869   // only extra cases that it would match are those uninteresting ones
3870   // where Neg and Pos are never in range at the same time.  E.g. for
3871   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3872   // as well as (sub 32, Pos), but:
3873   //
3874   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3875   //
3876   // always invokes undefined behavior for 32-bit X.
3877   //
3878   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3879   unsigned MaskLoBits = 0;
3880   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3881     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3882       if (NegC->getAPIntValue() == EltSize - 1) {
3883         Neg = Neg.getOperand(0);
3884         MaskLoBits = Log2_64(EltSize);
3885       }
3886     }
3887   }
3888
3889   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3890   if (Neg.getOpcode() != ISD::SUB)
3891     return false;
3892   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3893   if (!NegC)
3894     return false;
3895   SDValue NegOp1 = Neg.getOperand(1);
3896
3897   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3898   // Pos'.  The truncation is redundant for the purpose of the equality.
3899   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3900     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3901       if (PosC->getAPIntValue() == EltSize - 1)
3902         Pos = Pos.getOperand(0);
3903
3904   // The condition we need is now:
3905   //
3906   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3907   //
3908   // If NegOp1 == Pos then we need:
3909   //
3910   //              EltSize & Mask == NegC & Mask
3911   //
3912   // (because "x & Mask" is a truncation and distributes through subtraction).
3913   APInt Width;
3914   if (Pos == NegOp1)
3915     Width = NegC->getAPIntValue();
3916
3917   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3918   // Then the condition we want to prove becomes:
3919   //
3920   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3921   //
3922   // which, again because "x & Mask" is a truncation, becomes:
3923   //
3924   //                NegC & Mask == (EltSize - PosC) & Mask
3925   //             EltSize & Mask == (NegC + PosC) & Mask
3926   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3927     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3928       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3929     else
3930       return false;
3931   } else
3932     return false;
3933
3934   // Now we just need to check that EltSize & Mask == Width & Mask.
3935   if (MaskLoBits)
3936     // EltSize & Mask is 0 since Mask is EltSize - 1.
3937     return Width.getLoBits(MaskLoBits) == 0;
3938   return Width == EltSize;
3939 }
3940
3941 // A subroutine of MatchRotate used once we have found an OR of two opposite
3942 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3943 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3944 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3945 // Neg with outer conversions stripped away.
3946 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3947                                        SDValue Neg, SDValue InnerPos,
3948                                        SDValue InnerNeg, unsigned PosOpcode,
3949                                        unsigned NegOpcode, SDLoc DL) {
3950   // fold (or (shl x, (*ext y)),
3951   //          (srl x, (*ext (sub 32, y)))) ->
3952   //   (rotl x, y) or (rotr x, (sub 32, y))
3953   //
3954   // fold (or (shl x, (*ext (sub 32, y))),
3955   //          (srl x, (*ext y))) ->
3956   //   (rotr x, y) or (rotl x, (sub 32, y))
3957   EVT VT = Shifted.getValueType();
3958   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3959     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3960     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3961                        HasPos ? Pos : Neg).getNode();
3962   }
3963
3964   return nullptr;
3965 }
3966
3967 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3968 // idioms for rotate, and if the target supports rotation instructions, generate
3969 // a rot[lr].
3970 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3971   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3972   EVT VT = LHS.getValueType();
3973   if (!TLI.isTypeLegal(VT)) return nullptr;
3974
3975   // The target must have at least one rotate flavor.
3976   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3977   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3978   if (!HasROTL && !HasROTR) return nullptr;
3979
3980   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3981   SDValue LHSShift;   // The shift.
3982   SDValue LHSMask;    // AND value if any.
3983   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3984     return nullptr; // Not part of a rotate.
3985
3986   SDValue RHSShift;   // The shift.
3987   SDValue RHSMask;    // AND value if any.
3988   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3989     return nullptr; // Not part of a rotate.
3990
3991   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3992     return nullptr;   // Not shifting the same value.
3993
3994   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3995     return nullptr;   // Shifts must disagree.
3996
3997   // Canonicalize shl to left side in a shl/srl pair.
3998   if (RHSShift.getOpcode() == ISD::SHL) {
3999     std::swap(LHS, RHS);
4000     std::swap(LHSShift, RHSShift);
4001     std::swap(LHSMask, RHSMask);
4002   }
4003
4004   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4005   SDValue LHSShiftArg = LHSShift.getOperand(0);
4006   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4007   SDValue RHSShiftArg = RHSShift.getOperand(0);
4008   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4009
4010   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4011   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4012   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4013     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4014     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4015     if ((LShVal + RShVal) != EltSizeInBits)
4016       return nullptr;
4017
4018     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4019                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4020
4021     // If there is an AND of either shifted operand, apply it to the result.
4022     if (LHSMask.getNode() || RHSMask.getNode()) {
4023       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4024       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4025
4026       if (LHSMask.getNode()) {
4027         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4028         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4029                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4030                                        DAG.getConstant(RHSBits, DL, VT)));
4031       }
4032       if (RHSMask.getNode()) {
4033         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4034         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4035                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4036                                        DAG.getConstant(LHSBits, DL, VT)));
4037       }
4038
4039       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4040     }
4041
4042     return Rot.getNode();
4043   }
4044
4045   // If there is a mask here, and we have a variable shift, we can't be sure
4046   // that we're masking out the right stuff.
4047   if (LHSMask.getNode() || RHSMask.getNode())
4048     return nullptr;
4049
4050   // If the shift amount is sign/zext/any-extended just peel it off.
4051   SDValue LExtOp0 = LHSShiftAmt;
4052   SDValue RExtOp0 = RHSShiftAmt;
4053   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4054        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4055        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4056        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4057       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4058        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4059        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4060        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4061     LExtOp0 = LHSShiftAmt.getOperand(0);
4062     RExtOp0 = RHSShiftAmt.getOperand(0);
4063   }
4064
4065   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4066                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4067   if (TryL)
4068     return TryL;
4069
4070   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4071                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4072   if (TryR)
4073     return TryR;
4074
4075   return nullptr;
4076 }
4077
4078 SDValue DAGCombiner::visitXOR(SDNode *N) {
4079   SDValue N0 = N->getOperand(0);
4080   SDValue N1 = N->getOperand(1);
4081   EVT VT = N0.getValueType();
4082
4083   // fold vector ops
4084   if (VT.isVector()) {
4085     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4086       return FoldedVOp;
4087
4088     // fold (xor x, 0) -> x, vector edition
4089     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4090       return N1;
4091     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4092       return N0;
4093   }
4094
4095   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4096   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4097     return DAG.getConstant(0, SDLoc(N), VT);
4098   // fold (xor x, undef) -> undef
4099   if (N0.getOpcode() == ISD::UNDEF)
4100     return N0;
4101   if (N1.getOpcode() == ISD::UNDEF)
4102     return N1;
4103   // fold (xor c1, c2) -> c1^c2
4104   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4105   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4106   if (N0C && N1C)
4107     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4108   // canonicalize constant to RHS
4109   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4110      !isConstantIntBuildVectorOrConstantInt(N1))
4111     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4112   // fold (xor x, 0) -> x
4113   if (isNullConstant(N1))
4114     return N0;
4115   // reassociate xor
4116   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4117     return RXOR;
4118
4119   // fold !(x cc y) -> (x !cc y)
4120   SDValue LHS, RHS, CC;
4121   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4122     bool isInt = LHS.getValueType().isInteger();
4123     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4124                                                isInt);
4125
4126     if (!LegalOperations ||
4127         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4128       switch (N0.getOpcode()) {
4129       default:
4130         llvm_unreachable("Unhandled SetCC Equivalent!");
4131       case ISD::SETCC:
4132         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4133       case ISD::SELECT_CC:
4134         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4135                                N0.getOperand(3), NotCC);
4136       }
4137     }
4138   }
4139
4140   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4141   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4142       N0.getNode()->hasOneUse() &&
4143       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4144     SDValue V = N0.getOperand(0);
4145     SDLoc DL(N0);
4146     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4147                     DAG.getConstant(1, DL, V.getValueType()));
4148     AddToWorklist(V.getNode());
4149     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4150   }
4151
4152   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4153   if (isOneConstant(N1) && VT == MVT::i1 &&
4154       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4155     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4156     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4157       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4158       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4159       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4160       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4161       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4162     }
4163   }
4164   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4165   if (isAllOnesConstant(N1) &&
4166       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4167     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4168     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4169       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4170       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4171       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4172       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4173       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4174     }
4175   }
4176   // fold (xor (and x, y), y) -> (and (not x), y)
4177   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4178       N0->getOperand(1) == N1) {
4179     SDValue X = N0->getOperand(0);
4180     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4181     AddToWorklist(NotX.getNode());
4182     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4183   }
4184   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4185   if (N1C && N0.getOpcode() == ISD::XOR) {
4186     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4187       SDLoc DL(N);
4188       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4189                          DAG.getConstant(N1C->getAPIntValue() ^
4190                                          N00C->getAPIntValue(), DL, VT));
4191     }
4192     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4193       SDLoc DL(N);
4194       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4195                          DAG.getConstant(N1C->getAPIntValue() ^
4196                                          N01C->getAPIntValue(), DL, VT));
4197     }
4198   }
4199   // fold (xor x, x) -> 0
4200   if (N0 == N1)
4201     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4202
4203   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4204   // Here is a concrete example of this equivalence:
4205   // i16   x ==  14
4206   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4207   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4208   //
4209   // =>
4210   //
4211   // i16     ~1      == 0b1111111111111110
4212   // i16 rol(~1, 14) == 0b1011111111111111
4213   //
4214   // Some additional tips to help conceptualize this transform:
4215   // - Try to see the operation as placing a single zero in a value of all ones.
4216   // - There exists no value for x which would allow the result to contain zero.
4217   // - Values of x larger than the bitwidth are undefined and do not require a
4218   //   consistent result.
4219   // - Pushing the zero left requires shifting one bits in from the right.
4220   // A rotate left of ~1 is a nice way of achieving the desired result.
4221   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4222       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4223     SDLoc DL(N);
4224     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4225                        N0.getOperand(1));
4226   }
4227
4228   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4229   if (N0.getOpcode() == N1.getOpcode())
4230     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4231       return Tmp;
4232
4233   // Simplify the expression using non-local knowledge.
4234   if (!VT.isVector() &&
4235       SimplifyDemandedBits(SDValue(N, 0)))
4236     return SDValue(N, 0);
4237
4238   return SDValue();
4239 }
4240
4241 /// Handle transforms common to the three shifts, when the shift amount is a
4242 /// constant.
4243 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4244   SDNode *LHS = N->getOperand(0).getNode();
4245   if (!LHS->hasOneUse()) return SDValue();
4246
4247   // We want to pull some binops through shifts, so that we have (and (shift))
4248   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4249   // thing happens with address calculations, so it's important to canonicalize
4250   // it.
4251   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4252
4253   switch (LHS->getOpcode()) {
4254   default: return SDValue();
4255   case ISD::OR:
4256   case ISD::XOR:
4257     HighBitSet = false; // We can only transform sra if the high bit is clear.
4258     break;
4259   case ISD::AND:
4260     HighBitSet = true;  // We can only transform sra if the high bit is set.
4261     break;
4262   case ISD::ADD:
4263     if (N->getOpcode() != ISD::SHL)
4264       return SDValue(); // only shl(add) not sr[al](add).
4265     HighBitSet = false; // We can only transform sra if the high bit is clear.
4266     break;
4267   }
4268
4269   // We require the RHS of the binop to be a constant and not opaque as well.
4270   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4271   if (!BinOpCst) return SDValue();
4272
4273   // FIXME: disable this unless the input to the binop is a shift by a constant.
4274   // If it is not a shift, it pessimizes some common cases like:
4275   //
4276   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4277   //    int bar(int *X, int i) { return X[i & 255]; }
4278   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4279   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4280        BinOpLHSVal->getOpcode() != ISD::SRA &&
4281        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4282       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4283     return SDValue();
4284
4285   EVT VT = N->getValueType(0);
4286
4287   // If this is a signed shift right, and the high bit is modified by the
4288   // logical operation, do not perform the transformation. The highBitSet
4289   // boolean indicates the value of the high bit of the constant which would
4290   // cause it to be modified for this operation.
4291   if (N->getOpcode() == ISD::SRA) {
4292     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4293     if (BinOpRHSSignSet != HighBitSet)
4294       return SDValue();
4295   }
4296
4297   if (!TLI.isDesirableToCommuteWithShift(LHS))
4298     return SDValue();
4299
4300   // Fold the constants, shifting the binop RHS by the shift amount.
4301   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4302                                N->getValueType(0),
4303                                LHS->getOperand(1), N->getOperand(1));
4304   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4305
4306   // Create the new shift.
4307   SDValue NewShift = DAG.getNode(N->getOpcode(),
4308                                  SDLoc(LHS->getOperand(0)),
4309                                  VT, LHS->getOperand(0), N->getOperand(1));
4310
4311   // Create the new binop.
4312   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4313 }
4314
4315 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4316   assert(N->getOpcode() == ISD::TRUNCATE);
4317   assert(N->getOperand(0).getOpcode() == ISD::AND);
4318
4319   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4320   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4321     SDValue N01 = N->getOperand(0).getOperand(1);
4322
4323     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4324       if (!N01C->isOpaque()) {
4325         EVT TruncVT = N->getValueType(0);
4326         SDValue N00 = N->getOperand(0).getOperand(0);
4327         APInt TruncC = N01C->getAPIntValue();
4328         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4329         SDLoc DL(N);
4330
4331         return DAG.getNode(ISD::AND, DL, TruncVT,
4332                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4333                            DAG.getConstant(TruncC, DL, TruncVT));
4334       }
4335     }
4336   }
4337
4338   return SDValue();
4339 }
4340
4341 SDValue DAGCombiner::visitRotate(SDNode *N) {
4342   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4343   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4344       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4345     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4346     if (NewOp1.getNode())
4347       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4348                          N->getOperand(0), NewOp1);
4349   }
4350   return SDValue();
4351 }
4352
4353 SDValue DAGCombiner::visitSHL(SDNode *N) {
4354   SDValue N0 = N->getOperand(0);
4355   SDValue N1 = N->getOperand(1);
4356   EVT VT = N0.getValueType();
4357   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4358
4359   // fold vector ops
4360   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4361   if (VT.isVector()) {
4362     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4363       return FoldedVOp;
4364
4365     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4366     // If setcc produces all-one true value then:
4367     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4368     if (N1CV && N1CV->isConstant()) {
4369       if (N0.getOpcode() == ISD::AND) {
4370         SDValue N00 = N0->getOperand(0);
4371         SDValue N01 = N0->getOperand(1);
4372         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4373
4374         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4375             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4376                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4377           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4378                                                      N01CV, N1CV))
4379             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4380         }
4381       } else {
4382         N1C = isConstOrConstSplat(N1);
4383       }
4384     }
4385   }
4386
4387   // fold (shl c1, c2) -> c1<<c2
4388   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4389   if (N0C && N1C && !N1C->isOpaque())
4390     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4391   // fold (shl 0, x) -> 0
4392   if (isNullConstant(N0))
4393     return N0;
4394   // fold (shl x, c >= size(x)) -> undef
4395   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4396     return DAG.getUNDEF(VT);
4397   // fold (shl x, 0) -> x
4398   if (N1C && N1C->isNullValue())
4399     return N0;
4400   // fold (shl undef, x) -> 0
4401   if (N0.getOpcode() == ISD::UNDEF)
4402     return DAG.getConstant(0, SDLoc(N), VT);
4403   // if (shl x, c) is known to be zero, return 0
4404   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4405                             APInt::getAllOnesValue(OpSizeInBits)))
4406     return DAG.getConstant(0, SDLoc(N), VT);
4407   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4408   if (N1.getOpcode() == ISD::TRUNCATE &&
4409       N1.getOperand(0).getOpcode() == ISD::AND) {
4410     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4411     if (NewOp1.getNode())
4412       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4413   }
4414
4415   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4416     return SDValue(N, 0);
4417
4418   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4419   if (N1C && N0.getOpcode() == ISD::SHL) {
4420     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4421       uint64_t c1 = N0C1->getZExtValue();
4422       uint64_t c2 = N1C->getZExtValue();
4423       SDLoc DL(N);
4424       if (c1 + c2 >= OpSizeInBits)
4425         return DAG.getConstant(0, DL, VT);
4426       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4427                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4428     }
4429   }
4430
4431   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4432   // For this to be valid, the second form must not preserve any of the bits
4433   // that are shifted out by the inner shift in the first form.  This means
4434   // the outer shift size must be >= the number of bits added by the ext.
4435   // As a corollary, we don't care what kind of ext it is.
4436   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4437               N0.getOpcode() == ISD::ANY_EXTEND ||
4438               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4439       N0.getOperand(0).getOpcode() == ISD::SHL) {
4440     SDValue N0Op0 = N0.getOperand(0);
4441     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4442       uint64_t c1 = N0Op0C1->getZExtValue();
4443       uint64_t c2 = N1C->getZExtValue();
4444       EVT InnerShiftVT = N0Op0.getValueType();
4445       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4446       if (c2 >= OpSizeInBits - InnerShiftSize) {
4447         SDLoc DL(N0);
4448         if (c1 + c2 >= OpSizeInBits)
4449           return DAG.getConstant(0, DL, VT);
4450         return DAG.getNode(ISD::SHL, DL, VT,
4451                            DAG.getNode(N0.getOpcode(), DL, VT,
4452                                        N0Op0->getOperand(0)),
4453                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4454       }
4455     }
4456   }
4457
4458   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4459   // Only fold this if the inner zext has no other uses to avoid increasing
4460   // the total number of instructions.
4461   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4462       N0.getOperand(0).getOpcode() == ISD::SRL) {
4463     SDValue N0Op0 = N0.getOperand(0);
4464     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4465       uint64_t c1 = N0Op0C1->getZExtValue();
4466       if (c1 < VT.getScalarSizeInBits()) {
4467         uint64_t c2 = N1C->getZExtValue();
4468         if (c1 == c2) {
4469           SDValue NewOp0 = N0.getOperand(0);
4470           EVT CountVT = NewOp0.getOperand(1).getValueType();
4471           SDLoc DL(N);
4472           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4473                                        NewOp0,
4474                                        DAG.getConstant(c2, DL, CountVT));
4475           AddToWorklist(NewSHL.getNode());
4476           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4477         }
4478       }
4479     }
4480   }
4481
4482   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4483   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4484   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4485       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4486     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4487       uint64_t C1 = N0C1->getZExtValue();
4488       uint64_t C2 = N1C->getZExtValue();
4489       SDLoc DL(N);
4490       if (C1 <= C2)
4491         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4492                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4493       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4494                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4495     }
4496   }
4497
4498   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4499   //                               (and (srl x, (sub c1, c2), MASK)
4500   // Only fold this if the inner shift has no other uses -- if it does, folding
4501   // this will increase the total number of instructions.
4502   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4503     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4504       uint64_t c1 = N0C1->getZExtValue();
4505       if (c1 < OpSizeInBits) {
4506         uint64_t c2 = N1C->getZExtValue();
4507         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4508         SDValue Shift;
4509         if (c2 > c1) {
4510           Mask = Mask.shl(c2 - c1);
4511           SDLoc DL(N);
4512           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4513                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4514         } else {
4515           Mask = Mask.lshr(c1 - c2);
4516           SDLoc DL(N);
4517           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4518                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4519         }
4520         SDLoc DL(N0);
4521         return DAG.getNode(ISD::AND, DL, VT, Shift,
4522                            DAG.getConstant(Mask, DL, VT));
4523       }
4524     }
4525   }
4526   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4527   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4528     unsigned BitSize = VT.getScalarSizeInBits();
4529     SDLoc DL(N);
4530     SDValue HiBitsMask =
4531       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4532                                             BitSize - N1C->getZExtValue()),
4533                       DL, VT);
4534     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4535                        HiBitsMask);
4536   }
4537
4538   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4539   // Variant of version done on multiply, except mul by a power of 2 is turned
4540   // into a shift.
4541   APInt Val;
4542   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4543       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4544        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4545     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4546     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4547     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4548   }
4549
4550   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4551   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4552     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4553       if (SDValue Folded =
4554               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4555         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4556     }
4557   }
4558
4559   if (N1C && !N1C->isOpaque())
4560     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4561       return NewSHL;
4562
4563   return SDValue();
4564 }
4565
4566 SDValue DAGCombiner::visitSRA(SDNode *N) {
4567   SDValue N0 = N->getOperand(0);
4568   SDValue N1 = N->getOperand(1);
4569   EVT VT = N0.getValueType();
4570   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4571
4572   // fold vector ops
4573   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4574   if (VT.isVector()) {
4575     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4576       return FoldedVOp;
4577
4578     N1C = isConstOrConstSplat(N1);
4579   }
4580
4581   // fold (sra c1, c2) -> (sra c1, c2)
4582   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4583   if (N0C && N1C && !N1C->isOpaque())
4584     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4585   // fold (sra 0, x) -> 0
4586   if (isNullConstant(N0))
4587     return N0;
4588   // fold (sra -1, x) -> -1
4589   if (isAllOnesConstant(N0))
4590     return N0;
4591   // fold (sra x, (setge c, size(x))) -> undef
4592   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4593     return DAG.getUNDEF(VT);
4594   // fold (sra x, 0) -> x
4595   if (N1C && N1C->isNullValue())
4596     return N0;
4597   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4598   // sext_inreg.
4599   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4600     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4601     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4602     if (VT.isVector())
4603       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4604                                ExtVT, VT.getVectorNumElements());
4605     if ((!LegalOperations ||
4606          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4607       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4608                          N0.getOperand(0), DAG.getValueType(ExtVT));
4609   }
4610
4611   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4612   if (N1C && N0.getOpcode() == ISD::SRA) {
4613     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4614       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4615       if (Sum >= OpSizeInBits)
4616         Sum = OpSizeInBits - 1;
4617       SDLoc DL(N);
4618       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4619                          DAG.getConstant(Sum, DL, N1.getValueType()));
4620     }
4621   }
4622
4623   // fold (sra (shl X, m), (sub result_size, n))
4624   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4625   // result_size - n != m.
4626   // If truncate is free for the target sext(shl) is likely to result in better
4627   // code.
4628   if (N0.getOpcode() == ISD::SHL && N1C) {
4629     // Get the two constanst of the shifts, CN0 = m, CN = n.
4630     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4631     if (N01C) {
4632       LLVMContext &Ctx = *DAG.getContext();
4633       // Determine what the truncate's result bitsize and type would be.
4634       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4635
4636       if (VT.isVector())
4637         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4638
4639       // Determine the residual right-shift amount.
4640       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4641
4642       // If the shift is not a no-op (in which case this should be just a sign
4643       // extend already), the truncated to type is legal, sign_extend is legal
4644       // on that type, and the truncate to that type is both legal and free,
4645       // perform the transform.
4646       if ((ShiftAmt > 0) &&
4647           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4648           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4649           TLI.isTruncateFree(VT, TruncVT)) {
4650
4651         SDLoc DL(N);
4652         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4653             getShiftAmountTy(N0.getOperand(0).getValueType()));
4654         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4655                                     N0.getOperand(0), Amt);
4656         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4657                                     Shift);
4658         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4659                            N->getValueType(0), Trunc);
4660       }
4661     }
4662   }
4663
4664   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4665   if (N1.getOpcode() == ISD::TRUNCATE &&
4666       N1.getOperand(0).getOpcode() == ISD::AND) {
4667     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4668     if (NewOp1.getNode())
4669       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4670   }
4671
4672   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4673   //      if c1 is equal to the number of bits the trunc removes
4674   if (N0.getOpcode() == ISD::TRUNCATE &&
4675       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4676        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4677       N0.getOperand(0).hasOneUse() &&
4678       N0.getOperand(0).getOperand(1).hasOneUse() &&
4679       N1C) {
4680     SDValue N0Op0 = N0.getOperand(0);
4681     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4682       unsigned LargeShiftVal = LargeShift->getZExtValue();
4683       EVT LargeVT = N0Op0.getValueType();
4684
4685       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4686         SDLoc DL(N);
4687         SDValue Amt =
4688           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4689                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4690         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4691                                   N0Op0.getOperand(0), Amt);
4692         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4693       }
4694     }
4695   }
4696
4697   // Simplify, based on bits shifted out of the LHS.
4698   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4699     return SDValue(N, 0);
4700
4701
4702   // If the sign bit is known to be zero, switch this to a SRL.
4703   if (DAG.SignBitIsZero(N0))
4704     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4705
4706   if (N1C && !N1C->isOpaque())
4707     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4708       return NewSRA;
4709
4710   return SDValue();
4711 }
4712
4713 SDValue DAGCombiner::visitSRL(SDNode *N) {
4714   SDValue N0 = N->getOperand(0);
4715   SDValue N1 = N->getOperand(1);
4716   EVT VT = N0.getValueType();
4717   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4718
4719   // fold vector ops
4720   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4721   if (VT.isVector()) {
4722     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4723       return FoldedVOp;
4724
4725     N1C = isConstOrConstSplat(N1);
4726   }
4727
4728   // fold (srl c1, c2) -> c1 >>u c2
4729   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4730   if (N0C && N1C && !N1C->isOpaque())
4731     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4732   // fold (srl 0, x) -> 0
4733   if (isNullConstant(N0))
4734     return N0;
4735   // fold (srl x, c >= size(x)) -> undef
4736   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4737     return DAG.getUNDEF(VT);
4738   // fold (srl x, 0) -> x
4739   if (N1C && N1C->isNullValue())
4740     return N0;
4741   // if (srl x, c) is known to be zero, return 0
4742   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4743                                    APInt::getAllOnesValue(OpSizeInBits)))
4744     return DAG.getConstant(0, SDLoc(N), VT);
4745
4746   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4747   if (N1C && N0.getOpcode() == ISD::SRL) {
4748     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4749       uint64_t c1 = N01C->getZExtValue();
4750       uint64_t c2 = N1C->getZExtValue();
4751       SDLoc DL(N);
4752       if (c1 + c2 >= OpSizeInBits)
4753         return DAG.getConstant(0, DL, VT);
4754       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4755                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4756     }
4757   }
4758
4759   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4760   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4761       N0.getOperand(0).getOpcode() == ISD::SRL &&
4762       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4763     uint64_t c1 =
4764       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4765     uint64_t c2 = N1C->getZExtValue();
4766     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4767     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4768     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4769     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4770     if (c1 + OpSizeInBits == InnerShiftSize) {
4771       SDLoc DL(N0);
4772       if (c1 + c2 >= InnerShiftSize)
4773         return DAG.getConstant(0, DL, VT);
4774       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4775                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4776                                      N0.getOperand(0)->getOperand(0),
4777                                      DAG.getConstant(c1 + c2, DL,
4778                                                      ShiftCountVT)));
4779     }
4780   }
4781
4782   // fold (srl (shl x, c), c) -> (and x, cst2)
4783   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4784     unsigned BitSize = N0.getScalarValueSizeInBits();
4785     if (BitSize <= 64) {
4786       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4787       SDLoc DL(N);
4788       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4789                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4790     }
4791   }
4792
4793   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4794   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4795     // Shifting in all undef bits?
4796     EVT SmallVT = N0.getOperand(0).getValueType();
4797     unsigned BitSize = SmallVT.getScalarSizeInBits();
4798     if (N1C->getZExtValue() >= BitSize)
4799       return DAG.getUNDEF(VT);
4800
4801     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4802       uint64_t ShiftAmt = N1C->getZExtValue();
4803       SDLoc DL0(N0);
4804       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4805                                        N0.getOperand(0),
4806                           DAG.getConstant(ShiftAmt, DL0,
4807                                           getShiftAmountTy(SmallVT)));
4808       AddToWorklist(SmallShift.getNode());
4809       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4810       SDLoc DL(N);
4811       return DAG.getNode(ISD::AND, DL, VT,
4812                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4813                          DAG.getConstant(Mask, DL, VT));
4814     }
4815   }
4816
4817   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4818   // bit, which is unmodified by sra.
4819   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4820     if (N0.getOpcode() == ISD::SRA)
4821       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4822   }
4823
4824   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4825   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4826       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4827     APInt KnownZero, KnownOne;
4828     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4829
4830     // If any of the input bits are KnownOne, then the input couldn't be all
4831     // zeros, thus the result of the srl will always be zero.
4832     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4833
4834     // If all of the bits input the to ctlz node are known to be zero, then
4835     // the result of the ctlz is "32" and the result of the shift is one.
4836     APInt UnknownBits = ~KnownZero;
4837     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4838
4839     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4840     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4841       // Okay, we know that only that the single bit specified by UnknownBits
4842       // could be set on input to the CTLZ node. If this bit is set, the SRL
4843       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4844       // to an SRL/XOR pair, which is likely to simplify more.
4845       unsigned ShAmt = UnknownBits.countTrailingZeros();
4846       SDValue Op = N0.getOperand(0);
4847
4848       if (ShAmt) {
4849         SDLoc DL(N0);
4850         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4851                   DAG.getConstant(ShAmt, DL,
4852                                   getShiftAmountTy(Op.getValueType())));
4853         AddToWorklist(Op.getNode());
4854       }
4855
4856       SDLoc DL(N);
4857       return DAG.getNode(ISD::XOR, DL, VT,
4858                          Op, DAG.getConstant(1, DL, VT));
4859     }
4860   }
4861
4862   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4863   if (N1.getOpcode() == ISD::TRUNCATE &&
4864       N1.getOperand(0).getOpcode() == ISD::AND) {
4865     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4866       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4867   }
4868
4869   // fold operands of srl based on knowledge that the low bits are not
4870   // demanded.
4871   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4872     return SDValue(N, 0);
4873
4874   if (N1C && !N1C->isOpaque())
4875     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4876       return NewSRL;
4877
4878   // Attempt to convert a srl of a load into a narrower zero-extending load.
4879   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4880     return NarrowLoad;
4881
4882   // Here is a common situation. We want to optimize:
4883   //
4884   //   %a = ...
4885   //   %b = and i32 %a, 2
4886   //   %c = srl i32 %b, 1
4887   //   brcond i32 %c ...
4888   //
4889   // into
4890   //
4891   //   %a = ...
4892   //   %b = and %a, 2
4893   //   %c = setcc eq %b, 0
4894   //   brcond %c ...
4895   //
4896   // However when after the source operand of SRL is optimized into AND, the SRL
4897   // itself may not be optimized further. Look for it and add the BRCOND into
4898   // the worklist.
4899   if (N->hasOneUse()) {
4900     SDNode *Use = *N->use_begin();
4901     if (Use->getOpcode() == ISD::BRCOND)
4902       AddToWorklist(Use);
4903     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4904       // Also look pass the truncate.
4905       Use = *Use->use_begin();
4906       if (Use->getOpcode() == ISD::BRCOND)
4907         AddToWorklist(Use);
4908     }
4909   }
4910
4911   return SDValue();
4912 }
4913
4914 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4915   SDValue N0 = N->getOperand(0);
4916   EVT VT = N->getValueType(0);
4917
4918   // fold (bswap c1) -> c2
4919   if (isConstantIntBuildVectorOrConstantInt(N0))
4920     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4921   // fold (bswap (bswap x)) -> x
4922   if (N0.getOpcode() == ISD::BSWAP)
4923     return N0->getOperand(0);
4924   return SDValue();
4925 }
4926
4927 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4928   SDValue N0 = N->getOperand(0);
4929   EVT VT = N->getValueType(0);
4930
4931   // fold (ctlz c1) -> c2
4932   if (isConstantIntBuildVectorOrConstantInt(N0))
4933     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4934   return SDValue();
4935 }
4936
4937 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4938   SDValue N0 = N->getOperand(0);
4939   EVT VT = N->getValueType(0);
4940
4941   // fold (ctlz_zero_undef c1) -> c2
4942   if (isConstantIntBuildVectorOrConstantInt(N0))
4943     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4944   return SDValue();
4945 }
4946
4947 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4948   SDValue N0 = N->getOperand(0);
4949   EVT VT = N->getValueType(0);
4950
4951   // fold (cttz c1) -> c2
4952   if (isConstantIntBuildVectorOrConstantInt(N0))
4953     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4954   return SDValue();
4955 }
4956
4957 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4958   SDValue N0 = N->getOperand(0);
4959   EVT VT = N->getValueType(0);
4960
4961   // fold (cttz_zero_undef c1) -> c2
4962   if (isConstantIntBuildVectorOrConstantInt(N0))
4963     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4964   return SDValue();
4965 }
4966
4967 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4968   SDValue N0 = N->getOperand(0);
4969   EVT VT = N->getValueType(0);
4970
4971   // fold (ctpop c1) -> c2
4972   if (isConstantIntBuildVectorOrConstantInt(N0))
4973     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4974   return SDValue();
4975 }
4976
4977
4978 /// \brief Generate Min/Max node
4979 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4980                                    SDValue True, SDValue False,
4981                                    ISD::CondCode CC, const TargetLowering &TLI,
4982                                    SelectionDAG &DAG) {
4983   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4984     return SDValue();
4985
4986   switch (CC) {
4987   case ISD::SETOLT:
4988   case ISD::SETOLE:
4989   case ISD::SETLT:
4990   case ISD::SETLE:
4991   case ISD::SETULT:
4992   case ISD::SETULE: {
4993     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4994     if (TLI.isOperationLegal(Opcode, VT))
4995       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4996     return SDValue();
4997   }
4998   case ISD::SETOGT:
4999   case ISD::SETOGE:
5000   case ISD::SETGT:
5001   case ISD::SETGE:
5002   case ISD::SETUGT:
5003   case ISD::SETUGE: {
5004     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5005     if (TLI.isOperationLegal(Opcode, VT))
5006       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5007     return SDValue();
5008   }
5009   default:
5010     return SDValue();
5011   }
5012 }
5013
5014 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5015   SDValue N0 = N->getOperand(0);
5016   SDValue N1 = N->getOperand(1);
5017   SDValue N2 = N->getOperand(2);
5018   EVT VT = N->getValueType(0);
5019   EVT VT0 = N0.getValueType();
5020
5021   // fold (select C, X, X) -> X
5022   if (N1 == N2)
5023     return N1;
5024   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5025     // fold (select true, X, Y) -> X
5026     // fold (select false, X, Y) -> Y
5027     return !N0C->isNullValue() ? N1 : N2;
5028   }
5029   // fold (select C, 1, X) -> (or C, X)
5030   if (VT == MVT::i1 && isOneConstant(N1))
5031     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5032   // fold (select C, 0, 1) -> (xor C, 1)
5033   // We can't do this reliably if integer based booleans have different contents
5034   // to floating point based booleans. This is because we can't tell whether we
5035   // have an integer-based boolean or a floating-point-based boolean unless we
5036   // can find the SETCC that produced it and inspect its operands. This is
5037   // fairly easy if C is the SETCC node, but it can potentially be
5038   // undiscoverable (or not reasonably discoverable). For example, it could be
5039   // in another basic block or it could require searching a complicated
5040   // expression.
5041   if (VT.isInteger() &&
5042       (VT0 == MVT::i1 || (VT0.isInteger() &&
5043                           TLI.getBooleanContents(false, false) ==
5044                               TLI.getBooleanContents(false, true) &&
5045                           TLI.getBooleanContents(false, false) ==
5046                               TargetLowering::ZeroOrOneBooleanContent)) &&
5047       isNullConstant(N1) && isOneConstant(N2)) {
5048     SDValue XORNode;
5049     if (VT == VT0) {
5050       SDLoc DL(N);
5051       return DAG.getNode(ISD::XOR, DL, VT0,
5052                          N0, DAG.getConstant(1, DL, VT0));
5053     }
5054     SDLoc DL0(N0);
5055     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5056                           N0, DAG.getConstant(1, DL0, VT0));
5057     AddToWorklist(XORNode.getNode());
5058     if (VT.bitsGT(VT0))
5059       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5060     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5061   }
5062   // fold (select C, 0, X) -> (and (not C), X)
5063   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5064     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5065     AddToWorklist(NOTNode.getNode());
5066     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5067   }
5068   // fold (select C, X, 1) -> (or (not C), X)
5069   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5070     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5071     AddToWorklist(NOTNode.getNode());
5072     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5073   }
5074   // fold (select C, X, 0) -> (and C, X)
5075   if (VT == MVT::i1 && isNullConstant(N2))
5076     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5077   // fold (select X, X, Y) -> (or X, Y)
5078   // fold (select X, 1, Y) -> (or X, Y)
5079   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5080     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5081   // fold (select X, Y, X) -> (and X, Y)
5082   // fold (select X, Y, 0) -> (and X, Y)
5083   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5084     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5085
5086   // If we can fold this based on the true/false value, do so.
5087   if (SimplifySelectOps(N, N1, N2))
5088     return SDValue(N, 0);  // Don't revisit N.
5089
5090   if (VT0 == MVT::i1) {
5091     // The code in this block deals with the following 2 equivalences:
5092     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5093     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5094     // The target can specify its prefered form with the
5095     // shouldNormalizeToSelectSequence() callback. However we always transform
5096     // to the right anyway if we find the inner select exists in the DAG anyway
5097     // and we always transform to the left side if we know that we can further
5098     // optimize the combination of the conditions.
5099     bool normalizeToSequence
5100       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5101     // select (and Cond0, Cond1), X, Y
5102     //   -> select Cond0, (select Cond1, X, Y), Y
5103     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5104       SDValue Cond0 = N0->getOperand(0);
5105       SDValue Cond1 = N0->getOperand(1);
5106       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5107                                         N1.getValueType(), Cond1, N1, N2);
5108       if (normalizeToSequence || !InnerSelect.use_empty())
5109         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5110                            InnerSelect, N2);
5111     }
5112     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5113     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5114       SDValue Cond0 = N0->getOperand(0);
5115       SDValue Cond1 = N0->getOperand(1);
5116       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5117                                         N1.getValueType(), Cond1, N1, N2);
5118       if (normalizeToSequence || !InnerSelect.use_empty())
5119         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5120                            InnerSelect);
5121     }
5122
5123     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5124     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5125       SDValue N1_0 = N1->getOperand(0);
5126       SDValue N1_1 = N1->getOperand(1);
5127       SDValue N1_2 = N1->getOperand(2);
5128       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5129         // Create the actual and node if we can generate good code for it.
5130         if (!normalizeToSequence) {
5131           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5132                                     N0, N1_0);
5133           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5134                              N1_1, N2);
5135         }
5136         // Otherwise see if we can optimize the "and" to a better pattern.
5137         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5138           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5139                              N1_1, N2);
5140       }
5141     }
5142     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5143     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5144       SDValue N2_0 = N2->getOperand(0);
5145       SDValue N2_1 = N2->getOperand(1);
5146       SDValue N2_2 = N2->getOperand(2);
5147       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5148         // Create the actual or node if we can generate good code for it.
5149         if (!normalizeToSequence) {
5150           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5151                                    N0, N2_0);
5152           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5153                              N1, N2_2);
5154         }
5155         // Otherwise see if we can optimize to a better pattern.
5156         if (SDValue Combined = visitORLike(N0, N2_0, N))
5157           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5158                              N1, N2_2);
5159       }
5160     }
5161   }
5162
5163   // fold selects based on a setcc into other things, such as min/max/abs
5164   if (N0.getOpcode() == ISD::SETCC) {
5165     // select x, y (fcmp lt x, y) -> fminnum x, y
5166     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5167     //
5168     // This is OK if we don't care about what happens if either operand is a
5169     // NaN.
5170     //
5171
5172     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5173     // no signed zeros as well as no nans.
5174     const TargetOptions &Options = DAG.getTarget().Options;
5175     if (Options.UnsafeFPMath &&
5176         VT.isFloatingPoint() && N0.hasOneUse() &&
5177         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5178       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5179
5180       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5181                                                 N0.getOperand(1), N1, N2, CC,
5182                                                 TLI, DAG))
5183         return FMinMax;
5184     }
5185
5186     if ((!LegalOperations &&
5187          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5188         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5189       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5190                          N0.getOperand(0), N0.getOperand(1),
5191                          N1, N2, N0.getOperand(2));
5192     return SimplifySelect(SDLoc(N), N0, N1, N2);
5193   }
5194
5195   return SDValue();
5196 }
5197
5198 static
5199 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5200   SDLoc DL(N);
5201   EVT LoVT, HiVT;
5202   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5203
5204   // Split the inputs.
5205   SDValue Lo, Hi, LL, LH, RL, RH;
5206   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5207   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5208
5209   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5210   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5211
5212   return std::make_pair(Lo, Hi);
5213 }
5214
5215 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5216 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5217 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5218   SDLoc dl(N);
5219   SDValue Cond = N->getOperand(0);
5220   SDValue LHS = N->getOperand(1);
5221   SDValue RHS = N->getOperand(2);
5222   EVT VT = N->getValueType(0);
5223   int NumElems = VT.getVectorNumElements();
5224   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5225          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5226          Cond.getOpcode() == ISD::BUILD_VECTOR);
5227
5228   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5229   // binary ones here.
5230   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5231     return SDValue();
5232
5233   // We're sure we have an even number of elements due to the
5234   // concat_vectors we have as arguments to vselect.
5235   // Skip BV elements until we find one that's not an UNDEF
5236   // After we find an UNDEF element, keep looping until we get to half the
5237   // length of the BV and see if all the non-undef nodes are the same.
5238   ConstantSDNode *BottomHalf = nullptr;
5239   for (int i = 0; i < NumElems / 2; ++i) {
5240     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5241       continue;
5242
5243     if (BottomHalf == nullptr)
5244       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5245     else if (Cond->getOperand(i).getNode() != BottomHalf)
5246       return SDValue();
5247   }
5248
5249   // Do the same for the second half of the BuildVector
5250   ConstantSDNode *TopHalf = nullptr;
5251   for (int i = NumElems / 2; i < NumElems; ++i) {
5252     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5253       continue;
5254
5255     if (TopHalf == nullptr)
5256       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5257     else if (Cond->getOperand(i).getNode() != TopHalf)
5258       return SDValue();
5259   }
5260
5261   assert(TopHalf && BottomHalf &&
5262          "One half of the selector was all UNDEFs and the other was all the "
5263          "same value. This should have been addressed before this function.");
5264   return DAG.getNode(
5265       ISD::CONCAT_VECTORS, dl, VT,
5266       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5267       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5268 }
5269
5270 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5271
5272   if (Level >= AfterLegalizeTypes)
5273     return SDValue();
5274
5275   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5276   SDValue Mask = MSC->getMask();
5277   SDValue Data  = MSC->getValue();
5278   SDLoc DL(N);
5279
5280   // If the MSCATTER data type requires splitting and the mask is provided by a
5281   // SETCC, then split both nodes and its operands before legalization. This
5282   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5283   // and enables future optimizations (e.g. min/max pattern matching on X86).
5284   if (Mask.getOpcode() != ISD::SETCC)
5285     return SDValue();
5286
5287   // Check if any splitting is required.
5288   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5289       TargetLowering::TypeSplitVector)
5290     return SDValue();
5291   SDValue MaskLo, MaskHi, Lo, Hi;
5292   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5293
5294   EVT LoVT, HiVT;
5295   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5296
5297   SDValue Chain = MSC->getChain();
5298
5299   EVT MemoryVT = MSC->getMemoryVT();
5300   unsigned Alignment = MSC->getOriginalAlignment();
5301
5302   EVT LoMemVT, HiMemVT;
5303   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5304
5305   SDValue DataLo, DataHi;
5306   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5307
5308   SDValue BasePtr = MSC->getBasePtr();
5309   SDValue IndexLo, IndexHi;
5310   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5311
5312   MachineMemOperand *MMO = DAG.getMachineFunction().
5313     getMachineMemOperand(MSC->getPointerInfo(),
5314                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5315                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5316
5317   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5318   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5319                             DL, OpsLo, MMO);
5320
5321   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5322   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5323                             DL, OpsHi, MMO);
5324
5325   AddToWorklist(Lo.getNode());
5326   AddToWorklist(Hi.getNode());
5327
5328   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5329 }
5330
5331 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5332
5333   if (Level >= AfterLegalizeTypes)
5334     return SDValue();
5335
5336   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5337   SDValue Mask = MST->getMask();
5338   SDValue Data  = MST->getValue();
5339   SDLoc DL(N);
5340
5341   // If the MSTORE data type requires splitting and the mask is provided by a
5342   // SETCC, then split both nodes and its operands before legalization. This
5343   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5344   // and enables future optimizations (e.g. min/max pattern matching on X86).
5345   if (Mask.getOpcode() == ISD::SETCC) {
5346
5347     // Check if any splitting is required.
5348     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5349         TargetLowering::TypeSplitVector)
5350       return SDValue();
5351
5352     SDValue MaskLo, MaskHi, Lo, Hi;
5353     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5354
5355     EVT LoVT, HiVT;
5356     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5357
5358     SDValue Chain = MST->getChain();
5359     SDValue Ptr   = MST->getBasePtr();
5360
5361     EVT MemoryVT = MST->getMemoryVT();
5362     unsigned Alignment = MST->getOriginalAlignment();
5363
5364     // if Alignment is equal to the vector size,
5365     // take the half of it for the second part
5366     unsigned SecondHalfAlignment =
5367       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5368          Alignment/2 : Alignment;
5369
5370     EVT LoMemVT, HiMemVT;
5371     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5372
5373     SDValue DataLo, DataHi;
5374     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5375
5376     MachineMemOperand *MMO = DAG.getMachineFunction().
5377       getMachineMemOperand(MST->getPointerInfo(),
5378                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5379                            Alignment, MST->getAAInfo(), MST->getRanges());
5380
5381     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5382                             MST->isTruncatingStore());
5383
5384     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5385     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5386                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5387
5388     MMO = DAG.getMachineFunction().
5389       getMachineMemOperand(MST->getPointerInfo(),
5390                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5391                            SecondHalfAlignment, MST->getAAInfo(),
5392                            MST->getRanges());
5393
5394     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5395                             MST->isTruncatingStore());
5396
5397     AddToWorklist(Lo.getNode());
5398     AddToWorklist(Hi.getNode());
5399
5400     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5401   }
5402   return SDValue();
5403 }
5404
5405 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5406
5407   if (Level >= AfterLegalizeTypes)
5408     return SDValue();
5409
5410   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5411   SDValue Mask = MGT->getMask();
5412   SDLoc DL(N);
5413
5414   // If the MGATHER result requires splitting and the mask is provided by a
5415   // SETCC, then split both nodes and its operands before legalization. This
5416   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5417   // and enables future optimizations (e.g. min/max pattern matching on X86).
5418
5419   if (Mask.getOpcode() != ISD::SETCC)
5420     return SDValue();
5421
5422   EVT VT = N->getValueType(0);
5423
5424   // Check if any splitting is required.
5425   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5426       TargetLowering::TypeSplitVector)
5427     return SDValue();
5428
5429   SDValue MaskLo, MaskHi, Lo, Hi;
5430   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5431
5432   SDValue Src0 = MGT->getValue();
5433   SDValue Src0Lo, Src0Hi;
5434   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5435
5436   EVT LoVT, HiVT;
5437   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5438
5439   SDValue Chain = MGT->getChain();
5440   EVT MemoryVT = MGT->getMemoryVT();
5441   unsigned Alignment = MGT->getOriginalAlignment();
5442
5443   EVT LoMemVT, HiMemVT;
5444   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5445
5446   SDValue BasePtr = MGT->getBasePtr();
5447   SDValue Index = MGT->getIndex();
5448   SDValue IndexLo, IndexHi;
5449   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5450
5451   MachineMemOperand *MMO = DAG.getMachineFunction().
5452     getMachineMemOperand(MGT->getPointerInfo(),
5453                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5454                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5455
5456   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5457   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5458                             MMO);
5459
5460   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5461   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5462                             MMO);
5463
5464   AddToWorklist(Lo.getNode());
5465   AddToWorklist(Hi.getNode());
5466
5467   // Build a factor node to remember that this load is independent of the
5468   // other one.
5469   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5470                       Hi.getValue(1));
5471
5472   // Legalized the chain result - switch anything that used the old chain to
5473   // use the new one.
5474   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5475
5476   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5477
5478   SDValue RetOps[] = { GatherRes, Chain };
5479   return DAG.getMergeValues(RetOps, DL);
5480 }
5481
5482 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5483
5484   if (Level >= AfterLegalizeTypes)
5485     return SDValue();
5486
5487   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5488   SDValue Mask = MLD->getMask();
5489   SDLoc DL(N);
5490
5491   // If the MLOAD result requires splitting and the mask is provided by a
5492   // SETCC, then split both nodes and its operands before legalization. This
5493   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5494   // and enables future optimizations (e.g. min/max pattern matching on X86).
5495
5496   if (Mask.getOpcode() == ISD::SETCC) {
5497     EVT VT = N->getValueType(0);
5498
5499     // Check if any splitting is required.
5500     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5501         TargetLowering::TypeSplitVector)
5502       return SDValue();
5503
5504     SDValue MaskLo, MaskHi, Lo, Hi;
5505     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5506
5507     SDValue Src0 = MLD->getSrc0();
5508     SDValue Src0Lo, Src0Hi;
5509     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5510
5511     EVT LoVT, HiVT;
5512     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5513
5514     SDValue Chain = MLD->getChain();
5515     SDValue Ptr   = MLD->getBasePtr();
5516     EVT MemoryVT = MLD->getMemoryVT();
5517     unsigned Alignment = MLD->getOriginalAlignment();
5518
5519     // if Alignment is equal to the vector size,
5520     // take the half of it for the second part
5521     unsigned SecondHalfAlignment =
5522       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5523          Alignment/2 : Alignment;
5524
5525     EVT LoMemVT, HiMemVT;
5526     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5527
5528     MachineMemOperand *MMO = DAG.getMachineFunction().
5529     getMachineMemOperand(MLD->getPointerInfo(),
5530                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5531                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5532
5533     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5534                            ISD::NON_EXTLOAD);
5535
5536     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5537     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5538                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5539
5540     MMO = DAG.getMachineFunction().
5541     getMachineMemOperand(MLD->getPointerInfo(),
5542                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5543                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5544
5545     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5546                            ISD::NON_EXTLOAD);
5547
5548     AddToWorklist(Lo.getNode());
5549     AddToWorklist(Hi.getNode());
5550
5551     // Build a factor node to remember that this load is independent of the
5552     // other one.
5553     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5554                         Hi.getValue(1));
5555
5556     // Legalized the chain result - switch anything that used the old chain to
5557     // use the new one.
5558     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5559
5560     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5561
5562     SDValue RetOps[] = { LoadRes, Chain };
5563     return DAG.getMergeValues(RetOps, DL);
5564   }
5565   return SDValue();
5566 }
5567
5568 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5569   SDValue N0 = N->getOperand(0);
5570   SDValue N1 = N->getOperand(1);
5571   SDValue N2 = N->getOperand(2);
5572   SDLoc DL(N);
5573
5574   // Canonicalize integer abs.
5575   // vselect (setg[te] X,  0),  X, -X ->
5576   // vselect (setgt    X, -1),  X, -X ->
5577   // vselect (setl[te] X,  0), -X,  X ->
5578   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5579   if (N0.getOpcode() == ISD::SETCC) {
5580     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5581     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5582     bool isAbs = false;
5583     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5584
5585     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5586          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5587         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5588       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5589     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5590              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5591       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5592
5593     if (isAbs) {
5594       EVT VT = LHS.getValueType();
5595       SDValue Shift = DAG.getNode(
5596           ISD::SRA, DL, VT, LHS,
5597           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5598       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5599       AddToWorklist(Shift.getNode());
5600       AddToWorklist(Add.getNode());
5601       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5602     }
5603   }
5604
5605   if (SimplifySelectOps(N, N1, N2))
5606     return SDValue(N, 0);  // Don't revisit N.
5607
5608   // If the VSELECT result requires splitting and the mask is provided by a
5609   // SETCC, then split both nodes and its operands before legalization. This
5610   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5611   // and enables future optimizations (e.g. min/max pattern matching on X86).
5612   if (N0.getOpcode() == ISD::SETCC) {
5613     EVT VT = N->getValueType(0);
5614
5615     // Check if any splitting is required.
5616     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5617         TargetLowering::TypeSplitVector)
5618       return SDValue();
5619
5620     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5621     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5622     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5623     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5624
5625     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5626     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5627
5628     // Add the new VSELECT nodes to the work list in case they need to be split
5629     // again.
5630     AddToWorklist(Lo.getNode());
5631     AddToWorklist(Hi.getNode());
5632
5633     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5634   }
5635
5636   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5637   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5638     return N1;
5639   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5640   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5641     return N2;
5642
5643   // The ConvertSelectToConcatVector function is assuming both the above
5644   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5645   // and addressed.
5646   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5647       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5648       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5649     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5650       return CV;
5651   }
5652
5653   return SDValue();
5654 }
5655
5656 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5657   SDValue N0 = N->getOperand(0);
5658   SDValue N1 = N->getOperand(1);
5659   SDValue N2 = N->getOperand(2);
5660   SDValue N3 = N->getOperand(3);
5661   SDValue N4 = N->getOperand(4);
5662   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5663
5664   // fold select_cc lhs, rhs, x, x, cc -> x
5665   if (N2 == N3)
5666     return N2;
5667
5668   // Determine if the condition we're dealing with is constant
5669   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5670                               N0, N1, CC, SDLoc(N), false);
5671   if (SCC.getNode()) {
5672     AddToWorklist(SCC.getNode());
5673
5674     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5675       if (!SCCC->isNullValue())
5676         return N2;    // cond always true -> true val
5677       else
5678         return N3;    // cond always false -> false val
5679     } else if (SCC->getOpcode() == ISD::UNDEF) {
5680       // When the condition is UNDEF, just return the first operand. This is
5681       // coherent the DAG creation, no setcc node is created in this case
5682       return N2;
5683     } else if (SCC.getOpcode() == ISD::SETCC) {
5684       // Fold to a simpler select_cc
5685       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5686                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5687                          SCC.getOperand(2));
5688     }
5689   }
5690
5691   // If we can fold this based on the true/false value, do so.
5692   if (SimplifySelectOps(N, N2, N3))
5693     return SDValue(N, 0);  // Don't revisit N.
5694
5695   // fold select_cc into other things, such as min/max/abs
5696   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5697 }
5698
5699 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5700   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5701                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5702                        SDLoc(N));
5703 }
5704
5705 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5706   SDValue LHS = N->getOperand(0);
5707   SDValue RHS = N->getOperand(1);
5708   SDValue Carry = N->getOperand(2);
5709   SDValue Cond = N->getOperand(3);
5710
5711   // If Carry is false, fold to a regular SETCC.
5712   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5713     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5714
5715   return SDValue();
5716 }
5717
5718 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5719 /// a build_vector of constants.
5720 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5721 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5722 /// Vector extends are not folded if operations are legal; this is to
5723 /// avoid introducing illegal build_vector dag nodes.
5724 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5725                                          SelectionDAG &DAG, bool LegalTypes,
5726                                          bool LegalOperations) {
5727   unsigned Opcode = N->getOpcode();
5728   SDValue N0 = N->getOperand(0);
5729   EVT VT = N->getValueType(0);
5730
5731   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5732          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5733          && "Expected EXTEND dag node in input!");
5734
5735   // fold (sext c1) -> c1
5736   // fold (zext c1) -> c1
5737   // fold (aext c1) -> c1
5738   if (isa<ConstantSDNode>(N0))
5739     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5740
5741   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5742   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5743   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5744   EVT SVT = VT.getScalarType();
5745   if (!(VT.isVector() &&
5746       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5747       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5748     return nullptr;
5749
5750   // We can fold this node into a build_vector.
5751   unsigned VTBits = SVT.getSizeInBits();
5752   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5753   SmallVector<SDValue, 8> Elts;
5754   unsigned NumElts = VT.getVectorNumElements();
5755   SDLoc DL(N);
5756
5757   for (unsigned i=0; i != NumElts; ++i) {
5758     SDValue Op = N0->getOperand(i);
5759     if (Op->getOpcode() == ISD::UNDEF) {
5760       Elts.push_back(DAG.getUNDEF(SVT));
5761       continue;
5762     }
5763
5764     SDLoc DL(Op);
5765     // Get the constant value and if needed trunc it to the size of the type.
5766     // Nodes like build_vector might have constants wider than the scalar type.
5767     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5768     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5769       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5770     else
5771       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5772   }
5773
5774   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5775 }
5776
5777 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5778 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5779 // transformation. Returns true if extension are possible and the above
5780 // mentioned transformation is profitable.
5781 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5782                                     unsigned ExtOpc,
5783                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5784                                     const TargetLowering &TLI) {
5785   bool HasCopyToRegUses = false;
5786   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5787   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5788                             UE = N0.getNode()->use_end();
5789        UI != UE; ++UI) {
5790     SDNode *User = *UI;
5791     if (User == N)
5792       continue;
5793     if (UI.getUse().getResNo() != N0.getResNo())
5794       continue;
5795     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5796     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5797       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5798       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5799         // Sign bits will be lost after a zext.
5800         return false;
5801       bool Add = false;
5802       for (unsigned i = 0; i != 2; ++i) {
5803         SDValue UseOp = User->getOperand(i);
5804         if (UseOp == N0)
5805           continue;
5806         if (!isa<ConstantSDNode>(UseOp))
5807           return false;
5808         Add = true;
5809       }
5810       if (Add)
5811         ExtendNodes.push_back(User);
5812       continue;
5813     }
5814     // If truncates aren't free and there are users we can't
5815     // extend, it isn't worthwhile.
5816     if (!isTruncFree)
5817       return false;
5818     // Remember if this value is live-out.
5819     if (User->getOpcode() == ISD::CopyToReg)
5820       HasCopyToRegUses = true;
5821   }
5822
5823   if (HasCopyToRegUses) {
5824     bool BothLiveOut = false;
5825     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5826          UI != UE; ++UI) {
5827       SDUse &Use = UI.getUse();
5828       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5829         BothLiveOut = true;
5830         break;
5831       }
5832     }
5833     if (BothLiveOut)
5834       // Both unextended and extended values are live out. There had better be
5835       // a good reason for the transformation.
5836       return ExtendNodes.size();
5837   }
5838   return true;
5839 }
5840
5841 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5842                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5843                                   ISD::NodeType ExtType) {
5844   // Extend SetCC uses if necessary.
5845   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5846     SDNode *SetCC = SetCCs[i];
5847     SmallVector<SDValue, 4> Ops;
5848
5849     for (unsigned j = 0; j != 2; ++j) {
5850       SDValue SOp = SetCC->getOperand(j);
5851       if (SOp == Trunc)
5852         Ops.push_back(ExtLoad);
5853       else
5854         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5855     }
5856
5857     Ops.push_back(SetCC->getOperand(2));
5858     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5859   }
5860 }
5861
5862 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5863 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5864   SDValue N0 = N->getOperand(0);
5865   EVT DstVT = N->getValueType(0);
5866   EVT SrcVT = N0.getValueType();
5867
5868   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5869           N->getOpcode() == ISD::ZERO_EXTEND) &&
5870          "Unexpected node type (not an extend)!");
5871
5872   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5873   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5874   //   (v8i32 (sext (v8i16 (load x))))
5875   // into:
5876   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5877   //                          (v4i32 (sextload (x + 16)))))
5878   // Where uses of the original load, i.e.:
5879   //   (v8i16 (load x))
5880   // are replaced with:
5881   //   (v8i16 (truncate
5882   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5883   //                            (v4i32 (sextload (x + 16)))))))
5884   //
5885   // This combine is only applicable to illegal, but splittable, vectors.
5886   // All legal types, and illegal non-vector types, are handled elsewhere.
5887   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5888   //
5889   if (N0->getOpcode() != ISD::LOAD)
5890     return SDValue();
5891
5892   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5893
5894   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5895       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5896       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5897     return SDValue();
5898
5899   SmallVector<SDNode *, 4> SetCCs;
5900   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5901     return SDValue();
5902
5903   ISD::LoadExtType ExtType =
5904       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5905
5906   // Try to split the vector types to get down to legal types.
5907   EVT SplitSrcVT = SrcVT;
5908   EVT SplitDstVT = DstVT;
5909   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5910          SplitSrcVT.getVectorNumElements() > 1) {
5911     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5912     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5913   }
5914
5915   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5916     return SDValue();
5917
5918   SDLoc DL(N);
5919   const unsigned NumSplits =
5920       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5921   const unsigned Stride = SplitSrcVT.getStoreSize();
5922   SmallVector<SDValue, 4> Loads;
5923   SmallVector<SDValue, 4> Chains;
5924
5925   SDValue BasePtr = LN0->getBasePtr();
5926   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5927     const unsigned Offset = Idx * Stride;
5928     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5929
5930     SDValue SplitLoad = DAG.getExtLoad(
5931         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5932         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5933         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5934         Align, LN0->getAAInfo());
5935
5936     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5937                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5938
5939     Loads.push_back(SplitLoad.getValue(0));
5940     Chains.push_back(SplitLoad.getValue(1));
5941   }
5942
5943   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5944   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5945
5946   CombineTo(N, NewValue);
5947
5948   // Replace uses of the original load (before extension)
5949   // with a truncate of the concatenated sextloaded vectors.
5950   SDValue Trunc =
5951       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5952   CombineTo(N0.getNode(), Trunc, NewChain);
5953   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5954                   (ISD::NodeType)N->getOpcode());
5955   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5956 }
5957
5958 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5959   SDValue N0 = N->getOperand(0);
5960   EVT VT = N->getValueType(0);
5961
5962   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5963                                               LegalOperations))
5964     return SDValue(Res, 0);
5965
5966   // fold (sext (sext x)) -> (sext x)
5967   // fold (sext (aext x)) -> (sext x)
5968   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5969     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5970                        N0.getOperand(0));
5971
5972   if (N0.getOpcode() == ISD::TRUNCATE) {
5973     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5974     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5975     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5976       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5977       if (NarrowLoad.getNode() != N0.getNode()) {
5978         CombineTo(N0.getNode(), NarrowLoad);
5979         // CombineTo deleted the truncate, if needed, but not what's under it.
5980         AddToWorklist(oye);
5981       }
5982       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5983     }
5984
5985     // See if the value being truncated is already sign extended.  If so, just
5986     // eliminate the trunc/sext pair.
5987     SDValue Op = N0.getOperand(0);
5988     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5989     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5990     unsigned DestBits = VT.getScalarType().getSizeInBits();
5991     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5992
5993     if (OpBits == DestBits) {
5994       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5995       // bits, it is already ready.
5996       if (NumSignBits > DestBits-MidBits)
5997         return Op;
5998     } else if (OpBits < DestBits) {
5999       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6000       // bits, just sext from i32.
6001       if (NumSignBits > OpBits-MidBits)
6002         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6003     } else {
6004       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6005       // bits, just truncate to i32.
6006       if (NumSignBits > OpBits-MidBits)
6007         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6008     }
6009
6010     // fold (sext (truncate x)) -> (sextinreg x).
6011     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6012                                                  N0.getValueType())) {
6013       if (OpBits < DestBits)
6014         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6015       else if (OpBits > DestBits)
6016         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6017       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6018                          DAG.getValueType(N0.getValueType()));
6019     }
6020   }
6021
6022   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6023   // Only generate vector extloads when 1) they're legal, and 2) they are
6024   // deemed desirable by the target.
6025   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6026       ((!LegalOperations && !VT.isVector() &&
6027         !cast<LoadSDNode>(N0)->isVolatile()) ||
6028        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6029     bool DoXform = true;
6030     SmallVector<SDNode*, 4> SetCCs;
6031     if (!N0.hasOneUse())
6032       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6033     if (VT.isVector())
6034       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6035     if (DoXform) {
6036       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6037       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6038                                        LN0->getChain(),
6039                                        LN0->getBasePtr(), N0.getValueType(),
6040                                        LN0->getMemOperand());
6041       CombineTo(N, ExtLoad);
6042       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6043                                   N0.getValueType(), ExtLoad);
6044       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6045       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6046                       ISD::SIGN_EXTEND);
6047       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6048     }
6049   }
6050
6051   // fold (sext (load x)) to multiple smaller sextloads.
6052   // Only on illegal but splittable vectors.
6053   if (SDValue ExtLoad = CombineExtLoad(N))
6054     return ExtLoad;
6055
6056   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6057   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6058   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6059       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6060     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6061     EVT MemVT = LN0->getMemoryVT();
6062     if ((!LegalOperations && !LN0->isVolatile()) ||
6063         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6064       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6065                                        LN0->getChain(),
6066                                        LN0->getBasePtr(), MemVT,
6067                                        LN0->getMemOperand());
6068       CombineTo(N, ExtLoad);
6069       CombineTo(N0.getNode(),
6070                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6071                             N0.getValueType(), ExtLoad),
6072                 ExtLoad.getValue(1));
6073       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6074     }
6075   }
6076
6077   // fold (sext (and/or/xor (load x), cst)) ->
6078   //      (and/or/xor (sextload x), (sext cst))
6079   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6080        N0.getOpcode() == ISD::XOR) &&
6081       isa<LoadSDNode>(N0.getOperand(0)) &&
6082       N0.getOperand(1).getOpcode() == ISD::Constant &&
6083       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6084       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6085     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6086     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6087       bool DoXform = true;
6088       SmallVector<SDNode*, 4> SetCCs;
6089       if (!N0.hasOneUse())
6090         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6091                                           SetCCs, TLI);
6092       if (DoXform) {
6093         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6094                                          LN0->getChain(), LN0->getBasePtr(),
6095                                          LN0->getMemoryVT(),
6096                                          LN0->getMemOperand());
6097         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6098         Mask = Mask.sext(VT.getSizeInBits());
6099         SDLoc DL(N);
6100         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6101                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6102         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6103                                     SDLoc(N0.getOperand(0)),
6104                                     N0.getOperand(0).getValueType(), ExtLoad);
6105         CombineTo(N, And);
6106         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6107         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6108                         ISD::SIGN_EXTEND);
6109         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6110       }
6111     }
6112   }
6113
6114   if (N0.getOpcode() == ISD::SETCC) {
6115     EVT N0VT = N0.getOperand(0).getValueType();
6116     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6117     // Only do this before legalize for now.
6118     if (VT.isVector() && !LegalOperations &&
6119         TLI.getBooleanContents(N0VT) ==
6120             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6121       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6122       // of the same size as the compared operands. Only optimize sext(setcc())
6123       // if this is the case.
6124       EVT SVT = getSetCCResultType(N0VT);
6125
6126       // We know that the # elements of the results is the same as the
6127       // # elements of the compare (and the # elements of the compare result
6128       // for that matter).  Check to see that they are the same size.  If so,
6129       // we know that the element size of the sext'd result matches the
6130       // element size of the compare operands.
6131       if (VT.getSizeInBits() == SVT.getSizeInBits())
6132         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6133                              N0.getOperand(1),
6134                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6135
6136       // If the desired elements are smaller or larger than the source
6137       // elements we can use a matching integer vector type and then
6138       // truncate/sign extend
6139       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6140       if (SVT == MatchingVectorType) {
6141         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6142                                N0.getOperand(0), N0.getOperand(1),
6143                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6144         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6145       }
6146     }
6147
6148     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6149     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6150     SDLoc DL(N);
6151     SDValue NegOne =
6152       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6153     SDValue SCC =
6154       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6155                        NegOne, DAG.getConstant(0, DL, VT),
6156                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6157     if (SCC.getNode()) return SCC;
6158
6159     if (!VT.isVector()) {
6160       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6161       if (!LegalOperations ||
6162           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6163         SDLoc DL(N);
6164         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6165         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6166                                      N0.getOperand(0), N0.getOperand(1), CC);
6167         return DAG.getSelect(DL, VT, SetCC,
6168                              NegOne, DAG.getConstant(0, DL, VT));
6169       }
6170     }
6171   }
6172
6173   // fold (sext x) -> (zext x) if the sign bit is known zero.
6174   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6175       DAG.SignBitIsZero(N0))
6176     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6177
6178   return SDValue();
6179 }
6180
6181 // isTruncateOf - If N is a truncate of some other value, return true, record
6182 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6183 // This function computes KnownZero to avoid a duplicated call to
6184 // computeKnownBits in the caller.
6185 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6186                          APInt &KnownZero) {
6187   APInt KnownOne;
6188   if (N->getOpcode() == ISD::TRUNCATE) {
6189     Op = N->getOperand(0);
6190     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6191     return true;
6192   }
6193
6194   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6195       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6196     return false;
6197
6198   SDValue Op0 = N->getOperand(0);
6199   SDValue Op1 = N->getOperand(1);
6200   assert(Op0.getValueType() == Op1.getValueType());
6201
6202   if (isNullConstant(Op0))
6203     Op = Op1;
6204   else if (isNullConstant(Op1))
6205     Op = Op0;
6206   else
6207     return false;
6208
6209   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6210
6211   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6212     return false;
6213
6214   return true;
6215 }
6216
6217 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6218   SDValue N0 = N->getOperand(0);
6219   EVT VT = N->getValueType(0);
6220
6221   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6222                                               LegalOperations))
6223     return SDValue(Res, 0);
6224
6225   // fold (zext (zext x)) -> (zext x)
6226   // fold (zext (aext x)) -> (zext x)
6227   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6228     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6229                        N0.getOperand(0));
6230
6231   // fold (zext (truncate x)) -> (zext x) or
6232   //      (zext (truncate x)) -> (truncate x)
6233   // This is valid when the truncated bits of x are already zero.
6234   // FIXME: We should extend this to work for vectors too.
6235   SDValue Op;
6236   APInt KnownZero;
6237   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6238     APInt TruncatedBits =
6239       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6240       APInt(Op.getValueSizeInBits(), 0) :
6241       APInt::getBitsSet(Op.getValueSizeInBits(),
6242                         N0.getValueSizeInBits(),
6243                         std::min(Op.getValueSizeInBits(),
6244                                  VT.getSizeInBits()));
6245     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6246       if (VT.bitsGT(Op.getValueType()))
6247         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6248       if (VT.bitsLT(Op.getValueType()))
6249         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6250
6251       return Op;
6252     }
6253   }
6254
6255   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6256   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6257   if (N0.getOpcode() == ISD::TRUNCATE) {
6258     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6259       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6260       if (NarrowLoad.getNode() != N0.getNode()) {
6261         CombineTo(N0.getNode(), NarrowLoad);
6262         // CombineTo deleted the truncate, if needed, but not what's under it.
6263         AddToWorklist(oye);
6264       }
6265       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6266     }
6267   }
6268
6269   // fold (zext (truncate x)) -> (and x, mask)
6270   if (N0.getOpcode() == ISD::TRUNCATE) {
6271     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6272     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6273     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6274       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6275       if (NarrowLoad.getNode() != N0.getNode()) {
6276         CombineTo(N0.getNode(), NarrowLoad);
6277         // CombineTo deleted the truncate, if needed, but not what's under it.
6278         AddToWorklist(oye);
6279       }
6280       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6281     }
6282
6283     EVT SrcVT = N0.getOperand(0).getValueType();
6284     EVT MinVT = N0.getValueType();
6285
6286     // Try to mask before the extension to avoid having to generate a larger mask,
6287     // possibly over several sub-vectors.
6288     if (SrcVT.bitsLT(VT)) {
6289       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6290                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6291         SDValue Op = N0.getOperand(0);
6292         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6293         AddToWorklist(Op.getNode());
6294         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6295       }
6296     }
6297
6298     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6299       SDValue Op = N0.getOperand(0);
6300       if (SrcVT.bitsLT(VT)) {
6301         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6302         AddToWorklist(Op.getNode());
6303       } else if (SrcVT.bitsGT(VT)) {
6304         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6305         AddToWorklist(Op.getNode());
6306       }
6307       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6308     }
6309   }
6310
6311   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6312   // if either of the casts is not free.
6313   if (N0.getOpcode() == ISD::AND &&
6314       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6315       N0.getOperand(1).getOpcode() == ISD::Constant &&
6316       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6317                            N0.getValueType()) ||
6318        !TLI.isZExtFree(N0.getValueType(), VT))) {
6319     SDValue X = N0.getOperand(0).getOperand(0);
6320     if (X.getValueType().bitsLT(VT)) {
6321       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6322     } else if (X.getValueType().bitsGT(VT)) {
6323       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6324     }
6325     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6326     Mask = Mask.zext(VT.getSizeInBits());
6327     SDLoc DL(N);
6328     return DAG.getNode(ISD::AND, DL, VT,
6329                        X, DAG.getConstant(Mask, DL, VT));
6330   }
6331
6332   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6333   // Only generate vector extloads when 1) they're legal, and 2) they are
6334   // deemed desirable by the target.
6335   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6336       ((!LegalOperations && !VT.isVector() &&
6337         !cast<LoadSDNode>(N0)->isVolatile()) ||
6338        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6339     bool DoXform = true;
6340     SmallVector<SDNode*, 4> SetCCs;
6341     if (!N0.hasOneUse())
6342       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6343     if (VT.isVector())
6344       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6345     if (DoXform) {
6346       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6347       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6348                                        LN0->getChain(),
6349                                        LN0->getBasePtr(), N0.getValueType(),
6350                                        LN0->getMemOperand());
6351       CombineTo(N, ExtLoad);
6352       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6353                                   N0.getValueType(), ExtLoad);
6354       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6355
6356       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6357                       ISD::ZERO_EXTEND);
6358       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6359     }
6360   }
6361
6362   // fold (zext (load x)) to multiple smaller zextloads.
6363   // Only on illegal but splittable vectors.
6364   if (SDValue ExtLoad = CombineExtLoad(N))
6365     return ExtLoad;
6366
6367   // fold (zext (and/or/xor (load x), cst)) ->
6368   //      (and/or/xor (zextload x), (zext cst))
6369   // Unless (and (load x) cst) will match as a zextload already and has
6370   // additional users.
6371   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6372        N0.getOpcode() == ISD::XOR) &&
6373       isa<LoadSDNode>(N0.getOperand(0)) &&
6374       N0.getOperand(1).getOpcode() == ISD::Constant &&
6375       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6376       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6377     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6378     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6379       bool DoXform = true;
6380       SmallVector<SDNode*, 4> SetCCs;
6381       if (!N0.hasOneUse()) {
6382         if (N0.getOpcode() == ISD::AND) {
6383           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6384           auto NarrowLoad = false;
6385           EVT LoadResultTy = AndC->getValueType(0);
6386           EVT ExtVT, LoadedVT;
6387           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6388                                NarrowLoad))
6389             DoXform = false;
6390         }
6391         if (DoXform)
6392           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6393                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6394       }
6395       if (DoXform) {
6396         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6397                                          LN0->getChain(), LN0->getBasePtr(),
6398                                          LN0->getMemoryVT(),
6399                                          LN0->getMemOperand());
6400         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6401         Mask = Mask.zext(VT.getSizeInBits());
6402         SDLoc DL(N);
6403         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6404                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6405         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6406                                     SDLoc(N0.getOperand(0)),
6407                                     N0.getOperand(0).getValueType(), ExtLoad);
6408         CombineTo(N, And);
6409         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6410         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6411                         ISD::ZERO_EXTEND);
6412         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6413       }
6414     }
6415   }
6416
6417   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6418   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6419   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6420       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6421     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6422     EVT MemVT = LN0->getMemoryVT();
6423     if ((!LegalOperations && !LN0->isVolatile()) ||
6424         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6425       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6426                                        LN0->getChain(),
6427                                        LN0->getBasePtr(), MemVT,
6428                                        LN0->getMemOperand());
6429       CombineTo(N, ExtLoad);
6430       CombineTo(N0.getNode(),
6431                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6432                             ExtLoad),
6433                 ExtLoad.getValue(1));
6434       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6435     }
6436   }
6437
6438   if (N0.getOpcode() == ISD::SETCC) {
6439     if (!LegalOperations && VT.isVector() &&
6440         N0.getValueType().getVectorElementType() == MVT::i1) {
6441       EVT N0VT = N0.getOperand(0).getValueType();
6442       if (getSetCCResultType(N0VT) == N0.getValueType())
6443         return SDValue();
6444
6445       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6446       // Only do this before legalize for now.
6447       EVT EltVT = VT.getVectorElementType();
6448       SDLoc DL(N);
6449       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6450                                     DAG.getConstant(1, DL, EltVT));
6451       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6452         // We know that the # elements of the results is the same as the
6453         // # elements of the compare (and the # elements of the compare result
6454         // for that matter).  Check to see that they are the same size.  If so,
6455         // we know that the element size of the sext'd result matches the
6456         // element size of the compare operands.
6457         return DAG.getNode(ISD::AND, DL, VT,
6458                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6459                                          N0.getOperand(1),
6460                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6461                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6462                                        OneOps));
6463
6464       // If the desired elements are smaller or larger than the source
6465       // elements we can use a matching integer vector type and then
6466       // truncate/sign extend
6467       EVT MatchingElementType =
6468         EVT::getIntegerVT(*DAG.getContext(),
6469                           N0VT.getScalarType().getSizeInBits());
6470       EVT MatchingVectorType =
6471         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6472                          N0VT.getVectorNumElements());
6473       SDValue VsetCC =
6474         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6475                       N0.getOperand(1),
6476                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6477       return DAG.getNode(ISD::AND, DL, VT,
6478                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6479                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6480     }
6481
6482     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6483     SDLoc DL(N);
6484     SDValue SCC =
6485       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6486                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6487                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6488     if (SCC.getNode()) return SCC;
6489   }
6490
6491   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6492   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6493       isa<ConstantSDNode>(N0.getOperand(1)) &&
6494       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6495       N0.hasOneUse()) {
6496     SDValue ShAmt = N0.getOperand(1);
6497     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6498     if (N0.getOpcode() == ISD::SHL) {
6499       SDValue InnerZExt = N0.getOperand(0);
6500       // If the original shl may be shifting out bits, do not perform this
6501       // transformation.
6502       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6503         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6504       if (ShAmtVal > KnownZeroBits)
6505         return SDValue();
6506     }
6507
6508     SDLoc DL(N);
6509
6510     // Ensure that the shift amount is wide enough for the shifted value.
6511     if (VT.getSizeInBits() >= 256)
6512       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6513
6514     return DAG.getNode(N0.getOpcode(), DL, VT,
6515                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6516                        ShAmt);
6517   }
6518
6519   return SDValue();
6520 }
6521
6522 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6523   SDValue N0 = N->getOperand(0);
6524   EVT VT = N->getValueType(0);
6525
6526   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6527                                               LegalOperations))
6528     return SDValue(Res, 0);
6529
6530   // fold (aext (aext x)) -> (aext x)
6531   // fold (aext (zext x)) -> (zext x)
6532   // fold (aext (sext x)) -> (sext x)
6533   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6534       N0.getOpcode() == ISD::ZERO_EXTEND ||
6535       N0.getOpcode() == ISD::SIGN_EXTEND)
6536     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6537
6538   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6539   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6540   if (N0.getOpcode() == ISD::TRUNCATE) {
6541     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6542       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6543       if (NarrowLoad.getNode() != N0.getNode()) {
6544         CombineTo(N0.getNode(), NarrowLoad);
6545         // CombineTo deleted the truncate, if needed, but not what's under it.
6546         AddToWorklist(oye);
6547       }
6548       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6549     }
6550   }
6551
6552   // fold (aext (truncate x))
6553   if (N0.getOpcode() == ISD::TRUNCATE) {
6554     SDValue TruncOp = N0.getOperand(0);
6555     if (TruncOp.getValueType() == VT)
6556       return TruncOp; // x iff x size == zext size.
6557     if (TruncOp.getValueType().bitsGT(VT))
6558       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6559     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6560   }
6561
6562   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6563   // if the trunc is not free.
6564   if (N0.getOpcode() == ISD::AND &&
6565       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6566       N0.getOperand(1).getOpcode() == ISD::Constant &&
6567       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6568                           N0.getValueType())) {
6569     SDValue X = N0.getOperand(0).getOperand(0);
6570     if (X.getValueType().bitsLT(VT)) {
6571       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6572     } else if (X.getValueType().bitsGT(VT)) {
6573       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6574     }
6575     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6576     Mask = Mask.zext(VT.getSizeInBits());
6577     SDLoc DL(N);
6578     return DAG.getNode(ISD::AND, DL, VT,
6579                        X, DAG.getConstant(Mask, DL, VT));
6580   }
6581
6582   // fold (aext (load x)) -> (aext (truncate (extload x)))
6583   // None of the supported targets knows how to perform load and any_ext
6584   // on vectors in one instruction.  We only perform this transformation on
6585   // scalars.
6586   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6587       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6588       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6589     bool DoXform = true;
6590     SmallVector<SDNode*, 4> SetCCs;
6591     if (!N0.hasOneUse())
6592       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6593     if (DoXform) {
6594       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6595       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6596                                        LN0->getChain(),
6597                                        LN0->getBasePtr(), N0.getValueType(),
6598                                        LN0->getMemOperand());
6599       CombineTo(N, ExtLoad);
6600       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6601                                   N0.getValueType(), ExtLoad);
6602       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6603       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6604                       ISD::ANY_EXTEND);
6605       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6606     }
6607   }
6608
6609   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6610   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6611   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6612   if (N0.getOpcode() == ISD::LOAD &&
6613       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6614       N0.hasOneUse()) {
6615     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6616     ISD::LoadExtType ExtType = LN0->getExtensionType();
6617     EVT MemVT = LN0->getMemoryVT();
6618     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6619       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6620                                        VT, LN0->getChain(), LN0->getBasePtr(),
6621                                        MemVT, LN0->getMemOperand());
6622       CombineTo(N, ExtLoad);
6623       CombineTo(N0.getNode(),
6624                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6625                             N0.getValueType(), ExtLoad),
6626                 ExtLoad.getValue(1));
6627       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6628     }
6629   }
6630
6631   if (N0.getOpcode() == ISD::SETCC) {
6632     // For vectors:
6633     // aext(setcc) -> vsetcc
6634     // aext(setcc) -> truncate(vsetcc)
6635     // aext(setcc) -> aext(vsetcc)
6636     // Only do this before legalize for now.
6637     if (VT.isVector() && !LegalOperations) {
6638       EVT N0VT = N0.getOperand(0).getValueType();
6639         // We know that the # elements of the results is the same as the
6640         // # elements of the compare (and the # elements of the compare result
6641         // for that matter).  Check to see that they are the same size.  If so,
6642         // we know that the element size of the sext'd result matches the
6643         // element size of the compare operands.
6644       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6645         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6646                              N0.getOperand(1),
6647                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6648       // If the desired elements are smaller or larger than the source
6649       // elements we can use a matching integer vector type and then
6650       // truncate/any extend
6651       else {
6652         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6653         SDValue VsetCC =
6654           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6655                         N0.getOperand(1),
6656                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6657         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6658       }
6659     }
6660
6661     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6662     SDLoc DL(N);
6663     SDValue SCC =
6664       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6665                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6666                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6667     if (SCC.getNode())
6668       return SCC;
6669   }
6670
6671   return SDValue();
6672 }
6673
6674 /// See if the specified operand can be simplified with the knowledge that only
6675 /// the bits specified by Mask are used.  If so, return the simpler operand,
6676 /// otherwise return a null SDValue.
6677 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6678   switch (V.getOpcode()) {
6679   default: break;
6680   case ISD::Constant: {
6681     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6682     assert(CV && "Const value should be ConstSDNode.");
6683     const APInt &CVal = CV->getAPIntValue();
6684     APInt NewVal = CVal & Mask;
6685     if (NewVal != CVal)
6686       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6687     break;
6688   }
6689   case ISD::OR:
6690   case ISD::XOR:
6691     // If the LHS or RHS don't contribute bits to the or, drop them.
6692     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6693       return V.getOperand(1);
6694     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6695       return V.getOperand(0);
6696     break;
6697   case ISD::SRL:
6698     // Only look at single-use SRLs.
6699     if (!V.getNode()->hasOneUse())
6700       break;
6701     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6702       // See if we can recursively simplify the LHS.
6703       unsigned Amt = RHSC->getZExtValue();
6704
6705       // Watch out for shift count overflow though.
6706       if (Amt >= Mask.getBitWidth()) break;
6707       APInt NewMask = Mask << Amt;
6708       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6709         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6710                            SimplifyLHS, V.getOperand(1));
6711     }
6712   }
6713   return SDValue();
6714 }
6715
6716 /// If the result of a wider load is shifted to right of N  bits and then
6717 /// truncated to a narrower type and where N is a multiple of number of bits of
6718 /// the narrower type, transform it to a narrower load from address + N / num of
6719 /// bits of new type. If the result is to be extended, also fold the extension
6720 /// to form a extending load.
6721 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6722   unsigned Opc = N->getOpcode();
6723
6724   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6725   SDValue N0 = N->getOperand(0);
6726   EVT VT = N->getValueType(0);
6727   EVT ExtVT = VT;
6728
6729   // This transformation isn't valid for vector loads.
6730   if (VT.isVector())
6731     return SDValue();
6732
6733   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6734   // extended to VT.
6735   if (Opc == ISD::SIGN_EXTEND_INREG) {
6736     ExtType = ISD::SEXTLOAD;
6737     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6738   } else if (Opc == ISD::SRL) {
6739     // Another special-case: SRL is basically zero-extending a narrower value.
6740     ExtType = ISD::ZEXTLOAD;
6741     N0 = SDValue(N, 0);
6742     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6743     if (!N01) return SDValue();
6744     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6745                               VT.getSizeInBits() - N01->getZExtValue());
6746   }
6747   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6748     return SDValue();
6749
6750   unsigned EVTBits = ExtVT.getSizeInBits();
6751
6752   // Do not generate loads of non-round integer types since these can
6753   // be expensive (and would be wrong if the type is not byte sized).
6754   if (!ExtVT.isRound())
6755     return SDValue();
6756
6757   unsigned ShAmt = 0;
6758   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6759     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6760       ShAmt = N01->getZExtValue();
6761       // Is the shift amount a multiple of size of VT?
6762       if ((ShAmt & (EVTBits-1)) == 0) {
6763         N0 = N0.getOperand(0);
6764         // Is the load width a multiple of size of VT?
6765         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6766           return SDValue();
6767       }
6768
6769       // At this point, we must have a load or else we can't do the transform.
6770       if (!isa<LoadSDNode>(N0)) return SDValue();
6771
6772       // Because a SRL must be assumed to *need* to zero-extend the high bits
6773       // (as opposed to anyext the high bits), we can't combine the zextload
6774       // lowering of SRL and an sextload.
6775       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6776         return SDValue();
6777
6778       // If the shift amount is larger than the input type then we're not
6779       // accessing any of the loaded bytes.  If the load was a zextload/extload
6780       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6781       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6782         return SDValue();
6783     }
6784   }
6785
6786   // If the load is shifted left (and the result isn't shifted back right),
6787   // we can fold the truncate through the shift.
6788   unsigned ShLeftAmt = 0;
6789   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6790       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6791     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6792       ShLeftAmt = N01->getZExtValue();
6793       N0 = N0.getOperand(0);
6794     }
6795   }
6796
6797   // If we haven't found a load, we can't narrow it.  Don't transform one with
6798   // multiple uses, this would require adding a new load.
6799   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6800     return SDValue();
6801
6802   // Don't change the width of a volatile load.
6803   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6804   if (LN0->isVolatile())
6805     return SDValue();
6806
6807   // Verify that we are actually reducing a load width here.
6808   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6809     return SDValue();
6810
6811   // For the transform to be legal, the load must produce only two values
6812   // (the value loaded and the chain).  Don't transform a pre-increment
6813   // load, for example, which produces an extra value.  Otherwise the
6814   // transformation is not equivalent, and the downstream logic to replace
6815   // uses gets things wrong.
6816   if (LN0->getNumValues() > 2)
6817     return SDValue();
6818
6819   // If the load that we're shrinking is an extload and we're not just
6820   // discarding the extension we can't simply shrink the load. Bail.
6821   // TODO: It would be possible to merge the extensions in some cases.
6822   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6823       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6824     return SDValue();
6825
6826   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6827     return SDValue();
6828
6829   EVT PtrType = N0.getOperand(1).getValueType();
6830
6831   if (PtrType == MVT::Untyped || PtrType.isExtended())
6832     // It's not possible to generate a constant of extended or untyped type.
6833     return SDValue();
6834
6835   // For big endian targets, we need to adjust the offset to the pointer to
6836   // load the correct bytes.
6837   if (DAG.getDataLayout().isBigEndian()) {
6838     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6839     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6840     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6841   }
6842
6843   uint64_t PtrOff = ShAmt / 8;
6844   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6845   SDLoc DL(LN0);
6846   // The original load itself didn't wrap, so an offset within it doesn't.
6847   SDNodeFlags Flags;
6848   Flags.setNoUnsignedWrap(true);
6849   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6850                                PtrType, LN0->getBasePtr(),
6851                                DAG.getConstant(PtrOff, DL, PtrType),
6852                                &Flags);
6853   AddToWorklist(NewPtr.getNode());
6854
6855   SDValue Load;
6856   if (ExtType == ISD::NON_EXTLOAD)
6857     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6858                         LN0->getPointerInfo().getWithOffset(PtrOff),
6859                         LN0->isVolatile(), LN0->isNonTemporal(),
6860                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6861   else
6862     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6863                           LN0->getPointerInfo().getWithOffset(PtrOff),
6864                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6865                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6866
6867   // Replace the old load's chain with the new load's chain.
6868   WorklistRemover DeadNodes(*this);
6869   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6870
6871   // Shift the result left, if we've swallowed a left shift.
6872   SDValue Result = Load;
6873   if (ShLeftAmt != 0) {
6874     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6875     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6876       ShImmTy = VT;
6877     // If the shift amount is as large as the result size (but, presumably,
6878     // no larger than the source) then the useful bits of the result are
6879     // zero; we can't simply return the shortened shift, because the result
6880     // of that operation is undefined.
6881     SDLoc DL(N0);
6882     if (ShLeftAmt >= VT.getSizeInBits())
6883       Result = DAG.getConstant(0, DL, VT);
6884     else
6885       Result = DAG.getNode(ISD::SHL, DL, VT,
6886                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6887   }
6888
6889   // Return the new loaded value.
6890   return Result;
6891 }
6892
6893 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6894   SDValue N0 = N->getOperand(0);
6895   SDValue N1 = N->getOperand(1);
6896   EVT VT = N->getValueType(0);
6897   EVT EVT = cast<VTSDNode>(N1)->getVT();
6898   unsigned VTBits = VT.getScalarType().getSizeInBits();
6899   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6900
6901   if (N0.isUndef())
6902     return DAG.getUNDEF(VT);
6903
6904   // fold (sext_in_reg c1) -> c1
6905   if (isConstantIntBuildVectorOrConstantInt(N0))
6906     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6907
6908   // If the input is already sign extended, just drop the extension.
6909   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6910     return N0;
6911
6912   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6913   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6914       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6915     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6916                        N0.getOperand(0), N1);
6917
6918   // fold (sext_in_reg (sext x)) -> (sext x)
6919   // fold (sext_in_reg (aext x)) -> (sext x)
6920   // if x is small enough.
6921   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6922     SDValue N00 = N0.getOperand(0);
6923     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6924         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6925       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6926   }
6927
6928   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6929   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6930     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6931
6932   // fold operands of sext_in_reg based on knowledge that the top bits are not
6933   // demanded.
6934   if (SimplifyDemandedBits(SDValue(N, 0)))
6935     return SDValue(N, 0);
6936
6937   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6938   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6939   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6940     return NarrowLoad;
6941
6942   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6943   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6944   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6945   if (N0.getOpcode() == ISD::SRL) {
6946     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6947       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6948         // We can turn this into an SRA iff the input to the SRL is already sign
6949         // extended enough.
6950         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6951         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6952           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6953                              N0.getOperand(0), N0.getOperand(1));
6954       }
6955   }
6956
6957   // fold (sext_inreg (extload x)) -> (sextload x)
6958   if (ISD::isEXTLoad(N0.getNode()) &&
6959       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6960       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6961       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6962        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6963     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6964     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6965                                      LN0->getChain(),
6966                                      LN0->getBasePtr(), EVT,
6967                                      LN0->getMemOperand());
6968     CombineTo(N, ExtLoad);
6969     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6970     AddToWorklist(ExtLoad.getNode());
6971     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6972   }
6973   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6974   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6975       N0.hasOneUse() &&
6976       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6977       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6978        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6979     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6980     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6981                                      LN0->getChain(),
6982                                      LN0->getBasePtr(), EVT,
6983                                      LN0->getMemOperand());
6984     CombineTo(N, ExtLoad);
6985     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6986     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6987   }
6988
6989   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6990   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6991     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6992                                        N0.getOperand(1), false);
6993     if (BSwap.getNode())
6994       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6995                          BSwap, N1);
6996   }
6997
6998   return SDValue();
6999 }
7000
7001 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7002   SDValue N0 = N->getOperand(0);
7003   EVT VT = N->getValueType(0);
7004
7005   if (N0.getOpcode() == ISD::UNDEF)
7006     return DAG.getUNDEF(VT);
7007
7008   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7009                                               LegalOperations))
7010     return SDValue(Res, 0);
7011
7012   return SDValue();
7013 }
7014
7015 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7016   SDValue N0 = N->getOperand(0);
7017   EVT VT = N->getValueType(0);
7018   bool isLE = DAG.getDataLayout().isLittleEndian();
7019
7020   // noop truncate
7021   if (N0.getValueType() == N->getValueType(0))
7022     return N0;
7023   // fold (truncate c1) -> c1
7024   if (isConstantIntBuildVectorOrConstantInt(N0))
7025     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7026   // fold (truncate (truncate x)) -> (truncate x)
7027   if (N0.getOpcode() == ISD::TRUNCATE)
7028     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7029   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7030   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7031       N0.getOpcode() == ISD::SIGN_EXTEND ||
7032       N0.getOpcode() == ISD::ANY_EXTEND) {
7033     if (N0.getOperand(0).getValueType().bitsLT(VT))
7034       // if the source is smaller than the dest, we still need an extend
7035       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7036                          N0.getOperand(0));
7037     if (N0.getOperand(0).getValueType().bitsGT(VT))
7038       // if the source is larger than the dest, than we just need the truncate
7039       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7040     // if the source and dest are the same type, we can drop both the extend
7041     // and the truncate.
7042     return N0.getOperand(0);
7043   }
7044
7045   // Fold extract-and-trunc into a narrow extract. For example:
7046   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7047   //   i32 y = TRUNCATE(i64 x)
7048   //        -- becomes --
7049   //   v16i8 b = BITCAST (v2i64 val)
7050   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7051   //
7052   // Note: We only run this optimization after type legalization (which often
7053   // creates this pattern) and before operation legalization after which
7054   // we need to be more careful about the vector instructions that we generate.
7055   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7056       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7057
7058     EVT VecTy = N0.getOperand(0).getValueType();
7059     EVT ExTy = N0.getValueType();
7060     EVT TrTy = N->getValueType(0);
7061
7062     unsigned NumElem = VecTy.getVectorNumElements();
7063     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7064
7065     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7066     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7067
7068     SDValue EltNo = N0->getOperand(1);
7069     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7070       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7071       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7072       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7073
7074       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7075                               NVT, N0.getOperand(0));
7076
7077       SDLoc DL(N);
7078       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7079                          DL, TrTy, V,
7080                          DAG.getConstant(Index, DL, IndexTy));
7081     }
7082   }
7083
7084   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7085   if (N0.getOpcode() == ISD::SELECT) {
7086     EVT SrcVT = N0.getValueType();
7087     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7088         TLI.isTruncateFree(SrcVT, VT)) {
7089       SDLoc SL(N0);
7090       SDValue Cond = N0.getOperand(0);
7091       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7092       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7093       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7094     }
7095   }
7096
7097   // Fold a series of buildvector, bitcast, and truncate if possible.
7098   // For example fold
7099   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7100   //   (2xi32 (buildvector x, y)).
7101   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7102       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7103       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7104       N0.getOperand(0).hasOneUse()) {
7105
7106     SDValue BuildVect = N0.getOperand(0);
7107     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7108     EVT TruncVecEltTy = VT.getVectorElementType();
7109
7110     // Check that the element types match.
7111     if (BuildVectEltTy == TruncVecEltTy) {
7112       // Now we only need to compute the offset of the truncated elements.
7113       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7114       unsigned TruncVecNumElts = VT.getVectorNumElements();
7115       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7116
7117       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7118              "Invalid number of elements");
7119
7120       SmallVector<SDValue, 8> Opnds;
7121       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7122         Opnds.push_back(BuildVect.getOperand(i));
7123
7124       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7125     }
7126   }
7127
7128   // See if we can simplify the input to this truncate through knowledge that
7129   // only the low bits are being used.
7130   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7131   // Currently we only perform this optimization on scalars because vectors
7132   // may have different active low bits.
7133   if (!VT.isVector()) {
7134     SDValue Shorter =
7135       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7136                                                VT.getSizeInBits()));
7137     if (Shorter.getNode())
7138       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7139   }
7140   // fold (truncate (load x)) -> (smaller load x)
7141   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7142   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7143     if (SDValue Reduced = ReduceLoadWidth(N))
7144       return Reduced;
7145
7146     // Handle the case where the load remains an extending load even
7147     // after truncation.
7148     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7149       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7150       if (!LN0->isVolatile() &&
7151           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7152         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7153                                          VT, LN0->getChain(), LN0->getBasePtr(),
7154                                          LN0->getMemoryVT(),
7155                                          LN0->getMemOperand());
7156         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7157         return NewLoad;
7158       }
7159     }
7160   }
7161   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7162   // where ... are all 'undef'.
7163   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7164     SmallVector<EVT, 8> VTs;
7165     SDValue V;
7166     unsigned Idx = 0;
7167     unsigned NumDefs = 0;
7168
7169     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7170       SDValue X = N0.getOperand(i);
7171       if (X.getOpcode() != ISD::UNDEF) {
7172         V = X;
7173         Idx = i;
7174         NumDefs++;
7175       }
7176       // Stop if more than one members are non-undef.
7177       if (NumDefs > 1)
7178         break;
7179       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7180                                      VT.getVectorElementType(),
7181                                      X.getValueType().getVectorNumElements()));
7182     }
7183
7184     if (NumDefs == 0)
7185       return DAG.getUNDEF(VT);
7186
7187     if (NumDefs == 1) {
7188       assert(V.getNode() && "The single defined operand is empty!");
7189       SmallVector<SDValue, 8> Opnds;
7190       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7191         if (i != Idx) {
7192           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7193           continue;
7194         }
7195         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7196         AddToWorklist(NV.getNode());
7197         Opnds.push_back(NV);
7198       }
7199       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7200     }
7201   }
7202
7203   // Simplify the operands using demanded-bits information.
7204   if (!VT.isVector() &&
7205       SimplifyDemandedBits(SDValue(N, 0)))
7206     return SDValue(N, 0);
7207
7208   return SDValue();
7209 }
7210
7211 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7212   SDValue Elt = N->getOperand(i);
7213   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7214     return Elt.getNode();
7215   return Elt.getOperand(Elt.getResNo()).getNode();
7216 }
7217
7218 /// build_pair (load, load) -> load
7219 /// if load locations are consecutive.
7220 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7221   assert(N->getOpcode() == ISD::BUILD_PAIR);
7222
7223   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7224   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7225   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7226       LD1->getAddressSpace() != LD2->getAddressSpace())
7227     return SDValue();
7228   EVT LD1VT = LD1->getValueType(0);
7229
7230   if (ISD::isNON_EXTLoad(LD2) &&
7231       LD2->hasOneUse() &&
7232       // If both are volatile this would reduce the number of volatile loads.
7233       // If one is volatile it might be ok, but play conservative and bail out.
7234       !LD1->isVolatile() &&
7235       !LD2->isVolatile() &&
7236       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7237     unsigned Align = LD1->getAlignment();
7238     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7239         VT.getTypeForEVT(*DAG.getContext()));
7240
7241     if (NewAlign <= Align &&
7242         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7243       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7244                          LD1->getBasePtr(), LD1->getPointerInfo(),
7245                          false, false, false, Align);
7246   }
7247
7248   return SDValue();
7249 }
7250
7251 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7252   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7253   // and Lo parts; on big-endian machines it doesn't.
7254   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7255 }
7256
7257 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7258   SDValue N0 = N->getOperand(0);
7259   EVT VT = N->getValueType(0);
7260
7261   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7262   // Only do this before legalize, since afterward the target may be depending
7263   // on the bitconvert.
7264   // First check to see if this is all constant.
7265   if (!LegalTypes &&
7266       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7267       VT.isVector()) {
7268     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7269
7270     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7271     assert(!DestEltVT.isVector() &&
7272            "Element type of vector ValueType must not be vector!");
7273     if (isSimple)
7274       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7275   }
7276
7277   // If the input is a constant, let getNode fold it.
7278   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7279     // If we can't allow illegal operations, we need to check that this is just
7280     // a fp -> int or int -> conversion and that the resulting operation will
7281     // be legal.
7282     if (!LegalOperations ||
7283         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7284          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7285         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7286          TLI.isOperationLegal(ISD::Constant, VT)))
7287       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7288   }
7289
7290   // (conv (conv x, t1), t2) -> (conv x, t2)
7291   if (N0.getOpcode() == ISD::BITCAST)
7292     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7293                        N0.getOperand(0));
7294
7295   // fold (conv (load x)) -> (load (conv*)x)
7296   // If the resultant load doesn't need a higher alignment than the original!
7297   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7298       // Do not change the width of a volatile load.
7299       !cast<LoadSDNode>(N0)->isVolatile() &&
7300       // Do not remove the cast if the types differ in endian layout.
7301       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7302           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7303       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7304       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7305     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7306     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7307         VT.getTypeForEVT(*DAG.getContext()));
7308     unsigned OrigAlign = LN0->getAlignment();
7309
7310     if (Align <= OrigAlign) {
7311       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7312                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7313                                  LN0->isVolatile(), LN0->isNonTemporal(),
7314                                  LN0->isInvariant(), OrigAlign,
7315                                  LN0->getAAInfo());
7316       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7317       return Load;
7318     }
7319   }
7320
7321   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7322   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7323   //
7324   // For ppc_fp128:
7325   // fold (bitcast (fneg x)) ->
7326   //     flipbit = signbit
7327   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7328   // fold (bitcast (fabs x)) ->
7329   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7330   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7331   // This often reduces constant pool loads.
7332   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7333        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7334       N0.getNode()->hasOneUse() && VT.isInteger() &&
7335       !VT.isVector() && !N0.getValueType().isVector()) {
7336     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7337                                   N0.getOperand(0));
7338     AddToWorklist(NewConv.getNode());
7339
7340     SDLoc DL(N);
7341     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7342       assert(VT.getSizeInBits() == 128);
7343       SDValue SignBit = DAG.getConstant(
7344           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7345       SDValue FlipBit;
7346       if (N0.getOpcode() == ISD::FNEG) {
7347         FlipBit = SignBit;
7348         AddToWorklist(FlipBit.getNode());
7349       } else {
7350         assert(N0.getOpcode() == ISD::FABS);
7351         SDValue Hi =
7352             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7353                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7354                                               SDLoc(NewConv)));
7355         AddToWorklist(Hi.getNode());
7356         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7357         AddToWorklist(FlipBit.getNode());
7358       }
7359       SDValue FlipBits =
7360           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7361       AddToWorklist(FlipBits.getNode());
7362       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7363     }
7364     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7365     if (N0.getOpcode() == ISD::FNEG)
7366       return DAG.getNode(ISD::XOR, DL, VT,
7367                          NewConv, DAG.getConstant(SignBit, DL, VT));
7368     assert(N0.getOpcode() == ISD::FABS);
7369     return DAG.getNode(ISD::AND, DL, VT,
7370                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7371   }
7372
7373   // fold (bitconvert (fcopysign cst, x)) ->
7374   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7375   // Note that we don't handle (copysign x, cst) because this can always be
7376   // folded to an fneg or fabs.
7377   //
7378   // For ppc_fp128:
7379   // fold (bitcast (fcopysign cst, x)) ->
7380   //     flipbit = (and (extract_element
7381   //                     (xor (bitcast cst), (bitcast x)), 0),
7382   //                    signbit)
7383   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7384   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7385       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7386       VT.isInteger() && !VT.isVector()) {
7387     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7388     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7389     if (isTypeLegal(IntXVT)) {
7390       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7391                               IntXVT, N0.getOperand(1));
7392       AddToWorklist(X.getNode());
7393
7394       // If X has a different width than the result/lhs, sext it or truncate it.
7395       unsigned VTWidth = VT.getSizeInBits();
7396       if (OrigXWidth < VTWidth) {
7397         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7398         AddToWorklist(X.getNode());
7399       } else if (OrigXWidth > VTWidth) {
7400         // To get the sign bit in the right place, we have to shift it right
7401         // before truncating.
7402         SDLoc DL(X);
7403         X = DAG.getNode(ISD::SRL, DL,
7404                         X.getValueType(), X,
7405                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7406                                         X.getValueType()));
7407         AddToWorklist(X.getNode());
7408         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7409         AddToWorklist(X.getNode());
7410       }
7411
7412       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7413         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7414         SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(0)), VT,
7415                                   N0.getOperand(0));
7416         AddToWorklist(Cst.getNode());
7417         SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0.getOperand(1)), VT,
7418                                 N0.getOperand(1));
7419         AddToWorklist(X.getNode());
7420         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7421         AddToWorklist(XorResult.getNode());
7422         SDValue XorResult64 = DAG.getNode(
7423             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7424             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7425                                   SDLoc(XorResult)));
7426         AddToWorklist(XorResult64.getNode());
7427         SDValue FlipBit =
7428             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7429                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7430         AddToWorklist(FlipBit.getNode());
7431         SDValue FlipBits =
7432             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7433         AddToWorklist(FlipBits.getNode());
7434         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7435       }
7436       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7437       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7438                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7439       AddToWorklist(X.getNode());
7440
7441       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7442                                 VT, N0.getOperand(0));
7443       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7444                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7445       AddToWorklist(Cst.getNode());
7446
7447       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7448     }
7449   }
7450
7451   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7452   if (N0.getOpcode() == ISD::BUILD_PAIR)
7453     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7454       return CombineLD;
7455
7456   // Remove double bitcasts from shuffles - this is often a legacy of
7457   // XformToShuffleWithZero being used to combine bitmaskings (of
7458   // float vectors bitcast to integer vectors) into shuffles.
7459   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7460   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7461       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7462       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7463       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7464     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7465
7466     // If operands are a bitcast, peek through if it casts the original VT.
7467     // If operands are a constant, just bitcast back to original VT.
7468     auto PeekThroughBitcast = [&](SDValue Op) {
7469       if (Op.getOpcode() == ISD::BITCAST &&
7470           Op.getOperand(0).getValueType() == VT)
7471         return SDValue(Op.getOperand(0));
7472       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7473           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7474         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7475       return SDValue();
7476     };
7477
7478     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7479     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7480     if (!(SV0 && SV1))
7481       return SDValue();
7482
7483     int MaskScale =
7484         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7485     SmallVector<int, 8> NewMask;
7486     for (int M : SVN->getMask())
7487       for (int i = 0; i != MaskScale; ++i)
7488         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7489
7490     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7491     if (!LegalMask) {
7492       std::swap(SV0, SV1);
7493       ShuffleVectorSDNode::commuteMask(NewMask);
7494       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7495     }
7496
7497     if (LegalMask)
7498       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7499   }
7500
7501   return SDValue();
7502 }
7503
7504 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7505   EVT VT = N->getValueType(0);
7506   return CombineConsecutiveLoads(N, VT);
7507 }
7508
7509 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7510 /// operands. DstEltVT indicates the destination element value type.
7511 SDValue DAGCombiner::
7512 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7513   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7514
7515   // If this is already the right type, we're done.
7516   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7517
7518   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7519   unsigned DstBitSize = DstEltVT.getSizeInBits();
7520
7521   // If this is a conversion of N elements of one type to N elements of another
7522   // type, convert each element.  This handles FP<->INT cases.
7523   if (SrcBitSize == DstBitSize) {
7524     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7525                               BV->getValueType(0).getVectorNumElements());
7526
7527     // Due to the FP element handling below calling this routine recursively,
7528     // we can end up with a scalar-to-vector node here.
7529     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7530       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7531                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7532                                      DstEltVT, BV->getOperand(0)));
7533
7534     SmallVector<SDValue, 8> Ops;
7535     for (SDValue Op : BV->op_values()) {
7536       // If the vector element type is not legal, the BUILD_VECTOR operands
7537       // are promoted and implicitly truncated.  Make that explicit here.
7538       if (Op.getValueType() != SrcEltVT)
7539         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7540       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7541                                 DstEltVT, Op));
7542       AddToWorklist(Ops.back().getNode());
7543     }
7544     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7545   }
7546
7547   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7548   // handle annoying details of growing/shrinking FP values, we convert them to
7549   // int first.
7550   if (SrcEltVT.isFloatingPoint()) {
7551     // Convert the input float vector to a int vector where the elements are the
7552     // same sizes.
7553     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7554     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7555     SrcEltVT = IntVT;
7556   }
7557
7558   // Now we know the input is an integer vector.  If the output is a FP type,
7559   // convert to integer first, then to FP of the right size.
7560   if (DstEltVT.isFloatingPoint()) {
7561     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7562     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7563
7564     // Next, convert to FP elements of the same size.
7565     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7566   }
7567
7568   SDLoc DL(BV);
7569
7570   // Okay, we know the src/dst types are both integers of differing types.
7571   // Handling growing first.
7572   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7573   if (SrcBitSize < DstBitSize) {
7574     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7575
7576     SmallVector<SDValue, 8> Ops;
7577     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7578          i += NumInputsPerOutput) {
7579       bool isLE = DAG.getDataLayout().isLittleEndian();
7580       APInt NewBits = APInt(DstBitSize, 0);
7581       bool EltIsUndef = true;
7582       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7583         // Shift the previously computed bits over.
7584         NewBits <<= SrcBitSize;
7585         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7586         if (Op.getOpcode() == ISD::UNDEF) continue;
7587         EltIsUndef = false;
7588
7589         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7590                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7591       }
7592
7593       if (EltIsUndef)
7594         Ops.push_back(DAG.getUNDEF(DstEltVT));
7595       else
7596         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7597     }
7598
7599     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7600     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7601   }
7602
7603   // Finally, this must be the case where we are shrinking elements: each input
7604   // turns into multiple outputs.
7605   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7606   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7607                             NumOutputsPerInput*BV->getNumOperands());
7608   SmallVector<SDValue, 8> Ops;
7609
7610   for (const SDValue &Op : BV->op_values()) {
7611     if (Op.getOpcode() == ISD::UNDEF) {
7612       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7613       continue;
7614     }
7615
7616     APInt OpVal = cast<ConstantSDNode>(Op)->
7617                   getAPIntValue().zextOrTrunc(SrcBitSize);
7618
7619     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7620       APInt ThisVal = OpVal.trunc(DstBitSize);
7621       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7622       OpVal = OpVal.lshr(DstBitSize);
7623     }
7624
7625     // For big endian targets, swap the order of the pieces of each element.
7626     if (DAG.getDataLayout().isBigEndian())
7627       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7628   }
7629
7630   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7631 }
7632
7633 /// Try to perform FMA combining on a given FADD node.
7634 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7635   SDValue N0 = N->getOperand(0);
7636   SDValue N1 = N->getOperand(1);
7637   EVT VT = N->getValueType(0);
7638   SDLoc SL(N);
7639
7640   const TargetOptions &Options = DAG.getTarget().Options;
7641   bool AllowFusion =
7642       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7643
7644   // Floating-point multiply-add with intermediate rounding.
7645   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7646
7647   // Floating-point multiply-add without intermediate rounding.
7648   bool HasFMA =
7649       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7650       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7651
7652   // No valid opcode, do not combine.
7653   if (!HasFMAD && !HasFMA)
7654     return SDValue();
7655
7656   // Always prefer FMAD to FMA for precision.
7657   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7658   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7659   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7660
7661   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7662   // prefer to fold the multiply with fewer uses.
7663   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7664       N1.getOpcode() == ISD::FMUL) {
7665     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7666       std::swap(N0, N1);
7667   }
7668
7669   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7670   if (N0.getOpcode() == ISD::FMUL &&
7671       (Aggressive || N0->hasOneUse())) {
7672     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7673                        N0.getOperand(0), N0.getOperand(1), N1);
7674   }
7675
7676   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7677   // Note: Commutes FADD operands.
7678   if (N1.getOpcode() == ISD::FMUL &&
7679       (Aggressive || N1->hasOneUse())) {
7680     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7681                        N1.getOperand(0), N1.getOperand(1), N0);
7682   }
7683
7684   // Look through FP_EXTEND nodes to do more combining.
7685   if (AllowFusion && LookThroughFPExt) {
7686     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7687     if (N0.getOpcode() == ISD::FP_EXTEND) {
7688       SDValue N00 = N0.getOperand(0);
7689       if (N00.getOpcode() == ISD::FMUL)
7690         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7691                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7692                                        N00.getOperand(0)),
7693                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7694                                        N00.getOperand(1)), N1);
7695     }
7696
7697     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7698     // Note: Commutes FADD operands.
7699     if (N1.getOpcode() == ISD::FP_EXTEND) {
7700       SDValue N10 = N1.getOperand(0);
7701       if (N10.getOpcode() == ISD::FMUL)
7702         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7703                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7704                                        N10.getOperand(0)),
7705                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706                                        N10.getOperand(1)), N0);
7707     }
7708   }
7709
7710   // More folding opportunities when target permits.
7711   if ((AllowFusion || HasFMAD)  && Aggressive) {
7712     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7713     if (N0.getOpcode() == PreferredFusedOpcode &&
7714         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7715       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7716                          N0.getOperand(0), N0.getOperand(1),
7717                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7718                                      N0.getOperand(2).getOperand(0),
7719                                      N0.getOperand(2).getOperand(1),
7720                                      N1));
7721     }
7722
7723     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7724     if (N1->getOpcode() == PreferredFusedOpcode &&
7725         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7726       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7727                          N1.getOperand(0), N1.getOperand(1),
7728                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7729                                      N1.getOperand(2).getOperand(0),
7730                                      N1.getOperand(2).getOperand(1),
7731                                      N0));
7732     }
7733
7734     if (AllowFusion && LookThroughFPExt) {
7735       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7736       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7737       auto FoldFAddFMAFPExtFMul = [&] (
7738           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7739         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7740                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7741                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7742                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7743                                        Z));
7744       };
7745       if (N0.getOpcode() == PreferredFusedOpcode) {
7746         SDValue N02 = N0.getOperand(2);
7747         if (N02.getOpcode() == ISD::FP_EXTEND) {
7748           SDValue N020 = N02.getOperand(0);
7749           if (N020.getOpcode() == ISD::FMUL)
7750             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7751                                         N020.getOperand(0), N020.getOperand(1),
7752                                         N1);
7753         }
7754       }
7755
7756       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7757       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7758       // FIXME: This turns two single-precision and one double-precision
7759       // operation into two double-precision operations, which might not be
7760       // interesting for all targets, especially GPUs.
7761       auto FoldFAddFPExtFMAFMul = [&] (
7762           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7763         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7765                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7766                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7767                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7768                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7769                                        Z));
7770       };
7771       if (N0.getOpcode() == ISD::FP_EXTEND) {
7772         SDValue N00 = N0.getOperand(0);
7773         if (N00.getOpcode() == PreferredFusedOpcode) {
7774           SDValue N002 = N00.getOperand(2);
7775           if (N002.getOpcode() == ISD::FMUL)
7776             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7777                                         N002.getOperand(0), N002.getOperand(1),
7778                                         N1);
7779         }
7780       }
7781
7782       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7783       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7784       if (N1.getOpcode() == PreferredFusedOpcode) {
7785         SDValue N12 = N1.getOperand(2);
7786         if (N12.getOpcode() == ISD::FP_EXTEND) {
7787           SDValue N120 = N12.getOperand(0);
7788           if (N120.getOpcode() == ISD::FMUL)
7789             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7790                                         N120.getOperand(0), N120.getOperand(1),
7791                                         N0);
7792         }
7793       }
7794
7795       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7796       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7797       // FIXME: This turns two single-precision and one double-precision
7798       // operation into two double-precision operations, which might not be
7799       // interesting for all targets, especially GPUs.
7800       if (N1.getOpcode() == ISD::FP_EXTEND) {
7801         SDValue N10 = N1.getOperand(0);
7802         if (N10.getOpcode() == PreferredFusedOpcode) {
7803           SDValue N102 = N10.getOperand(2);
7804           if (N102.getOpcode() == ISD::FMUL)
7805             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7806                                         N102.getOperand(0), N102.getOperand(1),
7807                                         N0);
7808         }
7809       }
7810     }
7811   }
7812
7813   return SDValue();
7814 }
7815
7816 /// Try to perform FMA combining on a given FSUB node.
7817 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7818   SDValue N0 = N->getOperand(0);
7819   SDValue N1 = N->getOperand(1);
7820   EVT VT = N->getValueType(0);
7821   SDLoc SL(N);
7822
7823   const TargetOptions &Options = DAG.getTarget().Options;
7824   bool AllowFusion =
7825       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7826
7827   // Floating-point multiply-add with intermediate rounding.
7828   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7829
7830   // Floating-point multiply-add without intermediate rounding.
7831   bool HasFMA =
7832       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7833       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7834
7835   // No valid opcode, do not combine.
7836   if (!HasFMAD && !HasFMA)
7837     return SDValue();
7838
7839   // Always prefer FMAD to FMA for precision.
7840   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7841   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7842   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7843
7844   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7845   if (N0.getOpcode() == ISD::FMUL &&
7846       (Aggressive || N0->hasOneUse())) {
7847     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7848                        N0.getOperand(0), N0.getOperand(1),
7849                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7850   }
7851
7852   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7853   // Note: Commutes FSUB operands.
7854   if (N1.getOpcode() == ISD::FMUL &&
7855       (Aggressive || N1->hasOneUse()))
7856     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7857                        DAG.getNode(ISD::FNEG, SL, VT,
7858                                    N1.getOperand(0)),
7859                        N1.getOperand(1), N0);
7860
7861   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7862   if (N0.getOpcode() == ISD::FNEG &&
7863       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7864       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7865     SDValue N00 = N0.getOperand(0).getOperand(0);
7866     SDValue N01 = N0.getOperand(0).getOperand(1);
7867     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7868                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7869                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7870   }
7871
7872   // Look through FP_EXTEND nodes to do more combining.
7873   if (AllowFusion && LookThroughFPExt) {
7874     // fold (fsub (fpext (fmul x, y)), z)
7875     //   -> (fma (fpext x), (fpext y), (fneg z))
7876     if (N0.getOpcode() == ISD::FP_EXTEND) {
7877       SDValue N00 = N0.getOperand(0);
7878       if (N00.getOpcode() == ISD::FMUL)
7879         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7880                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7881                                        N00.getOperand(0)),
7882                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7883                                        N00.getOperand(1)),
7884                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7885     }
7886
7887     // fold (fsub x, (fpext (fmul y, z)))
7888     //   -> (fma (fneg (fpext y)), (fpext z), x)
7889     // Note: Commutes FSUB operands.
7890     if (N1.getOpcode() == ISD::FP_EXTEND) {
7891       SDValue N10 = N1.getOperand(0);
7892       if (N10.getOpcode() == ISD::FMUL)
7893         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7894                            DAG.getNode(ISD::FNEG, SL, VT,
7895                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7896                                                    N10.getOperand(0))),
7897                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7898                                        N10.getOperand(1)),
7899                            N0);
7900     }
7901
7902     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7903     //   -> (fneg (fma (fpext x), (fpext y), z))
7904     // Note: This could be removed with appropriate canonicalization of the
7905     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7906     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7907     // from implementing the canonicalization in visitFSUB.
7908     if (N0.getOpcode() == ISD::FP_EXTEND) {
7909       SDValue N00 = N0.getOperand(0);
7910       if (N00.getOpcode() == ISD::FNEG) {
7911         SDValue N000 = N00.getOperand(0);
7912         if (N000.getOpcode() == ISD::FMUL) {
7913           return DAG.getNode(ISD::FNEG, SL, VT,
7914                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7915                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7916                                                      N000.getOperand(0)),
7917                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7918                                                      N000.getOperand(1)),
7919                                          N1));
7920         }
7921       }
7922     }
7923
7924     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7925     //   -> (fneg (fma (fpext x)), (fpext y), z)
7926     // Note: This could be removed with appropriate canonicalization of the
7927     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7928     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7929     // from implementing the canonicalization in visitFSUB.
7930     if (N0.getOpcode() == ISD::FNEG) {
7931       SDValue N00 = N0.getOperand(0);
7932       if (N00.getOpcode() == ISD::FP_EXTEND) {
7933         SDValue N000 = N00.getOperand(0);
7934         if (N000.getOpcode() == ISD::FMUL) {
7935           return DAG.getNode(ISD::FNEG, SL, VT,
7936                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7937                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7938                                                      N000.getOperand(0)),
7939                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7940                                                      N000.getOperand(1)),
7941                                          N1));
7942         }
7943       }
7944     }
7945
7946   }
7947
7948   // More folding opportunities when target permits.
7949   if ((AllowFusion || HasFMAD) && Aggressive) {
7950     // fold (fsub (fma x, y, (fmul u, v)), z)
7951     //   -> (fma x, y (fma u, v, (fneg z)))
7952     if (N0.getOpcode() == PreferredFusedOpcode &&
7953         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7954       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7955                          N0.getOperand(0), N0.getOperand(1),
7956                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7957                                      N0.getOperand(2).getOperand(0),
7958                                      N0.getOperand(2).getOperand(1),
7959                                      DAG.getNode(ISD::FNEG, SL, VT,
7960                                                  N1)));
7961     }
7962
7963     // fold (fsub x, (fma y, z, (fmul u, v)))
7964     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7965     if (N1.getOpcode() == PreferredFusedOpcode &&
7966         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7967       SDValue N20 = N1.getOperand(2).getOperand(0);
7968       SDValue N21 = N1.getOperand(2).getOperand(1);
7969       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7970                          DAG.getNode(ISD::FNEG, SL, VT,
7971                                      N1.getOperand(0)),
7972                          N1.getOperand(1),
7973                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7974                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7975
7976                                      N21, N0));
7977     }
7978
7979     if (AllowFusion && LookThroughFPExt) {
7980       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7981       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7982       if (N0.getOpcode() == PreferredFusedOpcode) {
7983         SDValue N02 = N0.getOperand(2);
7984         if (N02.getOpcode() == ISD::FP_EXTEND) {
7985           SDValue N020 = N02.getOperand(0);
7986           if (N020.getOpcode() == ISD::FMUL)
7987             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7988                                N0.getOperand(0), N0.getOperand(1),
7989                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7990                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7991                                                        N020.getOperand(0)),
7992                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7993                                                        N020.getOperand(1)),
7994                                            DAG.getNode(ISD::FNEG, SL, VT,
7995                                                        N1)));
7996         }
7997       }
7998
7999       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8000       //   -> (fma (fpext x), (fpext y),
8001       //           (fma (fpext u), (fpext v), (fneg z)))
8002       // FIXME: This turns two single-precision and one double-precision
8003       // operation into two double-precision operations, which might not be
8004       // interesting for all targets, especially GPUs.
8005       if (N0.getOpcode() == ISD::FP_EXTEND) {
8006         SDValue N00 = N0.getOperand(0);
8007         if (N00.getOpcode() == PreferredFusedOpcode) {
8008           SDValue N002 = N00.getOperand(2);
8009           if (N002.getOpcode() == ISD::FMUL)
8010             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8011                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8012                                            N00.getOperand(0)),
8013                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8014                                            N00.getOperand(1)),
8015                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8016                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8017                                                        N002.getOperand(0)),
8018                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8019                                                        N002.getOperand(1)),
8020                                            DAG.getNode(ISD::FNEG, SL, VT,
8021                                                        N1)));
8022         }
8023       }
8024
8025       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8026       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8027       if (N1.getOpcode() == PreferredFusedOpcode &&
8028         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8029         SDValue N120 = N1.getOperand(2).getOperand(0);
8030         if (N120.getOpcode() == ISD::FMUL) {
8031           SDValue N1200 = N120.getOperand(0);
8032           SDValue N1201 = N120.getOperand(1);
8033           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8034                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8035                              N1.getOperand(1),
8036                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8037                                          DAG.getNode(ISD::FNEG, SL, VT,
8038                                              DAG.getNode(ISD::FP_EXTEND, SL,
8039                                                          VT, N1200)),
8040                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8041                                                      N1201),
8042                                          N0));
8043         }
8044       }
8045
8046       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8047       //   -> (fma (fneg (fpext y)), (fpext z),
8048       //           (fma (fneg (fpext u)), (fpext v), x))
8049       // FIXME: This turns two single-precision and one double-precision
8050       // operation into two double-precision operations, which might not be
8051       // interesting for all targets, especially GPUs.
8052       if (N1.getOpcode() == ISD::FP_EXTEND &&
8053         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8054         SDValue N100 = N1.getOperand(0).getOperand(0);
8055         SDValue N101 = N1.getOperand(0).getOperand(1);
8056         SDValue N102 = N1.getOperand(0).getOperand(2);
8057         if (N102.getOpcode() == ISD::FMUL) {
8058           SDValue N1020 = N102.getOperand(0);
8059           SDValue N1021 = N102.getOperand(1);
8060           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8061                              DAG.getNode(ISD::FNEG, SL, VT,
8062                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8063                                                      N100)),
8064                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8065                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8066                                          DAG.getNode(ISD::FNEG, SL, VT,
8067                                              DAG.getNode(ISD::FP_EXTEND, SL,
8068                                                          VT, N1020)),
8069                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8070                                                      N1021),
8071                                          N0));
8072         }
8073       }
8074     }
8075   }
8076
8077   return SDValue();
8078 }
8079
8080 /// Try to perform FMA combining on a given FMUL node.
8081 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8082   SDValue N0 = N->getOperand(0);
8083   SDValue N1 = N->getOperand(1);
8084   EVT VT = N->getValueType(0);
8085   SDLoc SL(N);
8086
8087   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8088
8089   const TargetOptions &Options = DAG.getTarget().Options;
8090   bool AllowFusion =
8091       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8092
8093   // Floating-point multiply-add with intermediate rounding.
8094   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8095
8096   // Floating-point multiply-add without intermediate rounding.
8097   bool HasFMA =
8098       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8099       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8100
8101   // No valid opcode, do not combine.
8102   if (!HasFMAD && !HasFMA)
8103     return SDValue();
8104
8105   // Always prefer FMAD to FMA for precision.
8106   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8107   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8108
8109   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8110   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8111   auto FuseFADD = [&](SDValue X, SDValue Y) {
8112     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8113       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8114       if (XC1 && XC1->isExactlyValue(+1.0))
8115         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8116       if (XC1 && XC1->isExactlyValue(-1.0))
8117         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8118                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8119     }
8120     return SDValue();
8121   };
8122
8123   if (SDValue FMA = FuseFADD(N0, N1))
8124     return FMA;
8125   if (SDValue FMA = FuseFADD(N1, N0))
8126     return FMA;
8127
8128   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8129   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8130   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8131   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8132   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8133     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8134       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8135       if (XC0 && XC0->isExactlyValue(+1.0))
8136         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8137                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8138                            Y);
8139       if (XC0 && XC0->isExactlyValue(-1.0))
8140         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8141                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8142                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8143
8144       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8145       if (XC1 && XC1->isExactlyValue(+1.0))
8146         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8147                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8148       if (XC1 && XC1->isExactlyValue(-1.0))
8149         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8150     }
8151     return SDValue();
8152   };
8153
8154   if (SDValue FMA = FuseFSUB(N0, N1))
8155     return FMA;
8156   if (SDValue FMA = FuseFSUB(N1, N0))
8157     return FMA;
8158
8159   return SDValue();
8160 }
8161
8162 SDValue DAGCombiner::visitFADD(SDNode *N) {
8163   SDValue N0 = N->getOperand(0);
8164   SDValue N1 = N->getOperand(1);
8165   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8166   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8167   EVT VT = N->getValueType(0);
8168   SDLoc DL(N);
8169   const TargetOptions &Options = DAG.getTarget().Options;
8170   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8171
8172   // fold vector ops
8173   if (VT.isVector())
8174     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8175       return FoldedVOp;
8176
8177   // fold (fadd c1, c2) -> c1 + c2
8178   if (N0CFP && N1CFP)
8179     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8180
8181   // canonicalize constant to RHS
8182   if (N0CFP && !N1CFP)
8183     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8184
8185   // fold (fadd A, (fneg B)) -> (fsub A, B)
8186   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8187       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8188     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8189                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8190
8191   // fold (fadd (fneg A), B) -> (fsub B, A)
8192   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8193       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8194     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8195                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8196
8197   // If 'unsafe math' is enabled, fold lots of things.
8198   if (Options.UnsafeFPMath) {
8199     // No FP constant should be created after legalization as Instruction
8200     // Selection pass has a hard time dealing with FP constants.
8201     bool AllowNewConst = (Level < AfterLegalizeDAG);
8202
8203     // fold (fadd A, 0) -> A
8204     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8205       if (N1C->isZero())
8206         return N0;
8207
8208     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8209     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8210         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8211       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8212                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8213                                      Flags),
8214                          Flags);
8215
8216     // If allowed, fold (fadd (fneg x), x) -> 0.0
8217     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8218       return DAG.getConstantFP(0.0, DL, VT);
8219
8220     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8221     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8222       return DAG.getConstantFP(0.0, DL, VT);
8223
8224     // We can fold chains of FADD's of the same value into multiplications.
8225     // This transform is not safe in general because we are reducing the number
8226     // of rounding steps.
8227     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8228       if (N0.getOpcode() == ISD::FMUL) {
8229         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8230         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8231
8232         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8233         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8234           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8235                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8236           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8237         }
8238
8239         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8240         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8241             N1.getOperand(0) == N1.getOperand(1) &&
8242             N0.getOperand(0) == N1.getOperand(0)) {
8243           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8244                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8245           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8246         }
8247       }
8248
8249       if (N1.getOpcode() == ISD::FMUL) {
8250         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8251         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8252
8253         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8254         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8255           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8256                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8257           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8258         }
8259
8260         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8261         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8262             N0.getOperand(0) == N0.getOperand(1) &&
8263             N1.getOperand(0) == N0.getOperand(0)) {
8264           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8265                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8266           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8267         }
8268       }
8269
8270       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8271         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8272         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8273         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8274             (N0.getOperand(0) == N1)) {
8275           return DAG.getNode(ISD::FMUL, DL, VT,
8276                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8277         }
8278       }
8279
8280       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8281         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8282         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8283         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8284             N1.getOperand(0) == N0) {
8285           return DAG.getNode(ISD::FMUL, DL, VT,
8286                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8287         }
8288       }
8289
8290       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8291       if (AllowNewConst &&
8292           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8293           N0.getOperand(0) == N0.getOperand(1) &&
8294           N1.getOperand(0) == N1.getOperand(1) &&
8295           N0.getOperand(0) == N1.getOperand(0)) {
8296         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8297                            DAG.getConstantFP(4.0, DL, VT), Flags);
8298       }
8299     }
8300   } // enable-unsafe-fp-math
8301
8302   // FADD -> FMA combines:
8303   if (SDValue Fused = visitFADDForFMACombine(N)) {
8304     AddToWorklist(Fused.getNode());
8305     return Fused;
8306   }
8307
8308   return SDValue();
8309 }
8310
8311 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8312   SDValue N0 = N->getOperand(0);
8313   SDValue N1 = N->getOperand(1);
8314   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8315   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8316   EVT VT = N->getValueType(0);
8317   SDLoc dl(N);
8318   const TargetOptions &Options = DAG.getTarget().Options;
8319   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8320
8321   // fold vector ops
8322   if (VT.isVector())
8323     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8324       return FoldedVOp;
8325
8326   // fold (fsub c1, c2) -> c1-c2
8327   if (N0CFP && N1CFP)
8328     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8329
8330   // fold (fsub A, (fneg B)) -> (fadd A, B)
8331   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8332     return DAG.getNode(ISD::FADD, dl, VT, N0,
8333                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8334
8335   // If 'unsafe math' is enabled, fold lots of things.
8336   if (Options.UnsafeFPMath) {
8337     // (fsub A, 0) -> A
8338     if (N1CFP && N1CFP->isZero())
8339       return N0;
8340
8341     // (fsub 0, B) -> -B
8342     if (N0CFP && N0CFP->isZero()) {
8343       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8344         return GetNegatedExpression(N1, DAG, LegalOperations);
8345       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8346         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8347     }
8348
8349     // (fsub x, x) -> 0.0
8350     if (N0 == N1)
8351       return DAG.getConstantFP(0.0f, dl, VT);
8352
8353     // (fsub x, (fadd x, y)) -> (fneg y)
8354     // (fsub x, (fadd y, x)) -> (fneg y)
8355     if (N1.getOpcode() == ISD::FADD) {
8356       SDValue N10 = N1->getOperand(0);
8357       SDValue N11 = N1->getOperand(1);
8358
8359       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8360         return GetNegatedExpression(N11, DAG, LegalOperations);
8361
8362       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8363         return GetNegatedExpression(N10, DAG, LegalOperations);
8364     }
8365   }
8366
8367   // FSUB -> FMA combines:
8368   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8369     AddToWorklist(Fused.getNode());
8370     return Fused;
8371   }
8372
8373   return SDValue();
8374 }
8375
8376 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8377   SDValue N0 = N->getOperand(0);
8378   SDValue N1 = N->getOperand(1);
8379   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8380   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8381   EVT VT = N->getValueType(0);
8382   SDLoc DL(N);
8383   const TargetOptions &Options = DAG.getTarget().Options;
8384   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8385
8386   // fold vector ops
8387   if (VT.isVector()) {
8388     // This just handles C1 * C2 for vectors. Other vector folds are below.
8389     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8390       return FoldedVOp;
8391   }
8392
8393   // fold (fmul c1, c2) -> c1*c2
8394   if (N0CFP && N1CFP)
8395     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8396
8397   // canonicalize constant to RHS
8398   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8399      !isConstantFPBuildVectorOrConstantFP(N1))
8400     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8401
8402   // fold (fmul A, 1.0) -> A
8403   if (N1CFP && N1CFP->isExactlyValue(1.0))
8404     return N0;
8405
8406   if (Options.UnsafeFPMath) {
8407     // fold (fmul A, 0) -> 0
8408     if (N1CFP && N1CFP->isZero())
8409       return N1;
8410
8411     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8412     if (N0.getOpcode() == ISD::FMUL) {
8413       // Fold scalars or any vector constants (not just splats).
8414       // This fold is done in general by InstCombine, but extra fmul insts
8415       // may have been generated during lowering.
8416       SDValue N00 = N0.getOperand(0);
8417       SDValue N01 = N0.getOperand(1);
8418       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8419       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8420       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8421
8422       // Check 1: Make sure that the first operand of the inner multiply is NOT
8423       // a constant. Otherwise, we may induce infinite looping.
8424       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8425         // Check 2: Make sure that the second operand of the inner multiply and
8426         // the second operand of the outer multiply are constants.
8427         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8428             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8429           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8430           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8431         }
8432       }
8433     }
8434
8435     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8436     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8437     // during an early run of DAGCombiner can prevent folding with fmuls
8438     // inserted during lowering.
8439     if (N0.getOpcode() == ISD::FADD &&
8440         (N0.getOperand(0) == N0.getOperand(1)) &&
8441         N0.hasOneUse()) {
8442       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8443       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8444       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8445     }
8446   }
8447
8448   // fold (fmul X, 2.0) -> (fadd X, X)
8449   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8450     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8451
8452   // fold (fmul X, -1.0) -> (fneg X)
8453   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8454     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8455       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8456
8457   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8458   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8459     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8460       // Both can be negated for free, check to see if at least one is cheaper
8461       // negated.
8462       if (LHSNeg == 2 || RHSNeg == 2)
8463         return DAG.getNode(ISD::FMUL, DL, VT,
8464                            GetNegatedExpression(N0, DAG, LegalOperations),
8465                            GetNegatedExpression(N1, DAG, LegalOperations),
8466                            Flags);
8467     }
8468   }
8469
8470   // FMUL -> FMA combines:
8471   if (SDValue Fused = visitFMULForFMACombine(N)) {
8472     AddToWorklist(Fused.getNode());
8473     return Fused;
8474   }
8475
8476   return SDValue();
8477 }
8478
8479 SDValue DAGCombiner::visitFMA(SDNode *N) {
8480   SDValue N0 = N->getOperand(0);
8481   SDValue N1 = N->getOperand(1);
8482   SDValue N2 = N->getOperand(2);
8483   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8484   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8485   EVT VT = N->getValueType(0);
8486   SDLoc dl(N);
8487   const TargetOptions &Options = DAG.getTarget().Options;
8488
8489   // Constant fold FMA.
8490   if (isa<ConstantFPSDNode>(N0) &&
8491       isa<ConstantFPSDNode>(N1) &&
8492       isa<ConstantFPSDNode>(N2)) {
8493     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8494   }
8495
8496   if (Options.UnsafeFPMath) {
8497     if (N0CFP && N0CFP->isZero())
8498       return N2;
8499     if (N1CFP && N1CFP->isZero())
8500       return N2;
8501   }
8502   // TODO: The FMA node should have flags that propagate to these nodes.
8503   if (N0CFP && N0CFP->isExactlyValue(1.0))
8504     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8505   if (N1CFP && N1CFP->isExactlyValue(1.0))
8506     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8507
8508   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8509   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8510      !isConstantFPBuildVectorOrConstantFP(N1))
8511     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8512
8513   // TODO: FMA nodes should have flags that propagate to the created nodes.
8514   // For now, create a Flags object for use with all unsafe math transforms.
8515   SDNodeFlags Flags;
8516   Flags.setUnsafeAlgebra(true);
8517
8518   if (Options.UnsafeFPMath) {
8519     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8520     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8521         isConstantFPBuildVectorOrConstantFP(N1) &&
8522         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8523       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8524                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8525                                      &Flags), &Flags);
8526     }
8527
8528     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8529     if (N0.getOpcode() == ISD::FMUL &&
8530         isConstantFPBuildVectorOrConstantFP(N1) &&
8531         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8532       return DAG.getNode(ISD::FMA, dl, VT,
8533                          N0.getOperand(0),
8534                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8535                                      &Flags),
8536                          N2);
8537     }
8538   }
8539
8540   // (fma x, 1, y) -> (fadd x, y)
8541   // (fma x, -1, y) -> (fadd (fneg x), y)
8542   if (N1CFP) {
8543     if (N1CFP->isExactlyValue(1.0))
8544       // TODO: The FMA node should have flags that propagate to this node.
8545       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8546
8547     if (N1CFP->isExactlyValue(-1.0) &&
8548         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8549       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8550       AddToWorklist(RHSNeg.getNode());
8551       // TODO: The FMA node should have flags that propagate to this node.
8552       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8553     }
8554   }
8555
8556   if (Options.UnsafeFPMath) {
8557     // (fma x, c, x) -> (fmul x, (c+1))
8558     if (N1CFP && N0 == N2) {
8559     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8560                          DAG.getNode(ISD::FADD, dl, VT,
8561                                      N1, DAG.getConstantFP(1.0, dl, VT),
8562                                      &Flags), &Flags);
8563     }
8564
8565     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8566     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8567       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8568                          DAG.getNode(ISD::FADD, dl, VT,
8569                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8570                                      &Flags), &Flags);
8571     }
8572   }
8573
8574   return SDValue();
8575 }
8576
8577 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8578 // reciprocal.
8579 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8580 // Notice that this is not always beneficial. One reason is different target
8581 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8582 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8583 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8584 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8585   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8586   const SDNodeFlags *Flags = N->getFlags();
8587   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8588     return SDValue();
8589
8590   // Skip if current node is a reciprocal.
8591   SDValue N0 = N->getOperand(0);
8592   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8593   if (N0CFP && N0CFP->isExactlyValue(1.0))
8594     return SDValue();
8595
8596   // Exit early if the target does not want this transform or if there can't
8597   // possibly be enough uses of the divisor to make the transform worthwhile.
8598   SDValue N1 = N->getOperand(1);
8599   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8600   if (!MinUses || N1->use_size() < MinUses)
8601     return SDValue();
8602
8603   // Find all FDIV users of the same divisor.
8604   // Use a set because duplicates may be present in the user list.
8605   SetVector<SDNode *> Users;
8606   for (auto *U : N1->uses()) {
8607     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8608       // This division is eligible for optimization only if global unsafe math
8609       // is enabled or if this division allows reciprocal formation.
8610       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8611         Users.insert(U);
8612     }
8613   }
8614
8615   // Now that we have the actual number of divisor uses, make sure it meets
8616   // the minimum threshold specified by the target.
8617   if (Users.size() < MinUses)
8618     return SDValue();
8619
8620   EVT VT = N->getValueType(0);
8621   SDLoc DL(N);
8622   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8623   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8624
8625   // Dividend / Divisor -> Dividend * Reciprocal
8626   for (auto *U : Users) {
8627     SDValue Dividend = U->getOperand(0);
8628     if (Dividend != FPOne) {
8629       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8630                                     Reciprocal, Flags);
8631       CombineTo(U, NewNode);
8632     } else if (U != Reciprocal.getNode()) {
8633       // In the absence of fast-math-flags, this user node is always the
8634       // same node as Reciprocal, but with FMF they may be different nodes.
8635       CombineTo(U, Reciprocal);
8636     }
8637   }
8638   return SDValue(N, 0);  // N was replaced.
8639 }
8640
8641 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8642   SDValue N0 = N->getOperand(0);
8643   SDValue N1 = N->getOperand(1);
8644   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8645   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8646   EVT VT = N->getValueType(0);
8647   SDLoc DL(N);
8648   const TargetOptions &Options = DAG.getTarget().Options;
8649   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8650
8651   // fold vector ops
8652   if (VT.isVector())
8653     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8654       return FoldedVOp;
8655
8656   // fold (fdiv c1, c2) -> c1/c2
8657   if (N0CFP && N1CFP)
8658     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8659
8660   if (Options.UnsafeFPMath) {
8661     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8662     if (N1CFP) {
8663       // Compute the reciprocal 1.0 / c2.
8664       APFloat N1APF = N1CFP->getValueAPF();
8665       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8666       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8667       // Only do the transform if the reciprocal is a legal fp immediate that
8668       // isn't too nasty (eg NaN, denormal, ...).
8669       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8670           (!LegalOperations ||
8671            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8672            // backend)... we should handle this gracefully after Legalize.
8673            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8674            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8675            TLI.isFPImmLegal(Recip, VT)))
8676         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8677                            DAG.getConstantFP(Recip, DL, VT), Flags);
8678     }
8679
8680     // If this FDIV is part of a reciprocal square root, it may be folded
8681     // into a target-specific square root estimate instruction.
8682     if (N1.getOpcode() == ISD::FSQRT) {
8683       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8684         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8685       }
8686     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8687                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8688       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8689                                           Flags)) {
8690         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8691         AddToWorklist(RV.getNode());
8692         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8693       }
8694     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8695                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8696       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8697                                           Flags)) {
8698         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8699         AddToWorklist(RV.getNode());
8700         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8701       }
8702     } else if (N1.getOpcode() == ISD::FMUL) {
8703       // Look through an FMUL. Even though this won't remove the FDIV directly,
8704       // it's still worthwhile to get rid of the FSQRT if possible.
8705       SDValue SqrtOp;
8706       SDValue OtherOp;
8707       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8708         SqrtOp = N1.getOperand(0);
8709         OtherOp = N1.getOperand(1);
8710       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8711         SqrtOp = N1.getOperand(1);
8712         OtherOp = N1.getOperand(0);
8713       }
8714       if (SqrtOp.getNode()) {
8715         // We found a FSQRT, so try to make this fold:
8716         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8717         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8718           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8719           AddToWorklist(RV.getNode());
8720           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8721         }
8722       }
8723     }
8724
8725     // Fold into a reciprocal estimate and multiply instead of a real divide.
8726     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8727       AddToWorklist(RV.getNode());
8728       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8729     }
8730   }
8731
8732   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8733   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8734     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8735       // Both can be negated for free, check to see if at least one is cheaper
8736       // negated.
8737       if (LHSNeg == 2 || RHSNeg == 2)
8738         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8739                            GetNegatedExpression(N0, DAG, LegalOperations),
8740                            GetNegatedExpression(N1, DAG, LegalOperations),
8741                            Flags);
8742     }
8743   }
8744
8745   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8746     return CombineRepeatedDivisors;
8747
8748   return SDValue();
8749 }
8750
8751 SDValue DAGCombiner::visitFREM(SDNode *N) {
8752   SDValue N0 = N->getOperand(0);
8753   SDValue N1 = N->getOperand(1);
8754   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8755   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8756   EVT VT = N->getValueType(0);
8757
8758   // fold (frem c1, c2) -> fmod(c1,c2)
8759   if (N0CFP && N1CFP)
8760     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8761                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8762
8763   return SDValue();
8764 }
8765
8766 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8767   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8768     return SDValue();
8769
8770   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8771   // For now, create a Flags object for use with all unsafe math transforms.
8772   SDNodeFlags Flags;
8773   Flags.setUnsafeAlgebra(true);
8774
8775   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8776   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8777   if (!RV)
8778     return SDValue();
8779
8780   EVT VT = RV.getValueType();
8781   SDLoc DL(N);
8782   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8783   AddToWorklist(RV.getNode());
8784
8785   // Unfortunately, RV is now NaN if the input was exactly 0.
8786   // Select out this case and force the answer to 0.
8787   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8788   EVT CCVT = getSetCCResultType(VT);
8789   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8790   AddToWorklist(ZeroCmp.getNode());
8791   AddToWorklist(RV.getNode());
8792
8793   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8794                      ZeroCmp, Zero, RV);
8795 }
8796
8797 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8798   // copysign(x, fp_extend(y)) -> copysign(x, y)
8799   // copysign(x, fp_round(y)) -> copysign(x, y)
8800   // Do not optimize out type conversion of f128 type yet.
8801   // For some target like x86_64, configuration is changed
8802   // to keep one f128 value in one SSE register, but
8803   // instruction selection cannot handle FCOPYSIGN on
8804   // SSE registers yet.
8805   SDValue N1 = N->getOperand(1);
8806   EVT N1VT = N1->getValueType(0);
8807   EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8808   return (N1.getOpcode() == ISD::FP_EXTEND ||
8809           N1.getOpcode() == ISD::FP_ROUND) &&
8810          (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8811 }
8812
8813 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8814   SDValue N0 = N->getOperand(0);
8815   SDValue N1 = N->getOperand(1);
8816   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8817   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8818   EVT VT = N->getValueType(0);
8819
8820   if (N0CFP && N1CFP)  // Constant fold
8821     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8822
8823   if (N1CFP) {
8824     const APFloat& V = N1CFP->getValueAPF();
8825     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8826     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8827     if (!V.isNegative()) {
8828       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8829         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8830     } else {
8831       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8832         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8833                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8834     }
8835   }
8836
8837   // copysign(fabs(x), y) -> copysign(x, y)
8838   // copysign(fneg(x), y) -> copysign(x, y)
8839   // copysign(copysign(x,z), y) -> copysign(x, y)
8840   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8841       N0.getOpcode() == ISD::FCOPYSIGN)
8842     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8843                        N0.getOperand(0), N1);
8844
8845   // copysign(x, abs(y)) -> abs(x)
8846   if (N1.getOpcode() == ISD::FABS)
8847     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8848
8849   // copysign(x, copysign(y,z)) -> copysign(x, z)
8850   if (N1.getOpcode() == ISD::FCOPYSIGN)
8851     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8852                        N0, N1.getOperand(1));
8853
8854   // copysign(x, fp_extend(y)) -> copysign(x, y)
8855   // copysign(x, fp_round(y)) -> copysign(x, y)
8856   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
8857     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8858                        N0, N1.getOperand(0));
8859
8860   return SDValue();
8861 }
8862
8863 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8864   SDValue N0 = N->getOperand(0);
8865   EVT VT = N->getValueType(0);
8866   EVT OpVT = N0.getValueType();
8867
8868   // fold (sint_to_fp c1) -> c1fp
8869   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8870       // ...but only if the target supports immediate floating-point values
8871       (!LegalOperations ||
8872        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8873     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8874
8875   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8876   // but UINT_TO_FP is legal on this target, try to convert.
8877   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8878       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8879     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8880     if (DAG.SignBitIsZero(N0))
8881       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8882   }
8883
8884   // The next optimizations are desirable only if SELECT_CC can be lowered.
8885   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8886     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8887     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8888         !VT.isVector() &&
8889         (!LegalOperations ||
8890          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8891       SDLoc DL(N);
8892       SDValue Ops[] =
8893         { N0.getOperand(0), N0.getOperand(1),
8894           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8895           N0.getOperand(2) };
8896       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8897     }
8898
8899     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8900     //      (select_cc x, y, 1.0, 0.0,, cc)
8901     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8902         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8903         (!LegalOperations ||
8904          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8905       SDLoc DL(N);
8906       SDValue Ops[] =
8907         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8908           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8909           N0.getOperand(0).getOperand(2) };
8910       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8911     }
8912   }
8913
8914   return SDValue();
8915 }
8916
8917 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8918   SDValue N0 = N->getOperand(0);
8919   EVT VT = N->getValueType(0);
8920   EVT OpVT = N0.getValueType();
8921
8922   // fold (uint_to_fp c1) -> c1fp
8923   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8924       // ...but only if the target supports immediate floating-point values
8925       (!LegalOperations ||
8926        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8927     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8928
8929   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8930   // but SINT_TO_FP is legal on this target, try to convert.
8931   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8932       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8933     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8934     if (DAG.SignBitIsZero(N0))
8935       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8936   }
8937
8938   // The next optimizations are desirable only if SELECT_CC can be lowered.
8939   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8940     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8941
8942     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8943         (!LegalOperations ||
8944          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8945       SDLoc DL(N);
8946       SDValue Ops[] =
8947         { N0.getOperand(0), N0.getOperand(1),
8948           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8949           N0.getOperand(2) };
8950       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8951     }
8952   }
8953
8954   return SDValue();
8955 }
8956
8957 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8958 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8959   SDValue N0 = N->getOperand(0);
8960   EVT VT = N->getValueType(0);
8961
8962   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8963     return SDValue();
8964
8965   SDValue Src = N0.getOperand(0);
8966   EVT SrcVT = Src.getValueType();
8967   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8968   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8969
8970   // We can safely assume the conversion won't overflow the output range,
8971   // because (for example) (uint8_t)18293.f is undefined behavior.
8972
8973   // Since we can assume the conversion won't overflow, our decision as to
8974   // whether the input will fit in the float should depend on the minimum
8975   // of the input range and output range.
8976
8977   // This means this is also safe for a signed input and unsigned output, since
8978   // a negative input would lead to undefined behavior.
8979   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8980   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8981   unsigned ActualSize = std::min(InputSize, OutputSize);
8982   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8983
8984   // We can only fold away the float conversion if the input range can be
8985   // represented exactly in the float range.
8986   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8987     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8988       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8989                                                        : ISD::ZERO_EXTEND;
8990       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8991     }
8992     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8993       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8994     if (SrcVT == VT)
8995       return Src;
8996     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8997   }
8998   return SDValue();
8999 }
9000
9001 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9002   SDValue N0 = N->getOperand(0);
9003   EVT VT = N->getValueType(0);
9004
9005   // fold (fp_to_sint c1fp) -> c1
9006   if (isConstantFPBuildVectorOrConstantFP(N0))
9007     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9008
9009   return FoldIntToFPToInt(N, DAG);
9010 }
9011
9012 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9013   SDValue N0 = N->getOperand(0);
9014   EVT VT = N->getValueType(0);
9015
9016   // fold (fp_to_uint c1fp) -> c1
9017   if (isConstantFPBuildVectorOrConstantFP(N0))
9018     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9019
9020   return FoldIntToFPToInt(N, DAG);
9021 }
9022
9023 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9024   SDValue N0 = N->getOperand(0);
9025   SDValue N1 = N->getOperand(1);
9026   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9027   EVT VT = N->getValueType(0);
9028
9029   // fold (fp_round c1fp) -> c1fp
9030   if (N0CFP)
9031     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9032
9033   // fold (fp_round (fp_extend x)) -> x
9034   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9035     return N0.getOperand(0);
9036
9037   // fold (fp_round (fp_round x)) -> (fp_round x)
9038   if (N0.getOpcode() == ISD::FP_ROUND) {
9039     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9040     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9041     // If the first fp_round isn't a value preserving truncation, it might
9042     // introduce a tie in the second fp_round, that wouldn't occur in the
9043     // single-step fp_round we want to fold to.
9044     // In other words, double rounding isn't the same as rounding.
9045     // Also, this is a value preserving truncation iff both fp_round's are.
9046     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9047       SDLoc DL(N);
9048       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9049                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9050     }
9051   }
9052
9053   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9054   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9055     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9056                               N0.getOperand(0), N1);
9057     AddToWorklist(Tmp.getNode());
9058     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9059                        Tmp, N0.getOperand(1));
9060   }
9061
9062   return SDValue();
9063 }
9064
9065 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9066   SDValue N0 = N->getOperand(0);
9067   EVT VT = N->getValueType(0);
9068   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9069   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9070
9071   // fold (fp_round_inreg c1fp) -> c1fp
9072   if (N0CFP && isTypeLegal(EVT)) {
9073     SDLoc DL(N);
9074     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9075     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9076   }
9077
9078   return SDValue();
9079 }
9080
9081 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9082   SDValue N0 = N->getOperand(0);
9083   EVT VT = N->getValueType(0);
9084
9085   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9086   if (N->hasOneUse() &&
9087       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9088     return SDValue();
9089
9090   // fold (fp_extend c1fp) -> c1fp
9091   if (isConstantFPBuildVectorOrConstantFP(N0))
9092     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9093
9094   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9095   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9096       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9097     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9098
9099   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9100   // value of X.
9101   if (N0.getOpcode() == ISD::FP_ROUND
9102       && N0.getNode()->getConstantOperandVal(1) == 1) {
9103     SDValue In = N0.getOperand(0);
9104     if (In.getValueType() == VT) return In;
9105     if (VT.bitsLT(In.getValueType()))
9106       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9107                          In, N0.getOperand(1));
9108     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9109   }
9110
9111   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9112   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9113        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9114     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9115     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9116                                      LN0->getChain(),
9117                                      LN0->getBasePtr(), N0.getValueType(),
9118                                      LN0->getMemOperand());
9119     CombineTo(N, ExtLoad);
9120     CombineTo(N0.getNode(),
9121               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9122                           N0.getValueType(), ExtLoad,
9123                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9124               ExtLoad.getValue(1));
9125     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9126   }
9127
9128   return SDValue();
9129 }
9130
9131 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9132   SDValue N0 = N->getOperand(0);
9133   EVT VT = N->getValueType(0);
9134
9135   // fold (fceil c1) -> fceil(c1)
9136   if (isConstantFPBuildVectorOrConstantFP(N0))
9137     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9138
9139   return SDValue();
9140 }
9141
9142 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9143   SDValue N0 = N->getOperand(0);
9144   EVT VT = N->getValueType(0);
9145
9146   // fold (ftrunc c1) -> ftrunc(c1)
9147   if (isConstantFPBuildVectorOrConstantFP(N0))
9148     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9149
9150   return SDValue();
9151 }
9152
9153 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9154   SDValue N0 = N->getOperand(0);
9155   EVT VT = N->getValueType(0);
9156
9157   // fold (ffloor c1) -> ffloor(c1)
9158   if (isConstantFPBuildVectorOrConstantFP(N0))
9159     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9160
9161   return SDValue();
9162 }
9163
9164 // FIXME: FNEG and FABS have a lot in common; refactor.
9165 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9166   SDValue N0 = N->getOperand(0);
9167   EVT VT = N->getValueType(0);
9168
9169   // Constant fold FNEG.
9170   if (isConstantFPBuildVectorOrConstantFP(N0))
9171     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9172
9173   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9174                          &DAG.getTarget().Options))
9175     return GetNegatedExpression(N0, DAG, LegalOperations);
9176
9177   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9178   // constant pool values.
9179   if (!TLI.isFNegFree(VT) &&
9180       N0.getOpcode() == ISD::BITCAST &&
9181       N0.getNode()->hasOneUse()) {
9182     SDValue Int = N0.getOperand(0);
9183     EVT IntVT = Int.getValueType();
9184     if (IntVT.isInteger() && !IntVT.isVector()) {
9185       APInt SignMask;
9186       if (N0.getValueType().isVector()) {
9187         // For a vector, get a mask such as 0x80... per scalar element
9188         // and splat it.
9189         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9190         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9191       } else {
9192         // For a scalar, just generate 0x80...
9193         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9194       }
9195       SDLoc DL0(N0);
9196       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9197                         DAG.getConstant(SignMask, DL0, IntVT));
9198       AddToWorklist(Int.getNode());
9199       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9200     }
9201   }
9202
9203   // (fneg (fmul c, x)) -> (fmul -c, x)
9204   if (N0.getOpcode() == ISD::FMUL &&
9205       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9206     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9207     if (CFP1) {
9208       APFloat CVal = CFP1->getValueAPF();
9209       CVal.changeSign();
9210       if (Level >= AfterLegalizeDAG &&
9211           (TLI.isFPImmLegal(CVal, VT) ||
9212            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9213         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9214                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9215                                        N0.getOperand(1)),
9216                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9217     }
9218   }
9219
9220   return SDValue();
9221 }
9222
9223 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9224   SDValue N0 = N->getOperand(0);
9225   SDValue N1 = N->getOperand(1);
9226   EVT VT = N->getValueType(0);
9227   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9228   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9229
9230   if (N0CFP && N1CFP) {
9231     const APFloat &C0 = N0CFP->getValueAPF();
9232     const APFloat &C1 = N1CFP->getValueAPF();
9233     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9234   }
9235
9236   // Canonicalize to constant on RHS.
9237   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9238      !isConstantFPBuildVectorOrConstantFP(N1))
9239     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9240
9241   return SDValue();
9242 }
9243
9244 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9245   SDValue N0 = N->getOperand(0);
9246   SDValue N1 = N->getOperand(1);
9247   EVT VT = N->getValueType(0);
9248   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9249   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9250
9251   if (N0CFP && N1CFP) {
9252     const APFloat &C0 = N0CFP->getValueAPF();
9253     const APFloat &C1 = N1CFP->getValueAPF();
9254     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9255   }
9256
9257   // Canonicalize to constant on RHS.
9258   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9259      !isConstantFPBuildVectorOrConstantFP(N1))
9260     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9261
9262   return SDValue();
9263 }
9264
9265 SDValue DAGCombiner::visitFABS(SDNode *N) {
9266   SDValue N0 = N->getOperand(0);
9267   EVT VT = N->getValueType(0);
9268
9269   // fold (fabs c1) -> fabs(c1)
9270   if (isConstantFPBuildVectorOrConstantFP(N0))
9271     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9272
9273   // fold (fabs (fabs x)) -> (fabs x)
9274   if (N0.getOpcode() == ISD::FABS)
9275     return N->getOperand(0);
9276
9277   // fold (fabs (fneg x)) -> (fabs x)
9278   // fold (fabs (fcopysign x, y)) -> (fabs x)
9279   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9280     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9281
9282   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9283   // constant pool values.
9284   if (!TLI.isFAbsFree(VT) &&
9285       N0.getOpcode() == ISD::BITCAST &&
9286       N0.getNode()->hasOneUse()) {
9287     SDValue Int = N0.getOperand(0);
9288     EVT IntVT = Int.getValueType();
9289     if (IntVT.isInteger() && !IntVT.isVector()) {
9290       APInt SignMask;
9291       if (N0.getValueType().isVector()) {
9292         // For a vector, get a mask such as 0x7f... per scalar element
9293         // and splat it.
9294         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9295         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9296       } else {
9297         // For a scalar, just generate 0x7f...
9298         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9299       }
9300       SDLoc DL(N0);
9301       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9302                         DAG.getConstant(SignMask, DL, IntVT));
9303       AddToWorklist(Int.getNode());
9304       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9305     }
9306   }
9307
9308   return SDValue();
9309 }
9310
9311 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9312   SDValue Chain = N->getOperand(0);
9313   SDValue N1 = N->getOperand(1);
9314   SDValue N2 = N->getOperand(2);
9315
9316   // If N is a constant we could fold this into a fallthrough or unconditional
9317   // branch. However that doesn't happen very often in normal code, because
9318   // Instcombine/SimplifyCFG should have handled the available opportunities.
9319   // If we did this folding here, it would be necessary to update the
9320   // MachineBasicBlock CFG, which is awkward.
9321
9322   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9323   // on the target.
9324   if (N1.getOpcode() == ISD::SETCC &&
9325       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9326                                    N1.getOperand(0).getValueType())) {
9327     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9328                        Chain, N1.getOperand(2),
9329                        N1.getOperand(0), N1.getOperand(1), N2);
9330   }
9331
9332   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9333       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9334        (N1.getOperand(0).hasOneUse() &&
9335         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9336     SDNode *Trunc = nullptr;
9337     if (N1.getOpcode() == ISD::TRUNCATE) {
9338       // Look pass the truncate.
9339       Trunc = N1.getNode();
9340       N1 = N1.getOperand(0);
9341     }
9342
9343     // Match this pattern so that we can generate simpler code:
9344     //
9345     //   %a = ...
9346     //   %b = and i32 %a, 2
9347     //   %c = srl i32 %b, 1
9348     //   brcond i32 %c ...
9349     //
9350     // into
9351     //
9352     //   %a = ...
9353     //   %b = and i32 %a, 2
9354     //   %c = setcc eq %b, 0
9355     //   brcond %c ...
9356     //
9357     // This applies only when the AND constant value has one bit set and the
9358     // SRL constant is equal to the log2 of the AND constant. The back-end is
9359     // smart enough to convert the result into a TEST/JMP sequence.
9360     SDValue Op0 = N1.getOperand(0);
9361     SDValue Op1 = N1.getOperand(1);
9362
9363     if (Op0.getOpcode() == ISD::AND &&
9364         Op1.getOpcode() == ISD::Constant) {
9365       SDValue AndOp1 = Op0.getOperand(1);
9366
9367       if (AndOp1.getOpcode() == ISD::Constant) {
9368         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9369
9370         if (AndConst.isPowerOf2() &&
9371             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9372           SDLoc DL(N);
9373           SDValue SetCC =
9374             DAG.getSetCC(DL,
9375                          getSetCCResultType(Op0.getValueType()),
9376                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9377                          ISD::SETNE);
9378
9379           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9380                                           MVT::Other, Chain, SetCC, N2);
9381           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9382           // will convert it back to (X & C1) >> C2.
9383           CombineTo(N, NewBRCond, false);
9384           // Truncate is dead.
9385           if (Trunc)
9386             deleteAndRecombine(Trunc);
9387           // Replace the uses of SRL with SETCC
9388           WorklistRemover DeadNodes(*this);
9389           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9390           deleteAndRecombine(N1.getNode());
9391           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9392         }
9393       }
9394     }
9395
9396     if (Trunc)
9397       // Restore N1 if the above transformation doesn't match.
9398       N1 = N->getOperand(1);
9399   }
9400
9401   // Transform br(xor(x, y)) -> br(x != y)
9402   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9403   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9404     SDNode *TheXor = N1.getNode();
9405     SDValue Op0 = TheXor->getOperand(0);
9406     SDValue Op1 = TheXor->getOperand(1);
9407     if (Op0.getOpcode() == Op1.getOpcode()) {
9408       // Avoid missing important xor optimizations.
9409       if (SDValue Tmp = visitXOR(TheXor)) {
9410         if (Tmp.getNode() != TheXor) {
9411           DEBUG(dbgs() << "\nReplacing.8 ";
9412                 TheXor->dump(&DAG);
9413                 dbgs() << "\nWith: ";
9414                 Tmp.getNode()->dump(&DAG);
9415                 dbgs() << '\n');
9416           WorklistRemover DeadNodes(*this);
9417           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9418           deleteAndRecombine(TheXor);
9419           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9420                              MVT::Other, Chain, Tmp, N2);
9421         }
9422
9423         // visitXOR has changed XOR's operands or replaced the XOR completely,
9424         // bail out.
9425         return SDValue(N, 0);
9426       }
9427     }
9428
9429     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9430       bool Equal = false;
9431       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9432           Op0.getOpcode() == ISD::XOR) {
9433         TheXor = Op0.getNode();
9434         Equal = true;
9435       }
9436
9437       EVT SetCCVT = N1.getValueType();
9438       if (LegalTypes)
9439         SetCCVT = getSetCCResultType(SetCCVT);
9440       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9441                                    SetCCVT,
9442                                    Op0, Op1,
9443                                    Equal ? ISD::SETEQ : ISD::SETNE);
9444       // Replace the uses of XOR with SETCC
9445       WorklistRemover DeadNodes(*this);
9446       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9447       deleteAndRecombine(N1.getNode());
9448       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9449                          MVT::Other, Chain, SetCC, N2);
9450     }
9451   }
9452
9453   return SDValue();
9454 }
9455
9456 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9457 //
9458 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9459   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9460   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9461
9462   // If N is a constant we could fold this into a fallthrough or unconditional
9463   // branch. However that doesn't happen very often in normal code, because
9464   // Instcombine/SimplifyCFG should have handled the available opportunities.
9465   // If we did this folding here, it would be necessary to update the
9466   // MachineBasicBlock CFG, which is awkward.
9467
9468   // Use SimplifySetCC to simplify SETCC's.
9469   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9470                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9471                                false);
9472   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9473
9474   // fold to a simpler setcc
9475   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9476     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9477                        N->getOperand(0), Simp.getOperand(2),
9478                        Simp.getOperand(0), Simp.getOperand(1),
9479                        N->getOperand(4));
9480
9481   return SDValue();
9482 }
9483
9484 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9485 /// and that N may be folded in the load / store addressing mode.
9486 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9487                                     SelectionDAG &DAG,
9488                                     const TargetLowering &TLI) {
9489   EVT VT;
9490   unsigned AS;
9491
9492   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9493     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9494       return false;
9495     VT = LD->getMemoryVT();
9496     AS = LD->getAddressSpace();
9497   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9498     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9499       return false;
9500     VT = ST->getMemoryVT();
9501     AS = ST->getAddressSpace();
9502   } else
9503     return false;
9504
9505   TargetLowering::AddrMode AM;
9506   if (N->getOpcode() == ISD::ADD) {
9507     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9508     if (Offset)
9509       // [reg +/- imm]
9510       AM.BaseOffs = Offset->getSExtValue();
9511     else
9512       // [reg +/- reg]
9513       AM.Scale = 1;
9514   } else if (N->getOpcode() == ISD::SUB) {
9515     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9516     if (Offset)
9517       // [reg +/- imm]
9518       AM.BaseOffs = -Offset->getSExtValue();
9519     else
9520       // [reg +/- reg]
9521       AM.Scale = 1;
9522   } else
9523     return false;
9524
9525   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9526                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9527 }
9528
9529 /// Try turning a load/store into a pre-indexed load/store when the base
9530 /// pointer is an add or subtract and it has other uses besides the load/store.
9531 /// After the transformation, the new indexed load/store has effectively folded
9532 /// the add/subtract in and all of its other uses are redirected to the
9533 /// new load/store.
9534 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9535   if (Level < AfterLegalizeDAG)
9536     return false;
9537
9538   bool isLoad = true;
9539   SDValue Ptr;
9540   EVT VT;
9541   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9542     if (LD->isIndexed())
9543       return false;
9544     VT = LD->getMemoryVT();
9545     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9546         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9547       return false;
9548     Ptr = LD->getBasePtr();
9549   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9550     if (ST->isIndexed())
9551       return false;
9552     VT = ST->getMemoryVT();
9553     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9554         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9555       return false;
9556     Ptr = ST->getBasePtr();
9557     isLoad = false;
9558   } else {
9559     return false;
9560   }
9561
9562   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9563   // out.  There is no reason to make this a preinc/predec.
9564   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9565       Ptr.getNode()->hasOneUse())
9566     return false;
9567
9568   // Ask the target to do addressing mode selection.
9569   SDValue BasePtr;
9570   SDValue Offset;
9571   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9572   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9573     return false;
9574
9575   // Backends without true r+i pre-indexed forms may need to pass a
9576   // constant base with a variable offset so that constant coercion
9577   // will work with the patterns in canonical form.
9578   bool Swapped = false;
9579   if (isa<ConstantSDNode>(BasePtr)) {
9580     std::swap(BasePtr, Offset);
9581     Swapped = true;
9582   }
9583
9584   // Don't create a indexed load / store with zero offset.
9585   if (isNullConstant(Offset))
9586     return false;
9587
9588   // Try turning it into a pre-indexed load / store except when:
9589   // 1) The new base ptr is a frame index.
9590   // 2) If N is a store and the new base ptr is either the same as or is a
9591   //    predecessor of the value being stored.
9592   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9593   //    that would create a cycle.
9594   // 4) All uses are load / store ops that use it as old base ptr.
9595
9596   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9597   // (plus the implicit offset) to a register to preinc anyway.
9598   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9599     return false;
9600
9601   // Check #2.
9602   if (!isLoad) {
9603     SDValue Val = cast<StoreSDNode>(N)->getValue();
9604     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9605       return false;
9606   }
9607
9608   // If the offset is a constant, there may be other adds of constants that
9609   // can be folded with this one. We should do this to avoid having to keep
9610   // a copy of the original base pointer.
9611   SmallVector<SDNode *, 16> OtherUses;
9612   if (isa<ConstantSDNode>(Offset))
9613     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9614                               UE = BasePtr.getNode()->use_end();
9615          UI != UE; ++UI) {
9616       SDUse &Use = UI.getUse();
9617       // Skip the use that is Ptr and uses of other results from BasePtr's
9618       // node (important for nodes that return multiple results).
9619       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9620         continue;
9621
9622       if (Use.getUser()->isPredecessorOf(N))
9623         continue;
9624
9625       if (Use.getUser()->getOpcode() != ISD::ADD &&
9626           Use.getUser()->getOpcode() != ISD::SUB) {
9627         OtherUses.clear();
9628         break;
9629       }
9630
9631       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9632       if (!isa<ConstantSDNode>(Op1)) {
9633         OtherUses.clear();
9634         break;
9635       }
9636
9637       // FIXME: In some cases, we can be smarter about this.
9638       if (Op1.getValueType() != Offset.getValueType()) {
9639         OtherUses.clear();
9640         break;
9641       }
9642
9643       OtherUses.push_back(Use.getUser());
9644     }
9645
9646   if (Swapped)
9647     std::swap(BasePtr, Offset);
9648
9649   // Now check for #3 and #4.
9650   bool RealUse = false;
9651
9652   // Caches for hasPredecessorHelper
9653   SmallPtrSet<const SDNode *, 32> Visited;
9654   SmallVector<const SDNode *, 16> Worklist;
9655
9656   for (SDNode *Use : Ptr.getNode()->uses()) {
9657     if (Use == N)
9658       continue;
9659     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9660       return false;
9661
9662     // If Ptr may be folded in addressing mode of other use, then it's
9663     // not profitable to do this transformation.
9664     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9665       RealUse = true;
9666   }
9667
9668   if (!RealUse)
9669     return false;
9670
9671   SDValue Result;
9672   if (isLoad)
9673     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9674                                 BasePtr, Offset, AM);
9675   else
9676     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9677                                  BasePtr, Offset, AM);
9678   ++PreIndexedNodes;
9679   ++NodesCombined;
9680   DEBUG(dbgs() << "\nReplacing.4 ";
9681         N->dump(&DAG);
9682         dbgs() << "\nWith: ";
9683         Result.getNode()->dump(&DAG);
9684         dbgs() << '\n');
9685   WorklistRemover DeadNodes(*this);
9686   if (isLoad) {
9687     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9688     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9689   } else {
9690     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9691   }
9692
9693   // Finally, since the node is now dead, remove it from the graph.
9694   deleteAndRecombine(N);
9695
9696   if (Swapped)
9697     std::swap(BasePtr, Offset);
9698
9699   // Replace other uses of BasePtr that can be updated to use Ptr
9700   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9701     unsigned OffsetIdx = 1;
9702     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9703       OffsetIdx = 0;
9704     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9705            BasePtr.getNode() && "Expected BasePtr operand");
9706
9707     // We need to replace ptr0 in the following expression:
9708     //   x0 * offset0 + y0 * ptr0 = t0
9709     // knowing that
9710     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9711     //
9712     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9713     // indexed load/store and the expresion that needs to be re-written.
9714     //
9715     // Therefore, we have:
9716     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9717
9718     ConstantSDNode *CN =
9719       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9720     int X0, X1, Y0, Y1;
9721     APInt Offset0 = CN->getAPIntValue();
9722     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9723
9724     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9725     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9726     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9727     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9728
9729     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9730
9731     APInt CNV = Offset0;
9732     if (X0 < 0) CNV = -CNV;
9733     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9734     else CNV = CNV - Offset1;
9735
9736     SDLoc DL(OtherUses[i]);
9737
9738     // We can now generate the new expression.
9739     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9740     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9741
9742     SDValue NewUse = DAG.getNode(Opcode,
9743                                  DL,
9744                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9745     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9746     deleteAndRecombine(OtherUses[i]);
9747   }
9748
9749   // Replace the uses of Ptr with uses of the updated base value.
9750   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9751   deleteAndRecombine(Ptr.getNode());
9752
9753   return true;
9754 }
9755
9756 /// Try to combine a load/store with a add/sub of the base pointer node into a
9757 /// post-indexed load/store. The transformation folded the add/subtract into the
9758 /// new indexed load/store effectively and all of its uses are redirected to the
9759 /// new load/store.
9760 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9761   if (Level < AfterLegalizeDAG)
9762     return false;
9763
9764   bool isLoad = true;
9765   SDValue Ptr;
9766   EVT VT;
9767   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9768     if (LD->isIndexed())
9769       return false;
9770     VT = LD->getMemoryVT();
9771     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9772         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9773       return false;
9774     Ptr = LD->getBasePtr();
9775   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9776     if (ST->isIndexed())
9777       return false;
9778     VT = ST->getMemoryVT();
9779     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9780         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9781       return false;
9782     Ptr = ST->getBasePtr();
9783     isLoad = false;
9784   } else {
9785     return false;
9786   }
9787
9788   if (Ptr.getNode()->hasOneUse())
9789     return false;
9790
9791   for (SDNode *Op : Ptr.getNode()->uses()) {
9792     if (Op == N ||
9793         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9794       continue;
9795
9796     SDValue BasePtr;
9797     SDValue Offset;
9798     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9799     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9800       // Don't create a indexed load / store with zero offset.
9801       if (isNullConstant(Offset))
9802         continue;
9803
9804       // Try turning it into a post-indexed load / store except when
9805       // 1) All uses are load / store ops that use it as base ptr (and
9806       //    it may be folded as addressing mmode).
9807       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9808       //    nor a successor of N. Otherwise, if Op is folded that would
9809       //    create a cycle.
9810
9811       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9812         continue;
9813
9814       // Check for #1.
9815       bool TryNext = false;
9816       for (SDNode *Use : BasePtr.getNode()->uses()) {
9817         if (Use == Ptr.getNode())
9818           continue;
9819
9820         // If all the uses are load / store addresses, then don't do the
9821         // transformation.
9822         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9823           bool RealUse = false;
9824           for (SDNode *UseUse : Use->uses()) {
9825             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9826               RealUse = true;
9827           }
9828
9829           if (!RealUse) {
9830             TryNext = true;
9831             break;
9832           }
9833         }
9834       }
9835
9836       if (TryNext)
9837         continue;
9838
9839       // Check for #2
9840       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9841         SDValue Result = isLoad
9842           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9843                                BasePtr, Offset, AM)
9844           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9845                                 BasePtr, Offset, AM);
9846         ++PostIndexedNodes;
9847         ++NodesCombined;
9848         DEBUG(dbgs() << "\nReplacing.5 ";
9849               N->dump(&DAG);
9850               dbgs() << "\nWith: ";
9851               Result.getNode()->dump(&DAG);
9852               dbgs() << '\n');
9853         WorklistRemover DeadNodes(*this);
9854         if (isLoad) {
9855           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9856           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9857         } else {
9858           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9859         }
9860
9861         // Finally, since the node is now dead, remove it from the graph.
9862         deleteAndRecombine(N);
9863
9864         // Replace the uses of Use with uses of the updated base value.
9865         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9866                                       Result.getValue(isLoad ? 1 : 0));
9867         deleteAndRecombine(Op);
9868         return true;
9869       }
9870     }
9871   }
9872
9873   return false;
9874 }
9875
9876 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9877 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9878   ISD::MemIndexedMode AM = LD->getAddressingMode();
9879   assert(AM != ISD::UNINDEXED);
9880   SDValue BP = LD->getOperand(1);
9881   SDValue Inc = LD->getOperand(2);
9882
9883   // Some backends use TargetConstants for load offsets, but don't expect
9884   // TargetConstants in general ADD nodes. We can convert these constants into
9885   // regular Constants (if the constant is not opaque).
9886   assert((Inc.getOpcode() != ISD::TargetConstant ||
9887           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9888          "Cannot split out indexing using opaque target constants");
9889   if (Inc.getOpcode() == ISD::TargetConstant) {
9890     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9891     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9892                           ConstInc->getValueType(0));
9893   }
9894
9895   unsigned Opc =
9896       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9897   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9898 }
9899
9900 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9901   LoadSDNode *LD  = cast<LoadSDNode>(N);
9902   SDValue Chain = LD->getChain();
9903   SDValue Ptr   = LD->getBasePtr();
9904
9905   // If load is not volatile and there are no uses of the loaded value (and
9906   // the updated indexed value in case of indexed loads), change uses of the
9907   // chain value into uses of the chain input (i.e. delete the dead load).
9908   if (!LD->isVolatile()) {
9909     if (N->getValueType(1) == MVT::Other) {
9910       // Unindexed loads.
9911       if (!N->hasAnyUseOfValue(0)) {
9912         // It's not safe to use the two value CombineTo variant here. e.g.
9913         // v1, chain2 = load chain1, loc
9914         // v2, chain3 = load chain2, loc
9915         // v3         = add v2, c
9916         // Now we replace use of chain2 with chain1.  This makes the second load
9917         // isomorphic to the one we are deleting, and thus makes this load live.
9918         DEBUG(dbgs() << "\nReplacing.6 ";
9919               N->dump(&DAG);
9920               dbgs() << "\nWith chain: ";
9921               Chain.getNode()->dump(&DAG);
9922               dbgs() << "\n");
9923         WorklistRemover DeadNodes(*this);
9924         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9925
9926         if (N->use_empty())
9927           deleteAndRecombine(N);
9928
9929         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9930       }
9931     } else {
9932       // Indexed loads.
9933       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9934
9935       // If this load has an opaque TargetConstant offset, then we cannot split
9936       // the indexing into an add/sub directly (that TargetConstant may not be
9937       // valid for a different type of node, and we cannot convert an opaque
9938       // target constant into a regular constant).
9939       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9940                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9941
9942       if (!N->hasAnyUseOfValue(0) &&
9943           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9944         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9945         SDValue Index;
9946         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9947           Index = SplitIndexingFromLoad(LD);
9948           // Try to fold the base pointer arithmetic into subsequent loads and
9949           // stores.
9950           AddUsersToWorklist(N);
9951         } else
9952           Index = DAG.getUNDEF(N->getValueType(1));
9953         DEBUG(dbgs() << "\nReplacing.7 ";
9954               N->dump(&DAG);
9955               dbgs() << "\nWith: ";
9956               Undef.getNode()->dump(&DAG);
9957               dbgs() << " and 2 other values\n");
9958         WorklistRemover DeadNodes(*this);
9959         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9960         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9961         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9962         deleteAndRecombine(N);
9963         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9964       }
9965     }
9966   }
9967
9968   // If this load is directly stored, replace the load value with the stored
9969   // value.
9970   // TODO: Handle store large -> read small portion.
9971   // TODO: Handle TRUNCSTORE/LOADEXT
9972   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9973     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9974       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9975       if (PrevST->getBasePtr() == Ptr &&
9976           PrevST->getValue().getValueType() == N->getValueType(0))
9977       return CombineTo(N, Chain.getOperand(1), Chain);
9978     }
9979   }
9980
9981   // Try to infer better alignment information than the load already has.
9982   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9983     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9984       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9985         SDValue NewLoad =
9986                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9987                               LD->getValueType(0),
9988                               Chain, Ptr, LD->getPointerInfo(),
9989                               LD->getMemoryVT(),
9990                               LD->isVolatile(), LD->isNonTemporal(),
9991                               LD->isInvariant(), Align, LD->getAAInfo());
9992         if (NewLoad.getNode() != N)
9993           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9994       }
9995     }
9996   }
9997
9998   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9999                                                   : DAG.getSubtarget().useAA();
10000 #ifndef NDEBUG
10001   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10002       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10003     UseAA = false;
10004 #endif
10005   if (UseAA && LD->isUnindexed()) {
10006     // Walk up chain skipping non-aliasing memory nodes.
10007     SDValue BetterChain = FindBetterChain(N, Chain);
10008
10009     // If there is a better chain.
10010     if (Chain != BetterChain) {
10011       SDValue ReplLoad;
10012
10013       // Replace the chain to void dependency.
10014       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10015         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10016                                BetterChain, Ptr, LD->getMemOperand());
10017       } else {
10018         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10019                                   LD->getValueType(0),
10020                                   BetterChain, Ptr, LD->getMemoryVT(),
10021                                   LD->getMemOperand());
10022       }
10023
10024       // Create token factor to keep old chain connected.
10025       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10026                                   MVT::Other, Chain, ReplLoad.getValue(1));
10027
10028       // Make sure the new and old chains are cleaned up.
10029       AddToWorklist(Token.getNode());
10030
10031       // Replace uses with load result and token factor. Don't add users
10032       // to work list.
10033       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10034     }
10035   }
10036
10037   // Try transforming N to an indexed load.
10038   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10039     return SDValue(N, 0);
10040
10041   // Try to slice up N to more direct loads if the slices are mapped to
10042   // different register banks or pairing can take place.
10043   if (SliceUpLoad(N))
10044     return SDValue(N, 0);
10045
10046   return SDValue();
10047 }
10048
10049 namespace {
10050 /// \brief Helper structure used to slice a load in smaller loads.
10051 /// Basically a slice is obtained from the following sequence:
10052 /// Origin = load Ty1, Base
10053 /// Shift = srl Ty1 Origin, CstTy Amount
10054 /// Inst = trunc Shift to Ty2
10055 ///
10056 /// Then, it will be rewriten into:
10057 /// Slice = load SliceTy, Base + SliceOffset
10058 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10059 ///
10060 /// SliceTy is deduced from the number of bits that are actually used to
10061 /// build Inst.
10062 struct LoadedSlice {
10063   /// \brief Helper structure used to compute the cost of a slice.
10064   struct Cost {
10065     /// Are we optimizing for code size.
10066     bool ForCodeSize;
10067     /// Various cost.
10068     unsigned Loads;
10069     unsigned Truncates;
10070     unsigned CrossRegisterBanksCopies;
10071     unsigned ZExts;
10072     unsigned Shift;
10073
10074     Cost(bool ForCodeSize = false)
10075         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10076           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10077
10078     /// \brief Get the cost of one isolated slice.
10079     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10080         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10081           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10082       EVT TruncType = LS.Inst->getValueType(0);
10083       EVT LoadedType = LS.getLoadedType();
10084       if (TruncType != LoadedType &&
10085           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10086         ZExts = 1;
10087     }
10088
10089     /// \brief Account for slicing gain in the current cost.
10090     /// Slicing provide a few gains like removing a shift or a
10091     /// truncate. This method allows to grow the cost of the original
10092     /// load with the gain from this slice.
10093     void addSliceGain(const LoadedSlice &LS) {
10094       // Each slice saves a truncate.
10095       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10096       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10097                               LS.Inst->getValueType(0)))
10098         ++Truncates;
10099       // If there is a shift amount, this slice gets rid of it.
10100       if (LS.Shift)
10101         ++Shift;
10102       // If this slice can merge a cross register bank copy, account for it.
10103       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10104         ++CrossRegisterBanksCopies;
10105     }
10106
10107     Cost &operator+=(const Cost &RHS) {
10108       Loads += RHS.Loads;
10109       Truncates += RHS.Truncates;
10110       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10111       ZExts += RHS.ZExts;
10112       Shift += RHS.Shift;
10113       return *this;
10114     }
10115
10116     bool operator==(const Cost &RHS) const {
10117       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10118              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10119              ZExts == RHS.ZExts && Shift == RHS.Shift;
10120     }
10121
10122     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10123
10124     bool operator<(const Cost &RHS) const {
10125       // Assume cross register banks copies are as expensive as loads.
10126       // FIXME: Do we want some more target hooks?
10127       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10128       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10129       // Unless we are optimizing for code size, consider the
10130       // expensive operation first.
10131       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10132         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10133       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10134              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10135     }
10136
10137     bool operator>(const Cost &RHS) const { return RHS < *this; }
10138
10139     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10140
10141     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10142   };
10143   // The last instruction that represent the slice. This should be a
10144   // truncate instruction.
10145   SDNode *Inst;
10146   // The original load instruction.
10147   LoadSDNode *Origin;
10148   // The right shift amount in bits from the original load.
10149   unsigned Shift;
10150   // The DAG from which Origin came from.
10151   // This is used to get some contextual information about legal types, etc.
10152   SelectionDAG *DAG;
10153
10154   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10155               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10156       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10157
10158   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10159   /// \return Result is \p BitWidth and has used bits set to 1 and
10160   ///         not used bits set to 0.
10161   APInt getUsedBits() const {
10162     // Reproduce the trunc(lshr) sequence:
10163     // - Start from the truncated value.
10164     // - Zero extend to the desired bit width.
10165     // - Shift left.
10166     assert(Origin && "No original load to compare against.");
10167     unsigned BitWidth = Origin->getValueSizeInBits(0);
10168     assert(Inst && "This slice is not bound to an instruction");
10169     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10170            "Extracted slice is bigger than the whole type!");
10171     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10172     UsedBits.setAllBits();
10173     UsedBits = UsedBits.zext(BitWidth);
10174     UsedBits <<= Shift;
10175     return UsedBits;
10176   }
10177
10178   /// \brief Get the size of the slice to be loaded in bytes.
10179   unsigned getLoadedSize() const {
10180     unsigned SliceSize = getUsedBits().countPopulation();
10181     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10182     return SliceSize / 8;
10183   }
10184
10185   /// \brief Get the type that will be loaded for this slice.
10186   /// Note: This may not be the final type for the slice.
10187   EVT getLoadedType() const {
10188     assert(DAG && "Missing context");
10189     LLVMContext &Ctxt = *DAG->getContext();
10190     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10191   }
10192
10193   /// \brief Get the alignment of the load used for this slice.
10194   unsigned getAlignment() const {
10195     unsigned Alignment = Origin->getAlignment();
10196     unsigned Offset = getOffsetFromBase();
10197     if (Offset != 0)
10198       Alignment = MinAlign(Alignment, Alignment + Offset);
10199     return Alignment;
10200   }
10201
10202   /// \brief Check if this slice can be rewritten with legal operations.
10203   bool isLegal() const {
10204     // An invalid slice is not legal.
10205     if (!Origin || !Inst || !DAG)
10206       return false;
10207
10208     // Offsets are for indexed load only, we do not handle that.
10209     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10210       return false;
10211
10212     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10213
10214     // Check that the type is legal.
10215     EVT SliceType = getLoadedType();
10216     if (!TLI.isTypeLegal(SliceType))
10217       return false;
10218
10219     // Check that the load is legal for this type.
10220     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10221       return false;
10222
10223     // Check that the offset can be computed.
10224     // 1. Check its type.
10225     EVT PtrType = Origin->getBasePtr().getValueType();
10226     if (PtrType == MVT::Untyped || PtrType.isExtended())
10227       return false;
10228
10229     // 2. Check that it fits in the immediate.
10230     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10231       return false;
10232
10233     // 3. Check that the computation is legal.
10234     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10235       return false;
10236
10237     // Check that the zext is legal if it needs one.
10238     EVT TruncateType = Inst->getValueType(0);
10239     if (TruncateType != SliceType &&
10240         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10241       return false;
10242
10243     return true;
10244   }
10245
10246   /// \brief Get the offset in bytes of this slice in the original chunk of
10247   /// bits.
10248   /// \pre DAG != nullptr.
10249   uint64_t getOffsetFromBase() const {
10250     assert(DAG && "Missing context.");
10251     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10252     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10253     uint64_t Offset = Shift / 8;
10254     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10255     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10256            "The size of the original loaded type is not a multiple of a"
10257            " byte.");
10258     // If Offset is bigger than TySizeInBytes, it means we are loading all
10259     // zeros. This should have been optimized before in the process.
10260     assert(TySizeInBytes > Offset &&
10261            "Invalid shift amount for given loaded size");
10262     if (IsBigEndian)
10263       Offset = TySizeInBytes - Offset - getLoadedSize();
10264     return Offset;
10265   }
10266
10267   /// \brief Generate the sequence of instructions to load the slice
10268   /// represented by this object and redirect the uses of this slice to
10269   /// this new sequence of instructions.
10270   /// \pre this->Inst && this->Origin are valid Instructions and this
10271   /// object passed the legal check: LoadedSlice::isLegal returned true.
10272   /// \return The last instruction of the sequence used to load the slice.
10273   SDValue loadSlice() const {
10274     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10275     const SDValue &OldBaseAddr = Origin->getBasePtr();
10276     SDValue BaseAddr = OldBaseAddr;
10277     // Get the offset in that chunk of bytes w.r.t. the endianess.
10278     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10279     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10280     if (Offset) {
10281       // BaseAddr = BaseAddr + Offset.
10282       EVT ArithType = BaseAddr.getValueType();
10283       SDLoc DL(Origin);
10284       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10285                               DAG->getConstant(Offset, DL, ArithType));
10286     }
10287
10288     // Create the type of the loaded slice according to its size.
10289     EVT SliceType = getLoadedType();
10290
10291     // Create the load for the slice.
10292     SDValue LastInst = DAG->getLoad(
10293         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10294         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10295         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10296     // If the final type is not the same as the loaded type, this means that
10297     // we have to pad with zero. Create a zero extend for that.
10298     EVT FinalType = Inst->getValueType(0);
10299     if (SliceType != FinalType)
10300       LastInst =
10301           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10302     return LastInst;
10303   }
10304
10305   /// \brief Check if this slice can be merged with an expensive cross register
10306   /// bank copy. E.g.,
10307   /// i = load i32
10308   /// f = bitcast i32 i to float
10309   bool canMergeExpensiveCrossRegisterBankCopy() const {
10310     if (!Inst || !Inst->hasOneUse())
10311       return false;
10312     SDNode *Use = *Inst->use_begin();
10313     if (Use->getOpcode() != ISD::BITCAST)
10314       return false;
10315     assert(DAG && "Missing context");
10316     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10317     EVT ResVT = Use->getValueType(0);
10318     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10319     const TargetRegisterClass *ArgRC =
10320         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10321     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10322       return false;
10323
10324     // At this point, we know that we perform a cross-register-bank copy.
10325     // Check if it is expensive.
10326     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10327     // Assume bitcasts are cheap, unless both register classes do not
10328     // explicitly share a common sub class.
10329     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10330       return false;
10331
10332     // Check if it will be merged with the load.
10333     // 1. Check the alignment constraint.
10334     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10335         ResVT.getTypeForEVT(*DAG->getContext()));
10336
10337     if (RequiredAlignment > getAlignment())
10338       return false;
10339
10340     // 2. Check that the load is a legal operation for that type.
10341     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10342       return false;
10343
10344     // 3. Check that we do not have a zext in the way.
10345     if (Inst->getValueType(0) != getLoadedType())
10346       return false;
10347
10348     return true;
10349   }
10350 };
10351 }
10352
10353 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10354 /// \p UsedBits looks like 0..0 1..1 0..0.
10355 static bool areUsedBitsDense(const APInt &UsedBits) {
10356   // If all the bits are one, this is dense!
10357   if (UsedBits.isAllOnesValue())
10358     return true;
10359
10360   // Get rid of the unused bits on the right.
10361   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10362   // Get rid of the unused bits on the left.
10363   if (NarrowedUsedBits.countLeadingZeros())
10364     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10365   // Check that the chunk of bits is completely used.
10366   return NarrowedUsedBits.isAllOnesValue();
10367 }
10368
10369 /// \brief Check whether or not \p First and \p Second are next to each other
10370 /// in memory. This means that there is no hole between the bits loaded
10371 /// by \p First and the bits loaded by \p Second.
10372 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10373                                      const LoadedSlice &Second) {
10374   assert(First.Origin == Second.Origin && First.Origin &&
10375          "Unable to match different memory origins.");
10376   APInt UsedBits = First.getUsedBits();
10377   assert((UsedBits & Second.getUsedBits()) == 0 &&
10378          "Slices are not supposed to overlap.");
10379   UsedBits |= Second.getUsedBits();
10380   return areUsedBitsDense(UsedBits);
10381 }
10382
10383 /// \brief Adjust the \p GlobalLSCost according to the target
10384 /// paring capabilities and the layout of the slices.
10385 /// \pre \p GlobalLSCost should account for at least as many loads as
10386 /// there is in the slices in \p LoadedSlices.
10387 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10388                                  LoadedSlice::Cost &GlobalLSCost) {
10389   unsigned NumberOfSlices = LoadedSlices.size();
10390   // If there is less than 2 elements, no pairing is possible.
10391   if (NumberOfSlices < 2)
10392     return;
10393
10394   // Sort the slices so that elements that are likely to be next to each
10395   // other in memory are next to each other in the list.
10396   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10397             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10398     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10399     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10400   });
10401   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10402   // First (resp. Second) is the first (resp. Second) potentially candidate
10403   // to be placed in a paired load.
10404   const LoadedSlice *First = nullptr;
10405   const LoadedSlice *Second = nullptr;
10406   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10407                 // Set the beginning of the pair.
10408                                                            First = Second) {
10409
10410     Second = &LoadedSlices[CurrSlice];
10411
10412     // If First is NULL, it means we start a new pair.
10413     // Get to the next slice.
10414     if (!First)
10415       continue;
10416
10417     EVT LoadedType = First->getLoadedType();
10418
10419     // If the types of the slices are different, we cannot pair them.
10420     if (LoadedType != Second->getLoadedType())
10421       continue;
10422
10423     // Check if the target supplies paired loads for this type.
10424     unsigned RequiredAlignment = 0;
10425     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10426       // move to the next pair, this type is hopeless.
10427       Second = nullptr;
10428       continue;
10429     }
10430     // Check if we meet the alignment requirement.
10431     if (RequiredAlignment > First->getAlignment())
10432       continue;
10433
10434     // Check that both loads are next to each other in memory.
10435     if (!areSlicesNextToEachOther(*First, *Second))
10436       continue;
10437
10438     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10439     --GlobalLSCost.Loads;
10440     // Move to the next pair.
10441     Second = nullptr;
10442   }
10443 }
10444
10445 /// \brief Check the profitability of all involved LoadedSlice.
10446 /// Currently, it is considered profitable if there is exactly two
10447 /// involved slices (1) which are (2) next to each other in memory, and
10448 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10449 ///
10450 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10451 /// the elements themselves.
10452 ///
10453 /// FIXME: When the cost model will be mature enough, we can relax
10454 /// constraints (1) and (2).
10455 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10456                                 const APInt &UsedBits, bool ForCodeSize) {
10457   unsigned NumberOfSlices = LoadedSlices.size();
10458   if (StressLoadSlicing)
10459     return NumberOfSlices > 1;
10460
10461   // Check (1).
10462   if (NumberOfSlices != 2)
10463     return false;
10464
10465   // Check (2).
10466   if (!areUsedBitsDense(UsedBits))
10467     return false;
10468
10469   // Check (3).
10470   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10471   // The original code has one big load.
10472   OrigCost.Loads = 1;
10473   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10474     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10475     // Accumulate the cost of all the slices.
10476     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10477     GlobalSlicingCost += SliceCost;
10478
10479     // Account as cost in the original configuration the gain obtained
10480     // with the current slices.
10481     OrigCost.addSliceGain(LS);
10482   }
10483
10484   // If the target supports paired load, adjust the cost accordingly.
10485   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10486   return OrigCost > GlobalSlicingCost;
10487 }
10488
10489 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10490 /// operations, split it in the various pieces being extracted.
10491 ///
10492 /// This sort of thing is introduced by SROA.
10493 /// This slicing takes care not to insert overlapping loads.
10494 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10495 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10496   if (Level < AfterLegalizeDAG)
10497     return false;
10498
10499   LoadSDNode *LD = cast<LoadSDNode>(N);
10500   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10501       !LD->getValueType(0).isInteger())
10502     return false;
10503
10504   // Keep track of already used bits to detect overlapping values.
10505   // In that case, we will just abort the transformation.
10506   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10507
10508   SmallVector<LoadedSlice, 4> LoadedSlices;
10509
10510   // Check if this load is used as several smaller chunks of bits.
10511   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10512   // of computation for each trunc.
10513   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10514        UI != UIEnd; ++UI) {
10515     // Skip the uses of the chain.
10516     if (UI.getUse().getResNo() != 0)
10517       continue;
10518
10519     SDNode *User = *UI;
10520     unsigned Shift = 0;
10521
10522     // Check if this is a trunc(lshr).
10523     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10524         isa<ConstantSDNode>(User->getOperand(1))) {
10525       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10526       User = *User->use_begin();
10527     }
10528
10529     // At this point, User is a Truncate, iff we encountered, trunc or
10530     // trunc(lshr).
10531     if (User->getOpcode() != ISD::TRUNCATE)
10532       return false;
10533
10534     // The width of the type must be a power of 2 and greater than 8-bits.
10535     // Otherwise the load cannot be represented in LLVM IR.
10536     // Moreover, if we shifted with a non-8-bits multiple, the slice
10537     // will be across several bytes. We do not support that.
10538     unsigned Width = User->getValueSizeInBits(0);
10539     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10540       return 0;
10541
10542     // Build the slice for this chain of computations.
10543     LoadedSlice LS(User, LD, Shift, &DAG);
10544     APInt CurrentUsedBits = LS.getUsedBits();
10545
10546     // Check if this slice overlaps with another.
10547     if ((CurrentUsedBits & UsedBits) != 0)
10548       return false;
10549     // Update the bits used globally.
10550     UsedBits |= CurrentUsedBits;
10551
10552     // Check if the new slice would be legal.
10553     if (!LS.isLegal())
10554       return false;
10555
10556     // Record the slice.
10557     LoadedSlices.push_back(LS);
10558   }
10559
10560   // Abort slicing if it does not seem to be profitable.
10561   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10562     return false;
10563
10564   ++SlicedLoads;
10565
10566   // Rewrite each chain to use an independent load.
10567   // By construction, each chain can be represented by a unique load.
10568
10569   // Prepare the argument for the new token factor for all the slices.
10570   SmallVector<SDValue, 8> ArgChains;
10571   for (SmallVectorImpl<LoadedSlice>::const_iterator
10572            LSIt = LoadedSlices.begin(),
10573            LSItEnd = LoadedSlices.end();
10574        LSIt != LSItEnd; ++LSIt) {
10575     SDValue SliceInst = LSIt->loadSlice();
10576     CombineTo(LSIt->Inst, SliceInst, true);
10577     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10578       SliceInst = SliceInst.getOperand(0);
10579     assert(SliceInst->getOpcode() == ISD::LOAD &&
10580            "It takes more than a zext to get to the loaded slice!!");
10581     ArgChains.push_back(SliceInst.getValue(1));
10582   }
10583
10584   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10585                               ArgChains);
10586   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10587   return true;
10588 }
10589
10590 /// Check to see if V is (and load (ptr), imm), where the load is having
10591 /// specific bytes cleared out.  If so, return the byte size being masked out
10592 /// and the shift amount.
10593 static std::pair<unsigned, unsigned>
10594 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10595   std::pair<unsigned, unsigned> Result(0, 0);
10596
10597   // Check for the structure we're looking for.
10598   if (V->getOpcode() != ISD::AND ||
10599       !isa<ConstantSDNode>(V->getOperand(1)) ||
10600       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10601     return Result;
10602
10603   // Check the chain and pointer.
10604   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10605   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10606
10607   // The store should be chained directly to the load or be an operand of a
10608   // tokenfactor.
10609   if (LD == Chain.getNode())
10610     ; // ok.
10611   else if (Chain->getOpcode() != ISD::TokenFactor)
10612     return Result; // Fail.
10613   else {
10614     bool isOk = false;
10615     for (const SDValue &ChainOp : Chain->op_values())
10616       if (ChainOp.getNode() == LD) {
10617         isOk = true;
10618         break;
10619       }
10620     if (!isOk) return Result;
10621   }
10622
10623   // This only handles simple types.
10624   if (V.getValueType() != MVT::i16 &&
10625       V.getValueType() != MVT::i32 &&
10626       V.getValueType() != MVT::i64)
10627     return Result;
10628
10629   // Check the constant mask.  Invert it so that the bits being masked out are
10630   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10631   // follow the sign bit for uniformity.
10632   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10633   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10634   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10635   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10636   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10637   if (NotMaskLZ == 64) return Result;  // All zero mask.
10638
10639   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10640   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10641     return Result;
10642
10643   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10644   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10645     NotMaskLZ -= 64-V.getValueSizeInBits();
10646
10647   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10648   switch (MaskedBytes) {
10649   case 1:
10650   case 2:
10651   case 4: break;
10652   default: return Result; // All one mask, or 5-byte mask.
10653   }
10654
10655   // Verify that the first bit starts at a multiple of mask so that the access
10656   // is aligned the same as the access width.
10657   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10658
10659   Result.first = MaskedBytes;
10660   Result.second = NotMaskTZ/8;
10661   return Result;
10662 }
10663
10664
10665 /// Check to see if IVal is something that provides a value as specified by
10666 /// MaskInfo. If so, replace the specified store with a narrower store of
10667 /// truncated IVal.
10668 static SDNode *
10669 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10670                                 SDValue IVal, StoreSDNode *St,
10671                                 DAGCombiner *DC) {
10672   unsigned NumBytes = MaskInfo.first;
10673   unsigned ByteShift = MaskInfo.second;
10674   SelectionDAG &DAG = DC->getDAG();
10675
10676   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10677   // that uses this.  If not, this is not a replacement.
10678   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10679                                   ByteShift*8, (ByteShift+NumBytes)*8);
10680   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10681
10682   // Check that it is legal on the target to do this.  It is legal if the new
10683   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10684   // legalization.
10685   MVT VT = MVT::getIntegerVT(NumBytes*8);
10686   if (!DC->isTypeLegal(VT))
10687     return nullptr;
10688
10689   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10690   // shifted by ByteShift and truncated down to NumBytes.
10691   if (ByteShift) {
10692     SDLoc DL(IVal);
10693     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10694                        DAG.getConstant(ByteShift*8, DL,
10695                                     DC->getShiftAmountTy(IVal.getValueType())));
10696   }
10697
10698   // Figure out the offset for the store and the alignment of the access.
10699   unsigned StOffset;
10700   unsigned NewAlign = St->getAlignment();
10701
10702   if (DAG.getDataLayout().isLittleEndian())
10703     StOffset = ByteShift;
10704   else
10705     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10706
10707   SDValue Ptr = St->getBasePtr();
10708   if (StOffset) {
10709     SDLoc DL(IVal);
10710     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10711                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10712     NewAlign = MinAlign(NewAlign, StOffset);
10713   }
10714
10715   // Truncate down to the new size.
10716   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10717
10718   ++OpsNarrowed;
10719   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10720                       St->getPointerInfo().getWithOffset(StOffset),
10721                       false, false, NewAlign).getNode();
10722 }
10723
10724
10725 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10726 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10727 /// narrowing the load and store if it would end up being a win for performance
10728 /// or code size.
10729 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10730   StoreSDNode *ST  = cast<StoreSDNode>(N);
10731   if (ST->isVolatile())
10732     return SDValue();
10733
10734   SDValue Chain = ST->getChain();
10735   SDValue Value = ST->getValue();
10736   SDValue Ptr   = ST->getBasePtr();
10737   EVT VT = Value.getValueType();
10738
10739   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10740     return SDValue();
10741
10742   unsigned Opc = Value.getOpcode();
10743
10744   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10745   // is a byte mask indicating a consecutive number of bytes, check to see if
10746   // Y is known to provide just those bytes.  If so, we try to replace the
10747   // load + replace + store sequence with a single (narrower) store, which makes
10748   // the load dead.
10749   if (Opc == ISD::OR) {
10750     std::pair<unsigned, unsigned> MaskedLoad;
10751     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10752     if (MaskedLoad.first)
10753       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10754                                                   Value.getOperand(1), ST,this))
10755         return SDValue(NewST, 0);
10756
10757     // Or is commutative, so try swapping X and Y.
10758     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10759     if (MaskedLoad.first)
10760       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10761                                                   Value.getOperand(0), ST,this))
10762         return SDValue(NewST, 0);
10763   }
10764
10765   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10766       Value.getOperand(1).getOpcode() != ISD::Constant)
10767     return SDValue();
10768
10769   SDValue N0 = Value.getOperand(0);
10770   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10771       Chain == SDValue(N0.getNode(), 1)) {
10772     LoadSDNode *LD = cast<LoadSDNode>(N0);
10773     if (LD->getBasePtr() != Ptr ||
10774         LD->getPointerInfo().getAddrSpace() !=
10775         ST->getPointerInfo().getAddrSpace())
10776       return SDValue();
10777
10778     // Find the type to narrow it the load / op / store to.
10779     SDValue N1 = Value.getOperand(1);
10780     unsigned BitWidth = N1.getValueSizeInBits();
10781     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10782     if (Opc == ISD::AND)
10783       Imm ^= APInt::getAllOnesValue(BitWidth);
10784     if (Imm == 0 || Imm.isAllOnesValue())
10785       return SDValue();
10786     unsigned ShAmt = Imm.countTrailingZeros();
10787     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10788     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10789     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10790     // The narrowing should be profitable, the load/store operation should be
10791     // legal (or custom) and the store size should be equal to the NewVT width.
10792     while (NewBW < BitWidth &&
10793            (NewVT.getStoreSizeInBits() != NewBW ||
10794             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10795             !TLI.isNarrowingProfitable(VT, NewVT))) {
10796       NewBW = NextPowerOf2(NewBW);
10797       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10798     }
10799     if (NewBW >= BitWidth)
10800       return SDValue();
10801
10802     // If the lsb changed does not start at the type bitwidth boundary,
10803     // start at the previous one.
10804     if (ShAmt % NewBW)
10805       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10806     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10807                                    std::min(BitWidth, ShAmt + NewBW));
10808     if ((Imm & Mask) == Imm) {
10809       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10810       if (Opc == ISD::AND)
10811         NewImm ^= APInt::getAllOnesValue(NewBW);
10812       uint64_t PtrOff = ShAmt / 8;
10813       // For big endian targets, we need to adjust the offset to the pointer to
10814       // load the correct bytes.
10815       if (DAG.getDataLayout().isBigEndian())
10816         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10817
10818       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10819       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10820       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10821         return SDValue();
10822
10823       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10824                                    Ptr.getValueType(), Ptr,
10825                                    DAG.getConstant(PtrOff, SDLoc(LD),
10826                                                    Ptr.getValueType()));
10827       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10828                                   LD->getChain(), NewPtr,
10829                                   LD->getPointerInfo().getWithOffset(PtrOff),
10830                                   LD->isVolatile(), LD->isNonTemporal(),
10831                                   LD->isInvariant(), NewAlign,
10832                                   LD->getAAInfo());
10833       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10834                                    DAG.getConstant(NewImm, SDLoc(Value),
10835                                                    NewVT));
10836       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10837                                    NewVal, NewPtr,
10838                                    ST->getPointerInfo().getWithOffset(PtrOff),
10839                                    false, false, NewAlign);
10840
10841       AddToWorklist(NewPtr.getNode());
10842       AddToWorklist(NewLD.getNode());
10843       AddToWorklist(NewVal.getNode());
10844       WorklistRemover DeadNodes(*this);
10845       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10846       ++OpsNarrowed;
10847       return NewST;
10848     }
10849   }
10850
10851   return SDValue();
10852 }
10853
10854 /// For a given floating point load / store pair, if the load value isn't used
10855 /// by any other operations, then consider transforming the pair to integer
10856 /// load / store operations if the target deems the transformation profitable.
10857 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10858   StoreSDNode *ST  = cast<StoreSDNode>(N);
10859   SDValue Chain = ST->getChain();
10860   SDValue Value = ST->getValue();
10861   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10862       Value.hasOneUse() &&
10863       Chain == SDValue(Value.getNode(), 1)) {
10864     LoadSDNode *LD = cast<LoadSDNode>(Value);
10865     EVT VT = LD->getMemoryVT();
10866     if (!VT.isFloatingPoint() ||
10867         VT != ST->getMemoryVT() ||
10868         LD->isNonTemporal() ||
10869         ST->isNonTemporal() ||
10870         LD->getPointerInfo().getAddrSpace() != 0 ||
10871         ST->getPointerInfo().getAddrSpace() != 0)
10872       return SDValue();
10873
10874     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10875     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10876         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10877         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10878         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10879       return SDValue();
10880
10881     unsigned LDAlign = LD->getAlignment();
10882     unsigned STAlign = ST->getAlignment();
10883     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10884     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10885     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10886       return SDValue();
10887
10888     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10889                                 LD->getChain(), LD->getBasePtr(),
10890                                 LD->getPointerInfo(),
10891                                 false, false, false, LDAlign);
10892
10893     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10894                                  NewLD, ST->getBasePtr(),
10895                                  ST->getPointerInfo(),
10896                                  false, false, STAlign);
10897
10898     AddToWorklist(NewLD.getNode());
10899     AddToWorklist(NewST.getNode());
10900     WorklistRemover DeadNodes(*this);
10901     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10902     ++LdStFP2Int;
10903     return NewST;
10904   }
10905
10906   return SDValue();
10907 }
10908
10909 namespace {
10910 /// Helper struct to parse and store a memory address as base + index + offset.
10911 /// We ignore sign extensions when it is safe to do so.
10912 /// The following two expressions are not equivalent. To differentiate we need
10913 /// to store whether there was a sign extension involved in the index
10914 /// computation.
10915 ///  (load (i64 add (i64 copyfromreg %c)
10916 ///                 (i64 signextend (add (i8 load %index)
10917 ///                                      (i8 1))))
10918 /// vs
10919 ///
10920 /// (load (i64 add (i64 copyfromreg %c)
10921 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10922 ///                                         (i32 1)))))
10923 struct BaseIndexOffset {
10924   SDValue Base;
10925   SDValue Index;
10926   int64_t Offset;
10927   bool IsIndexSignExt;
10928
10929   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10930
10931   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10932                   bool IsIndexSignExt) :
10933     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10934
10935   bool equalBaseIndex(const BaseIndexOffset &Other) {
10936     return Other.Base == Base && Other.Index == Index &&
10937       Other.IsIndexSignExt == IsIndexSignExt;
10938   }
10939
10940   /// Parses tree in Ptr for base, index, offset addresses.
10941   static BaseIndexOffset match(SDValue Ptr) {
10942     bool IsIndexSignExt = false;
10943
10944     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10945     // instruction, then it could be just the BASE or everything else we don't
10946     // know how to handle. Just use Ptr as BASE and give up.
10947     if (Ptr->getOpcode() != ISD::ADD)
10948       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10949
10950     // We know that we have at least an ADD instruction. Try to pattern match
10951     // the simple case of BASE + OFFSET.
10952     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10953       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10954       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10955                               IsIndexSignExt);
10956     }
10957
10958     // Inside a loop the current BASE pointer is calculated using an ADD and a
10959     // MUL instruction. In this case Ptr is the actual BASE pointer.
10960     // (i64 add (i64 %array_ptr)
10961     //          (i64 mul (i64 %induction_var)
10962     //                   (i64 %element_size)))
10963     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10964       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10965
10966     // Look at Base + Index + Offset cases.
10967     SDValue Base = Ptr->getOperand(0);
10968     SDValue IndexOffset = Ptr->getOperand(1);
10969
10970     // Skip signextends.
10971     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10972       IndexOffset = IndexOffset->getOperand(0);
10973       IsIndexSignExt = true;
10974     }
10975
10976     // Either the case of Base + Index (no offset) or something else.
10977     if (IndexOffset->getOpcode() != ISD::ADD)
10978       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10979
10980     // Now we have the case of Base + Index + offset.
10981     SDValue Index = IndexOffset->getOperand(0);
10982     SDValue Offset = IndexOffset->getOperand(1);
10983
10984     if (!isa<ConstantSDNode>(Offset))
10985       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10986
10987     // Ignore signextends.
10988     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10989       Index = Index->getOperand(0);
10990       IsIndexSignExt = true;
10991     } else IsIndexSignExt = false;
10992
10993     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10994     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10995   }
10996 };
10997 } // namespace
10998
10999 // This is a helper function for visitMUL to check the profitability
11000 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11001 // MulNode is the original multiply, AddNode is (add x, c1),
11002 // and ConstNode is c2.
11003 //
11004 // If the (add x, c1) has multiple uses, we could increase
11005 // the number of adds if we make this transformation.
11006 // It would only be worth doing this if we can remove a
11007 // multiply in the process. Check for that here.
11008 // To illustrate:
11009 //     (A + c1) * c3
11010 //     (A + c2) * c3
11011 // We're checking for cases where we have common "c3 * A" expressions.
11012 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11013                                               SDValue &AddNode,
11014                                               SDValue &ConstNode) {
11015   APInt Val;
11016
11017   // If the add only has one use, this would be OK to do.
11018   if (AddNode.getNode()->hasOneUse())
11019     return true;
11020
11021   // Walk all the users of the constant with which we're multiplying.
11022   for (SDNode *Use : ConstNode->uses()) {
11023
11024     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11025       continue;
11026
11027     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11028       SDNode *OtherOp;
11029       SDNode *MulVar = AddNode.getOperand(0).getNode();
11030
11031       // OtherOp is what we're multiplying against the constant.
11032       if (Use->getOperand(0) == ConstNode)
11033         OtherOp = Use->getOperand(1).getNode();
11034       else
11035         OtherOp = Use->getOperand(0).getNode();
11036
11037       // Check to see if multiply is with the same operand of our "add".
11038       //
11039       //     ConstNode  = CONST
11040       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11041       //     ...
11042       //     AddNode  = (A + c1)  <-- MulVar is A.
11043       //         = AddNode * ConstNode   <-- current visiting instruction.
11044       //
11045       // If we make this transformation, we will have a common
11046       // multiply (ConstNode * A) that we can save.
11047       if (OtherOp == MulVar)
11048         return true;
11049
11050       // Now check to see if a future expansion will give us a common
11051       // multiply.
11052       //
11053       //     ConstNode  = CONST
11054       //     AddNode    = (A + c1)
11055       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11056       //     ...
11057       //     OtherOp = (A + c2)
11058       //     Use     = OtherOp * ConstNode <-- visiting Use.
11059       //
11060       // If we make this transformation, we will have a common
11061       // multiply (CONST * A) after we also do the same transformation
11062       // to the "t2" instruction.
11063       if (OtherOp->getOpcode() == ISD::ADD &&
11064           isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11065           OtherOp->getOperand(0).getNode() == MulVar)
11066         return true;
11067     }
11068   }
11069
11070   // Didn't find a case where this would be profitable.
11071   return false;
11072 }
11073
11074 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11075                                                   SDLoc SL,
11076                                                   ArrayRef<MemOpLink> Stores,
11077                                                   SmallVectorImpl<SDValue> &Chains,
11078                                                   EVT Ty) const {
11079   SmallVector<SDValue, 8> BuildVector;
11080
11081   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11082     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11083     Chains.push_back(St->getChain());
11084     BuildVector.push_back(St->getValue());
11085   }
11086
11087   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
11088 }
11089
11090 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11091                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11092                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11093   // Make sure we have something to merge.
11094   if (NumStores < 2)
11095     return false;
11096
11097   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11098   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11099   unsigned LatestNodeUsed = 0;
11100
11101   for (unsigned i=0; i < NumStores; ++i) {
11102     // Find a chain for the new wide-store operand. Notice that some
11103     // of the store nodes that we found may not be selected for inclusion
11104     // in the wide store. The chain we use needs to be the chain of the
11105     // latest store node which is *used* and replaced by the wide store.
11106     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11107       LatestNodeUsed = i;
11108   }
11109
11110   SmallVector<SDValue, 8> Chains;
11111
11112   // The latest Node in the DAG.
11113   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11114   SDLoc DL(StoreNodes[0].MemNode);
11115
11116   SDValue StoredVal;
11117   if (UseVector) {
11118     bool IsVec = MemVT.isVector();
11119     unsigned Elts = NumStores;
11120     if (IsVec) {
11121       // When merging vector stores, get the total number of elements.
11122       Elts *= MemVT.getVectorNumElements();
11123     }
11124     // Get the type for the merged vector store.
11125     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11126     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11127
11128     if (IsConstantSrc) {
11129       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11130     } else {
11131       SmallVector<SDValue, 8> Ops;
11132       for (unsigned i = 0; i < NumStores; ++i) {
11133         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11134         SDValue Val = St->getValue();
11135         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11136         if (Val.getValueType() != MemVT)
11137           return false;
11138         Ops.push_back(Val);
11139         Chains.push_back(St->getChain());
11140       }
11141
11142       // Build the extracted vector elements back into a vector.
11143       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11144                               DL, Ty, Ops);    }
11145   } else {
11146     // We should always use a vector store when merging extracted vector
11147     // elements, so this path implies a store of constants.
11148     assert(IsConstantSrc && "Merged vector elements should use vector store");
11149
11150     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11151     APInt StoreInt(SizeInBits, 0);
11152
11153     // Construct a single integer constant which is made of the smaller
11154     // constant inputs.
11155     bool IsLE = DAG.getDataLayout().isLittleEndian();
11156     for (unsigned i = 0; i < NumStores; ++i) {
11157       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11158       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11159       Chains.push_back(St->getChain());
11160
11161       SDValue Val = St->getValue();
11162       StoreInt <<= ElementSizeBytes * 8;
11163       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11164         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11165       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11166         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11167       } else {
11168         llvm_unreachable("Invalid constant element type");
11169       }
11170     }
11171
11172     // Create the new Load and Store operations.
11173     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11174     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11175   }
11176
11177   assert(!Chains.empty());
11178
11179   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11180   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11181                                   FirstInChain->getBasePtr(),
11182                                   FirstInChain->getPointerInfo(),
11183                                   false, false,
11184                                   FirstInChain->getAlignment());
11185
11186   // Replace the last store with the new store
11187   CombineTo(LatestOp, NewStore);
11188   // Erase all other stores.
11189   for (unsigned i = 0; i < NumStores; ++i) {
11190     if (StoreNodes[i].MemNode == LatestOp)
11191       continue;
11192     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11193     // ReplaceAllUsesWith will replace all uses that existed when it was
11194     // called, but graph optimizations may cause new ones to appear. For
11195     // example, the case in pr14333 looks like
11196     //
11197     //  St's chain -> St -> another store -> X
11198     //
11199     // And the only difference from St to the other store is the chain.
11200     // When we change it's chain to be St's chain they become identical,
11201     // get CSEed and the net result is that X is now a use of St.
11202     // Since we know that St is redundant, just iterate.
11203     while (!St->use_empty())
11204       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11205     deleteAndRecombine(St);
11206   }
11207
11208   return true;
11209 }
11210
11211 void DAGCombiner::getStoreMergeAndAliasCandidates(
11212     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11213     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11214   // This holds the base pointer, index, and the offset in bytes from the base
11215   // pointer.
11216   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11217
11218   // We must have a base and an offset.
11219   if (!BasePtr.Base.getNode())
11220     return;
11221
11222   // Do not handle stores to undef base pointers.
11223   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11224     return;
11225
11226   // Walk up the chain and look for nodes with offsets from the same
11227   // base pointer. Stop when reaching an instruction with a different kind
11228   // or instruction which has a different base pointer.
11229   EVT MemVT = St->getMemoryVT();
11230   unsigned Seq = 0;
11231   StoreSDNode *Index = St;
11232
11233
11234   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11235                                                   : DAG.getSubtarget().useAA();
11236
11237   if (UseAA) {
11238     // Look at other users of the same chain. Stores on the same chain do not
11239     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11240     // to be on the same chain, so don't bother looking at adjacent chains.
11241
11242     SDValue Chain = St->getChain();
11243     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11244       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11245         if (I.getOperandNo() != 0)
11246           continue;
11247
11248         if (OtherST->isVolatile() || OtherST->isIndexed())
11249           continue;
11250
11251         if (OtherST->getMemoryVT() != MemVT)
11252           continue;
11253
11254         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11255
11256         if (Ptr.equalBaseIndex(BasePtr))
11257           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11258       }
11259     }
11260
11261     return;
11262   }
11263
11264   while (Index) {
11265     // If the chain has more than one use, then we can't reorder the mem ops.
11266     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11267       break;
11268
11269     // Find the base pointer and offset for this memory node.
11270     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11271
11272     // Check that the base pointer is the same as the original one.
11273     if (!Ptr.equalBaseIndex(BasePtr))
11274       break;
11275
11276     // The memory operands must not be volatile.
11277     if (Index->isVolatile() || Index->isIndexed())
11278       break;
11279
11280     // No truncation.
11281     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11282       if (St->isTruncatingStore())
11283         break;
11284
11285     // The stored memory type must be the same.
11286     if (Index->getMemoryVT() != MemVT)
11287       break;
11288
11289     // We do not allow under-aligned stores in order to prevent
11290     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11291     // be irrelevant here; what MATTERS is that we not move memory
11292     // operations that potentially overlap past each-other.
11293     if (Index->getAlignment() < MemVT.getStoreSize())
11294       break;
11295
11296     // We found a potential memory operand to merge.
11297     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11298
11299     // Find the next memory operand in the chain. If the next operand in the
11300     // chain is a store then move up and continue the scan with the next
11301     // memory operand. If the next operand is a load save it and use alias
11302     // information to check if it interferes with anything.
11303     SDNode *NextInChain = Index->getChain().getNode();
11304     while (1) {
11305       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11306         // We found a store node. Use it for the next iteration.
11307         Index = STn;
11308         break;
11309       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11310         if (Ldn->isVolatile()) {
11311           Index = nullptr;
11312           break;
11313         }
11314
11315         // Save the load node for later. Continue the scan.
11316         AliasLoadNodes.push_back(Ldn);
11317         NextInChain = Ldn->getChain().getNode();
11318         continue;
11319       } else {
11320         Index = nullptr;
11321         break;
11322       }
11323     }
11324   }
11325 }
11326
11327 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11328   if (OptLevel == CodeGenOpt::None)
11329     return false;
11330
11331   EVT MemVT = St->getMemoryVT();
11332   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11333   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11334       Attribute::NoImplicitFloat);
11335
11336   // This function cannot currently deal with non-byte-sized memory sizes.
11337   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11338     return false;
11339
11340   if (!MemVT.isSimple())
11341     return false;
11342
11343   // Perform an early exit check. Do not bother looking at stored values that
11344   // are not constants, loads, or extracted vector elements.
11345   SDValue StoredVal = St->getValue();
11346   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11347   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11348                        isa<ConstantFPSDNode>(StoredVal);
11349   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11350                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11351
11352   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11353     return false;
11354
11355   // Don't merge vectors into wider vectors if the source data comes from loads.
11356   // TODO: This restriction can be lifted by using logic similar to the
11357   // ExtractVecSrc case.
11358   if (MemVT.isVector() && IsLoadSrc)
11359     return false;
11360
11361   // Only look at ends of store sequences.
11362   SDValue Chain = SDValue(St, 0);
11363   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11364     return false;
11365
11366   // Save the LoadSDNodes that we find in the chain.
11367   // We need to make sure that these nodes do not interfere with
11368   // any of the store nodes.
11369   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11370
11371   // Save the StoreSDNodes that we find in the chain.
11372   SmallVector<MemOpLink, 8> StoreNodes;
11373
11374   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11375
11376   // Check if there is anything to merge.
11377   if (StoreNodes.size() < 2)
11378     return false;
11379
11380   // Sort the memory operands according to their distance from the
11381   // base pointer.  As a secondary criteria: make sure stores coming
11382   // later in the code come first in the list. This is important for
11383   // the non-UseAA case, because we're merging stores into the FINAL
11384   // store along a chain which potentially contains aliasing stores.
11385   // Thus, if there are multiple stores to the same address, the last
11386   // one can be considered for merging but not the others.
11387   std::sort(StoreNodes.begin(), StoreNodes.end(),
11388             [](MemOpLink LHS, MemOpLink RHS) {
11389     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11390            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11391             LHS.SequenceNum < RHS.SequenceNum);
11392   });
11393
11394   // Scan the memory operations on the chain and find the first non-consecutive
11395   // store memory address.
11396   unsigned LastConsecutiveStore = 0;
11397   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11398   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11399
11400     // Check that the addresses are consecutive starting from the second
11401     // element in the list of stores.
11402     if (i > 0) {
11403       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11404       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11405         break;
11406     }
11407
11408     // Check if this store interferes with any of the loads that we found.
11409     // If we find a load that alias with this store. Stop the sequence.
11410     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11411                     [&](LSBaseSDNode* Ldn) {
11412                       return isAlias(Ldn, StoreNodes[i].MemNode);
11413                     }))
11414       break;
11415
11416     // Mark this node as useful.
11417     LastConsecutiveStore = i;
11418   }
11419
11420   // The node with the lowest store address.
11421   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11422   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11423   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11424   LLVMContext &Context = *DAG.getContext();
11425   const DataLayout &DL = DAG.getDataLayout();
11426
11427   // Store the constants into memory as one consecutive store.
11428   if (IsConstantSrc) {
11429     unsigned LastLegalType = 0;
11430     unsigned LastLegalVectorType = 0;
11431     bool NonZero = false;
11432     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11433       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11434       SDValue StoredVal = St->getValue();
11435
11436       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11437         NonZero |= !C->isNullValue();
11438       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11439         NonZero |= !C->getConstantFPValue()->isNullValue();
11440       } else {
11441         // Non-constant.
11442         break;
11443       }
11444
11445       // Find a legal type for the constant store.
11446       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11447       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11448       bool IsFast;
11449       if (TLI.isTypeLegal(StoreTy) &&
11450           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11451                                  FirstStoreAlign, &IsFast) && IsFast) {
11452         LastLegalType = i+1;
11453       // Or check whether a truncstore is legal.
11454       } else if (TLI.getTypeAction(Context, StoreTy) ==
11455                  TargetLowering::TypePromoteInteger) {
11456         EVT LegalizedStoredValueTy =
11457           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11458         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11459             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11460                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11461             IsFast) {
11462           LastLegalType = i + 1;
11463         }
11464       }
11465
11466       // We only use vectors if the constant is known to be zero or the target
11467       // allows it and the function is not marked with the noimplicitfloat
11468       // attribute.
11469       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11470                                                         FirstStoreAS)) &&
11471           !NoVectors) {
11472         // Find a legal type for the vector store.
11473         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11474         if (TLI.isTypeLegal(Ty) &&
11475             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11476                                    FirstStoreAlign, &IsFast) && IsFast)
11477           LastLegalVectorType = i + 1;
11478       }
11479     }
11480
11481     // Check if we found a legal integer type to store.
11482     if (LastLegalType == 0 && LastLegalVectorType == 0)
11483       return false;
11484
11485     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11486     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11487
11488     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11489                                            true, UseVector);
11490   }
11491
11492   // When extracting multiple vector elements, try to store them
11493   // in one vector store rather than a sequence of scalar stores.
11494   if (IsExtractVecSrc) {
11495     unsigned NumStoresToMerge = 0;
11496     bool IsVec = MemVT.isVector();
11497     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11498       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11499       unsigned StoreValOpcode = St->getValue().getOpcode();
11500       // This restriction could be loosened.
11501       // Bail out if any stored values are not elements extracted from a vector.
11502       // It should be possible to handle mixed sources, but load sources need
11503       // more careful handling (see the block of code below that handles
11504       // consecutive loads).
11505       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11506           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11507         return false;
11508
11509       // Find a legal type for the vector store.
11510       unsigned Elts = i + 1;
11511       if (IsVec) {
11512         // When merging vector stores, get the total number of elements.
11513         Elts *= MemVT.getVectorNumElements();
11514       }
11515       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11516       bool IsFast;
11517       if (TLI.isTypeLegal(Ty) &&
11518           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11519                                  FirstStoreAlign, &IsFast) && IsFast)
11520         NumStoresToMerge = i + 1;
11521     }
11522
11523     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11524                                            false, true);
11525   }
11526
11527   // Below we handle the case of multiple consecutive stores that
11528   // come from multiple consecutive loads. We merge them into a single
11529   // wide load and a single wide store.
11530
11531   // Look for load nodes which are used by the stored values.
11532   SmallVector<MemOpLink, 8> LoadNodes;
11533
11534   // Find acceptable loads. Loads need to have the same chain (token factor),
11535   // must not be zext, volatile, indexed, and they must be consecutive.
11536   BaseIndexOffset LdBasePtr;
11537   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11538     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11539     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11540     if (!Ld) break;
11541
11542     // Loads must only have one use.
11543     if (!Ld->hasNUsesOfValue(1, 0))
11544       break;
11545
11546     // The memory operands must not be volatile.
11547     if (Ld->isVolatile() || Ld->isIndexed())
11548       break;
11549
11550     // We do not accept ext loads.
11551     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11552       break;
11553
11554     // The stored memory type must be the same.
11555     if (Ld->getMemoryVT() != MemVT)
11556       break;
11557
11558     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11559     // If this is not the first ptr that we check.
11560     if (LdBasePtr.Base.getNode()) {
11561       // The base ptr must be the same.
11562       if (!LdPtr.equalBaseIndex(LdBasePtr))
11563         break;
11564     } else {
11565       // Check that all other base pointers are the same as this one.
11566       LdBasePtr = LdPtr;
11567     }
11568
11569     // We found a potential memory operand to merge.
11570     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11571   }
11572
11573   if (LoadNodes.size() < 2)
11574     return false;
11575
11576   // If we have load/store pair instructions and we only have two values,
11577   // don't bother.
11578   unsigned RequiredAlignment;
11579   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11580       St->getAlignment() >= RequiredAlignment)
11581     return false;
11582
11583   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11584   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11585   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11586
11587   // Scan the memory operations on the chain and find the first non-consecutive
11588   // load memory address. These variables hold the index in the store node
11589   // array.
11590   unsigned LastConsecutiveLoad = 0;
11591   // This variable refers to the size and not index in the array.
11592   unsigned LastLegalVectorType = 0;
11593   unsigned LastLegalIntegerType = 0;
11594   StartAddress = LoadNodes[0].OffsetFromBase;
11595   SDValue FirstChain = FirstLoad->getChain();
11596   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11597     // All loads must share the same chain.
11598     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11599       break;
11600
11601     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11602     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11603       break;
11604     LastConsecutiveLoad = i;
11605     // Find a legal type for the vector store.
11606     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11607     bool IsFastSt, IsFastLd;
11608     if (TLI.isTypeLegal(StoreTy) &&
11609         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11610                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11611         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11612                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11613       LastLegalVectorType = i + 1;
11614     }
11615
11616     // Find a legal type for the integer store.
11617     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11618     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11619     if (TLI.isTypeLegal(StoreTy) &&
11620         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11621                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11622         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11623                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11624       LastLegalIntegerType = i + 1;
11625     // Or check whether a truncstore and extload is legal.
11626     else if (TLI.getTypeAction(Context, StoreTy) ==
11627              TargetLowering::TypePromoteInteger) {
11628       EVT LegalizedStoredValueTy =
11629         TLI.getTypeToTransformTo(Context, StoreTy);
11630       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11631           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11632           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11633           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11634           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11635                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11636           IsFastSt &&
11637           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11638                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11639           IsFastLd)
11640         LastLegalIntegerType = i+1;
11641     }
11642   }
11643
11644   // Only use vector types if the vector type is larger than the integer type.
11645   // If they are the same, use integers.
11646   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11647   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11648
11649   // We add +1 here because the LastXXX variables refer to location while
11650   // the NumElem refers to array/index size.
11651   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11652   NumElem = std::min(LastLegalType, NumElem);
11653
11654   if (NumElem < 2)
11655     return false;
11656
11657   // Collect the chains from all merged stores.
11658   SmallVector<SDValue, 8> MergeStoreChains;
11659   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11660
11661   // The latest Node in the DAG.
11662   unsigned LatestNodeUsed = 0;
11663   for (unsigned i=1; i<NumElem; ++i) {
11664     // Find a chain for the new wide-store operand. Notice that some
11665     // of the store nodes that we found may not be selected for inclusion
11666     // in the wide store. The chain we use needs to be the chain of the
11667     // latest store node which is *used* and replaced by the wide store.
11668     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11669       LatestNodeUsed = i;
11670
11671     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11672   }
11673
11674   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11675
11676   // Find if it is better to use vectors or integers to load and store
11677   // to memory.
11678   EVT JointMemOpVT;
11679   if (UseVectorTy) {
11680     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11681   } else {
11682     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11683     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11684   }
11685
11686   SDLoc LoadDL(LoadNodes[0].MemNode);
11687   SDLoc StoreDL(StoreNodes[0].MemNode);
11688
11689   // The merged loads are required to have the same incoming chain, so
11690   // using the first's chain is acceptable.
11691   SDValue NewLoad = DAG.getLoad(
11692       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11693       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11694
11695   SDValue NewStoreChain =
11696     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11697
11698   SDValue NewStore = DAG.getStore(
11699     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11700       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11701
11702   // Transfer chain users from old loads to the new load.
11703   for (unsigned i = 0; i < NumElem; ++i) {
11704     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11705     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11706                                   SDValue(NewLoad.getNode(), 1));
11707   }
11708
11709   // Replace the last store with the new store.
11710   CombineTo(LatestOp, NewStore);
11711   // Erase all other stores.
11712   for (unsigned i = 0; i < NumElem ; ++i) {
11713     // Remove all Store nodes.
11714     if (StoreNodes[i].MemNode == LatestOp)
11715       continue;
11716     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11717     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11718     deleteAndRecombine(St);
11719   }
11720
11721   return true;
11722 }
11723
11724 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11725   SDLoc SL(ST);
11726   SDValue ReplStore;
11727
11728   // Replace the chain to avoid dependency.
11729   if (ST->isTruncatingStore()) {
11730     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11731                                   ST->getBasePtr(), ST->getMemoryVT(),
11732                                   ST->getMemOperand());
11733   } else {
11734     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11735                              ST->getMemOperand());
11736   }
11737
11738   // Create token to keep both nodes around.
11739   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11740                               MVT::Other, ST->getChain(), ReplStore);
11741
11742   // Make sure the new and old chains are cleaned up.
11743   AddToWorklist(Token.getNode());
11744
11745   // Don't add users to work list.
11746   return CombineTo(ST, Token, false);
11747 }
11748
11749 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11750   SDValue Value = ST->getValue();
11751   if (Value.getOpcode() == ISD::TargetConstantFP)
11752     return SDValue();
11753
11754   SDLoc DL(ST);
11755
11756   SDValue Chain = ST->getChain();
11757   SDValue Ptr = ST->getBasePtr();
11758
11759   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11760
11761   // NOTE: If the original store is volatile, this transform must not increase
11762   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11763   // processor operation but an i64 (which is not legal) requires two.  So the
11764   // transform should not be done in this case.
11765
11766   SDValue Tmp;
11767   switch (CFP->getSimpleValueType(0).SimpleTy) {
11768   default:
11769     llvm_unreachable("Unknown FP type");
11770   case MVT::f16:    // We don't do this for these yet.
11771   case MVT::f80:
11772   case MVT::f128:
11773   case MVT::ppcf128:
11774     return SDValue();
11775   case MVT::f32:
11776     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11777         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11778       ;
11779       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11780                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11781                             MVT::i32);
11782       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11783     }
11784
11785     return SDValue();
11786   case MVT::f64:
11787     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11788          !ST->isVolatile()) ||
11789         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11790       ;
11791       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11792                             getZExtValue(), SDLoc(CFP), MVT::i64);
11793       return DAG.getStore(Chain, DL, Tmp,
11794                           Ptr, ST->getMemOperand());
11795     }
11796
11797     if (!ST->isVolatile() &&
11798         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11799       // Many FP stores are not made apparent until after legalize, e.g. for
11800       // argument passing.  Since this is so common, custom legalize the
11801       // 64-bit integer store into two 32-bit stores.
11802       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11803       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11804       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11805       if (DAG.getDataLayout().isBigEndian())
11806         std::swap(Lo, Hi);
11807
11808       unsigned Alignment = ST->getAlignment();
11809       bool isVolatile = ST->isVolatile();
11810       bool isNonTemporal = ST->isNonTemporal();
11811       AAMDNodes AAInfo = ST->getAAInfo();
11812
11813       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11814                                  Ptr, ST->getPointerInfo(),
11815                                  isVolatile, isNonTemporal,
11816                                  ST->getAlignment(), AAInfo);
11817       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11818                         DAG.getConstant(4, DL, Ptr.getValueType()));
11819       Alignment = MinAlign(Alignment, 4U);
11820       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11821                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11822                                  isVolatile, isNonTemporal,
11823                                  Alignment, AAInfo);
11824       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11825                          St0, St1);
11826     }
11827
11828     return SDValue();
11829   }
11830 }
11831
11832 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11833   StoreSDNode *ST  = cast<StoreSDNode>(N);
11834   SDValue Chain = ST->getChain();
11835   SDValue Value = ST->getValue();
11836   SDValue Ptr   = ST->getBasePtr();
11837
11838   // If this is a store of a bit convert, store the input value if the
11839   // resultant store does not need a higher alignment than the original.
11840   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11841       ST->isUnindexed()) {
11842     unsigned OrigAlign = ST->getAlignment();
11843     EVT SVT = Value.getOperand(0).getValueType();
11844     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11845         SVT.getTypeForEVT(*DAG.getContext()));
11846     if (Align <= OrigAlign &&
11847         ((!LegalOperations && !ST->isVolatile()) ||
11848          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11849       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11850                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11851                           ST->isNonTemporal(), OrigAlign,
11852                           ST->getAAInfo());
11853   }
11854
11855   // Turn 'store undef, Ptr' -> nothing.
11856   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11857     return Chain;
11858
11859   // Try to infer better alignment information than the store already has.
11860   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11861     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11862       if (Align > ST->getAlignment()) {
11863         SDValue NewStore =
11864                DAG.getTruncStore(Chain, SDLoc(N), Value,
11865                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11866                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11867                                  ST->getAAInfo());
11868         if (NewStore.getNode() != N)
11869           return CombineTo(ST, NewStore, true);
11870       }
11871     }
11872   }
11873
11874   // Try transforming a pair floating point load / store ops to integer
11875   // load / store ops.
11876   if (SDValue NewST = TransformFPLoadStorePair(N))
11877     return NewST;
11878
11879   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11880                                                   : DAG.getSubtarget().useAA();
11881 #ifndef NDEBUG
11882   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11883       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11884     UseAA = false;
11885 #endif
11886   if (UseAA && ST->isUnindexed()) {
11887     // FIXME: We should do this even without AA enabled. AA will just allow
11888     // FindBetterChain to work in more situations. The problem with this is that
11889     // any combine that expects memory operations to be on consecutive chains
11890     // first needs to be updated to look for users of the same chain.
11891
11892     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11893     // adjacent stores.
11894     if (findBetterNeighborChains(ST)) {
11895       // replaceStoreChain uses CombineTo, which handled all of the worklist
11896       // manipulation. Return the original node to not do anything else.
11897       return SDValue(ST, 0);
11898     }
11899   }
11900
11901   // Try transforming N to an indexed store.
11902   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11903     return SDValue(N, 0);
11904
11905   // FIXME: is there such a thing as a truncating indexed store?
11906   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11907       Value.getValueType().isInteger()) {
11908     // See if we can simplify the input to this truncstore with knowledge that
11909     // only the low bits are being used.  For example:
11910     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11911     SDValue Shorter =
11912       GetDemandedBits(Value,
11913                       APInt::getLowBitsSet(
11914                         Value.getValueType().getScalarType().getSizeInBits(),
11915                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11916     AddToWorklist(Value.getNode());
11917     if (Shorter.getNode())
11918       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11919                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11920
11921     // Otherwise, see if we can simplify the operation with
11922     // SimplifyDemandedBits, which only works if the value has a single use.
11923     if (SimplifyDemandedBits(Value,
11924                         APInt::getLowBitsSet(
11925                           Value.getValueType().getScalarType().getSizeInBits(),
11926                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11927       return SDValue(N, 0);
11928   }
11929
11930   // If this is a load followed by a store to the same location, then the store
11931   // is dead/noop.
11932   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11933     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11934         ST->isUnindexed() && !ST->isVolatile() &&
11935         // There can't be any side effects between the load and store, such as
11936         // a call or store.
11937         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11938       // The store is dead, remove it.
11939       return Chain;
11940     }
11941   }
11942
11943   // If this is a store followed by a store with the same value to the same
11944   // location, then the store is dead/noop.
11945   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11946     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11947         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11948         ST1->isUnindexed() && !ST1->isVolatile()) {
11949       // The store is dead, remove it.
11950       return Chain;
11951     }
11952   }
11953
11954   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11955   // truncating store.  We can do this even if this is already a truncstore.
11956   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11957       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11958       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11959                             ST->getMemoryVT())) {
11960     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11961                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11962   }
11963
11964   // Only perform this optimization before the types are legal, because we
11965   // don't want to perform this optimization on every DAGCombine invocation.
11966   if (!LegalTypes) {
11967     bool EverChanged = false;
11968
11969     do {
11970       // There can be multiple store sequences on the same chain.
11971       // Keep trying to merge store sequences until we are unable to do so
11972       // or until we merge the last store on the chain.
11973       bool Changed = MergeConsecutiveStores(ST);
11974       EverChanged |= Changed;
11975       if (!Changed) break;
11976     } while (ST->getOpcode() != ISD::DELETED_NODE);
11977
11978     if (EverChanged)
11979       return SDValue(N, 0);
11980   }
11981
11982   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11983   //
11984   // Make sure to do this only after attempting to merge stores in order to
11985   //  avoid changing the types of some subset of stores due to visit order,
11986   //  preventing their merging.
11987   if (isa<ConstantFPSDNode>(Value)) {
11988     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11989       return NewSt;
11990   }
11991
11992   return ReduceLoadOpStoreWidth(N);
11993 }
11994
11995 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11996   SDValue InVec = N->getOperand(0);
11997   SDValue InVal = N->getOperand(1);
11998   SDValue EltNo = N->getOperand(2);
11999   SDLoc dl(N);
12000
12001   // If the inserted element is an UNDEF, just use the input vector.
12002   if (InVal.getOpcode() == ISD::UNDEF)
12003     return InVec;
12004
12005   EVT VT = InVec.getValueType();
12006
12007   // If we can't generate a legal BUILD_VECTOR, exit
12008   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12009     return SDValue();
12010
12011   // Check that we know which element is being inserted
12012   if (!isa<ConstantSDNode>(EltNo))
12013     return SDValue();
12014   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12015
12016   // Canonicalize insert_vector_elt dag nodes.
12017   // Example:
12018   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12019   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12020   //
12021   // Do this only if the child insert_vector node has one use; also
12022   // do this only if indices are both constants and Idx1 < Idx0.
12023   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12024       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12025     unsigned OtherElt =
12026       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12027     if (Elt < OtherElt) {
12028       // Swap nodes.
12029       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12030                                   InVec.getOperand(0), InVal, EltNo);
12031       AddToWorklist(NewOp.getNode());
12032       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12033                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12034     }
12035   }
12036
12037   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12038   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12039   // vector elements.
12040   SmallVector<SDValue, 8> Ops;
12041   // Do not combine these two vectors if the output vector will not replace
12042   // the input vector.
12043   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12044     Ops.append(InVec.getNode()->op_begin(),
12045                InVec.getNode()->op_end());
12046   } else if (InVec.getOpcode() == ISD::UNDEF) {
12047     unsigned NElts = VT.getVectorNumElements();
12048     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12049   } else {
12050     return SDValue();
12051   }
12052
12053   // Insert the element
12054   if (Elt < Ops.size()) {
12055     // All the operands of BUILD_VECTOR must have the same type;
12056     // we enforce that here.
12057     EVT OpVT = Ops[0].getValueType();
12058     if (InVal.getValueType() != OpVT)
12059       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12060                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12061                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12062     Ops[Elt] = InVal;
12063   }
12064
12065   // Return the new vector
12066   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
12067 }
12068
12069 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12070     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12071   EVT ResultVT = EVE->getValueType(0);
12072   EVT VecEltVT = InVecVT.getVectorElementType();
12073   unsigned Align = OriginalLoad->getAlignment();
12074   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12075       VecEltVT.getTypeForEVT(*DAG.getContext()));
12076
12077   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12078     return SDValue();
12079
12080   Align = NewAlign;
12081
12082   SDValue NewPtr = OriginalLoad->getBasePtr();
12083   SDValue Offset;
12084   EVT PtrType = NewPtr.getValueType();
12085   MachinePointerInfo MPI;
12086   SDLoc DL(EVE);
12087   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12088     int Elt = ConstEltNo->getZExtValue();
12089     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12090     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12091     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12092   } else {
12093     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12094     Offset = DAG.getNode(
12095         ISD::MUL, DL, PtrType, Offset,
12096         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12097     MPI = OriginalLoad->getPointerInfo();
12098   }
12099   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12100
12101   // The replacement we need to do here is a little tricky: we need to
12102   // replace an extractelement of a load with a load.
12103   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12104   // Note that this replacement assumes that the extractvalue is the only
12105   // use of the load; that's okay because we don't want to perform this
12106   // transformation in other cases anyway.
12107   SDValue Load;
12108   SDValue Chain;
12109   if (ResultVT.bitsGT(VecEltVT)) {
12110     // If the result type of vextract is wider than the load, then issue an
12111     // extending load instead.
12112     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12113                                                   VecEltVT)
12114                                    ? ISD::ZEXTLOAD
12115                                    : ISD::EXTLOAD;
12116     Load = DAG.getExtLoad(
12117         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12118         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12119         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12120     Chain = Load.getValue(1);
12121   } else {
12122     Load = DAG.getLoad(
12123         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12124         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12125         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12126     Chain = Load.getValue(1);
12127     if (ResultVT.bitsLT(VecEltVT))
12128       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12129     else
12130       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12131   }
12132   WorklistRemover DeadNodes(*this);
12133   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12134   SDValue To[] = { Load, Chain };
12135   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12136   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12137   // worklist explicitly as well.
12138   AddToWorklist(Load.getNode());
12139   AddUsersToWorklist(Load.getNode()); // Add users too
12140   // Make sure to revisit this node to clean it up; it will usually be dead.
12141   AddToWorklist(EVE);
12142   ++OpsNarrowed;
12143   return SDValue(EVE, 0);
12144 }
12145
12146 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12147   // (vextract (scalar_to_vector val, 0) -> val
12148   SDValue InVec = N->getOperand(0);
12149   EVT VT = InVec.getValueType();
12150   EVT NVT = N->getValueType(0);
12151
12152   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12153     // Check if the result type doesn't match the inserted element type. A
12154     // SCALAR_TO_VECTOR may truncate the inserted element and the
12155     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12156     SDValue InOp = InVec.getOperand(0);
12157     if (InOp.getValueType() != NVT) {
12158       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12159       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12160     }
12161     return InOp;
12162   }
12163
12164   SDValue EltNo = N->getOperand(1);
12165   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12166
12167   // extract_vector_elt (build_vector x, y), 1 -> y
12168   if (ConstEltNo &&
12169       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12170       TLI.isTypeLegal(VT) &&
12171       (InVec.hasOneUse() ||
12172        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12173     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12174     EVT InEltVT = Elt.getValueType();
12175
12176     // Sometimes build_vector's scalar input types do not match result type.
12177     if (NVT == InEltVT)
12178       return Elt;
12179
12180     // TODO: It may be useful to truncate if free if the build_vector implicitly
12181     // converts.
12182   }
12183
12184   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12185   // We only perform this optimization before the op legalization phase because
12186   // we may introduce new vector instructions which are not backed by TD
12187   // patterns. For example on AVX, extracting elements from a wide vector
12188   // without using extract_subvector. However, if we can find an underlying
12189   // scalar value, then we can always use that.
12190   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12191     int NumElem = VT.getVectorNumElements();
12192     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12193     // Find the new index to extract from.
12194     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12195
12196     // Extracting an undef index is undef.
12197     if (OrigElt == -1)
12198       return DAG.getUNDEF(NVT);
12199
12200     // Select the right vector half to extract from.
12201     SDValue SVInVec;
12202     if (OrigElt < NumElem) {
12203       SVInVec = InVec->getOperand(0);
12204     } else {
12205       SVInVec = InVec->getOperand(1);
12206       OrigElt -= NumElem;
12207     }
12208
12209     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12210       SDValue InOp = SVInVec.getOperand(OrigElt);
12211       if (InOp.getValueType() != NVT) {
12212         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12213         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12214       }
12215
12216       return InOp;
12217     }
12218
12219     // FIXME: We should handle recursing on other vector shuffles and
12220     // scalar_to_vector here as well.
12221
12222     if (!LegalOperations) {
12223       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12224       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12225                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12226     }
12227   }
12228
12229   bool BCNumEltsChanged = false;
12230   EVT ExtVT = VT.getVectorElementType();
12231   EVT LVT = ExtVT;
12232
12233   // If the result of load has to be truncated, then it's not necessarily
12234   // profitable.
12235   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12236     return SDValue();
12237
12238   if (InVec.getOpcode() == ISD::BITCAST) {
12239     // Don't duplicate a load with other uses.
12240     if (!InVec.hasOneUse())
12241       return SDValue();
12242
12243     EVT BCVT = InVec.getOperand(0).getValueType();
12244     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12245       return SDValue();
12246     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12247       BCNumEltsChanged = true;
12248     InVec = InVec.getOperand(0);
12249     ExtVT = BCVT.getVectorElementType();
12250   }
12251
12252   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12253   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12254       ISD::isNormalLoad(InVec.getNode()) &&
12255       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12256     SDValue Index = N->getOperand(1);
12257     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12258       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12259                                                            OrigLoad);
12260   }
12261
12262   // Perform only after legalization to ensure build_vector / vector_shuffle
12263   // optimizations have already been done.
12264   if (!LegalOperations) return SDValue();
12265
12266   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12267   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12268   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12269
12270   if (ConstEltNo) {
12271     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12272
12273     LoadSDNode *LN0 = nullptr;
12274     const ShuffleVectorSDNode *SVN = nullptr;
12275     if (ISD::isNormalLoad(InVec.getNode())) {
12276       LN0 = cast<LoadSDNode>(InVec);
12277     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12278                InVec.getOperand(0).getValueType() == ExtVT &&
12279                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12280       // Don't duplicate a load with other uses.
12281       if (!InVec.hasOneUse())
12282         return SDValue();
12283
12284       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12285     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12286       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12287       // =>
12288       // (load $addr+1*size)
12289
12290       // Don't duplicate a load with other uses.
12291       if (!InVec.hasOneUse())
12292         return SDValue();
12293
12294       // If the bit convert changed the number of elements, it is unsafe
12295       // to examine the mask.
12296       if (BCNumEltsChanged)
12297         return SDValue();
12298
12299       // Select the input vector, guarding against out of range extract vector.
12300       unsigned NumElems = VT.getVectorNumElements();
12301       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12302       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12303
12304       if (InVec.getOpcode() == ISD::BITCAST) {
12305         // Don't duplicate a load with other uses.
12306         if (!InVec.hasOneUse())
12307           return SDValue();
12308
12309         InVec = InVec.getOperand(0);
12310       }
12311       if (ISD::isNormalLoad(InVec.getNode())) {
12312         LN0 = cast<LoadSDNode>(InVec);
12313         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12314         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12315       }
12316     }
12317
12318     // Make sure we found a non-volatile load and the extractelement is
12319     // the only use.
12320     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12321       return SDValue();
12322
12323     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12324     if (Elt == -1)
12325       return DAG.getUNDEF(LVT);
12326
12327     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12328   }
12329
12330   return SDValue();
12331 }
12332
12333 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12334 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12335   // We perform this optimization post type-legalization because
12336   // the type-legalizer often scalarizes integer-promoted vectors.
12337   // Performing this optimization before may create bit-casts which
12338   // will be type-legalized to complex code sequences.
12339   // We perform this optimization only before the operation legalizer because we
12340   // may introduce illegal operations.
12341   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12342     return SDValue();
12343
12344   unsigned NumInScalars = N->getNumOperands();
12345   SDLoc dl(N);
12346   EVT VT = N->getValueType(0);
12347
12348   // Check to see if this is a BUILD_VECTOR of a bunch of values
12349   // which come from any_extend or zero_extend nodes. If so, we can create
12350   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12351   // optimizations. We do not handle sign-extend because we can't fill the sign
12352   // using shuffles.
12353   EVT SourceType = MVT::Other;
12354   bool AllAnyExt = true;
12355
12356   for (unsigned i = 0; i != NumInScalars; ++i) {
12357     SDValue In = N->getOperand(i);
12358     // Ignore undef inputs.
12359     if (In.getOpcode() == ISD::UNDEF) continue;
12360
12361     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12362     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12363
12364     // Abort if the element is not an extension.
12365     if (!ZeroExt && !AnyExt) {
12366       SourceType = MVT::Other;
12367       break;
12368     }
12369
12370     // The input is a ZeroExt or AnyExt. Check the original type.
12371     EVT InTy = In.getOperand(0).getValueType();
12372
12373     // Check that all of the widened source types are the same.
12374     if (SourceType == MVT::Other)
12375       // First time.
12376       SourceType = InTy;
12377     else if (InTy != SourceType) {
12378       // Multiple income types. Abort.
12379       SourceType = MVT::Other;
12380       break;
12381     }
12382
12383     // Check if all of the extends are ANY_EXTENDs.
12384     AllAnyExt &= AnyExt;
12385   }
12386
12387   // In order to have valid types, all of the inputs must be extended from the
12388   // same source type and all of the inputs must be any or zero extend.
12389   // Scalar sizes must be a power of two.
12390   EVT OutScalarTy = VT.getScalarType();
12391   bool ValidTypes = SourceType != MVT::Other &&
12392                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12393                  isPowerOf2_32(SourceType.getSizeInBits());
12394
12395   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12396   // turn into a single shuffle instruction.
12397   if (!ValidTypes)
12398     return SDValue();
12399
12400   bool isLE = DAG.getDataLayout().isLittleEndian();
12401   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12402   assert(ElemRatio > 1 && "Invalid element size ratio");
12403   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12404                                DAG.getConstant(0, SDLoc(N), SourceType);
12405
12406   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12407   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12408
12409   // Populate the new build_vector
12410   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12411     SDValue Cast = N->getOperand(i);
12412     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12413             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12414             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12415     SDValue In;
12416     if (Cast.getOpcode() == ISD::UNDEF)
12417       In = DAG.getUNDEF(SourceType);
12418     else
12419       In = Cast->getOperand(0);
12420     unsigned Index = isLE ? (i * ElemRatio) :
12421                             (i * ElemRatio + (ElemRatio - 1));
12422
12423     assert(Index < Ops.size() && "Invalid index");
12424     Ops[Index] = In;
12425   }
12426
12427   // The type of the new BUILD_VECTOR node.
12428   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12429   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12430          "Invalid vector size");
12431   // Check if the new vector type is legal.
12432   if (!isTypeLegal(VecVT)) return SDValue();
12433
12434   // Make the new BUILD_VECTOR.
12435   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12436
12437   // The new BUILD_VECTOR node has the potential to be further optimized.
12438   AddToWorklist(BV.getNode());
12439   // Bitcast to the desired type.
12440   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12441 }
12442
12443 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12444   EVT VT = N->getValueType(0);
12445
12446   unsigned NumInScalars = N->getNumOperands();
12447   SDLoc dl(N);
12448
12449   EVT SrcVT = MVT::Other;
12450   unsigned Opcode = ISD::DELETED_NODE;
12451   unsigned NumDefs = 0;
12452
12453   for (unsigned i = 0; i != NumInScalars; ++i) {
12454     SDValue In = N->getOperand(i);
12455     unsigned Opc = In.getOpcode();
12456
12457     if (Opc == ISD::UNDEF)
12458       continue;
12459
12460     // If all scalar values are floats and converted from integers.
12461     if (Opcode == ISD::DELETED_NODE &&
12462         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12463       Opcode = Opc;
12464     }
12465
12466     if (Opc != Opcode)
12467       return SDValue();
12468
12469     EVT InVT = In.getOperand(0).getValueType();
12470
12471     // If all scalar values are typed differently, bail out. It's chosen to
12472     // simplify BUILD_VECTOR of integer types.
12473     if (SrcVT == MVT::Other)
12474       SrcVT = InVT;
12475     if (SrcVT != InVT)
12476       return SDValue();
12477     NumDefs++;
12478   }
12479
12480   // If the vector has just one element defined, it's not worth to fold it into
12481   // a vectorized one.
12482   if (NumDefs < 2)
12483     return SDValue();
12484
12485   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12486          && "Should only handle conversion from integer to float.");
12487   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12488
12489   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12490
12491   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12492     return SDValue();
12493
12494   // Just because the floating-point vector type is legal does not necessarily
12495   // mean that the corresponding integer vector type is.
12496   if (!isTypeLegal(NVT))
12497     return SDValue();
12498
12499   SmallVector<SDValue, 8> Opnds;
12500   for (unsigned i = 0; i != NumInScalars; ++i) {
12501     SDValue In = N->getOperand(i);
12502
12503     if (In.getOpcode() == ISD::UNDEF)
12504       Opnds.push_back(DAG.getUNDEF(SrcVT));
12505     else
12506       Opnds.push_back(In.getOperand(0));
12507   }
12508   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12509   AddToWorklist(BV.getNode());
12510
12511   return DAG.getNode(Opcode, dl, VT, BV);
12512 }
12513
12514 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12515   unsigned NumInScalars = N->getNumOperands();
12516   SDLoc dl(N);
12517   EVT VT = N->getValueType(0);
12518
12519   // A vector built entirely of undefs is undef.
12520   if (ISD::allOperandsUndef(N))
12521     return DAG.getUNDEF(VT);
12522
12523   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12524     return V;
12525
12526   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12527     return V;
12528
12529   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12530   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12531   // at most two distinct vectors, turn this into a shuffle node.
12532
12533   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12534   if (!isTypeLegal(VT))
12535     return SDValue();
12536
12537   // May only combine to shuffle after legalize if shuffle is legal.
12538   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12539     return SDValue();
12540
12541   SDValue VecIn1, VecIn2;
12542   bool UsesZeroVector = false;
12543   for (unsigned i = 0; i != NumInScalars; ++i) {
12544     SDValue Op = N->getOperand(i);
12545     // Ignore undef inputs.
12546     if (Op.getOpcode() == ISD::UNDEF) continue;
12547
12548     // See if we can combine this build_vector into a blend with a zero vector.
12549     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12550       UsesZeroVector = true;
12551       continue;
12552     }
12553
12554     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12555     // constant index, bail out.
12556     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12557         !isa<ConstantSDNode>(Op.getOperand(1))) {
12558       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12559       break;
12560     }
12561
12562     // We allow up to two distinct input vectors.
12563     SDValue ExtractedFromVec = Op.getOperand(0);
12564     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12565       continue;
12566
12567     if (!VecIn1.getNode()) {
12568       VecIn1 = ExtractedFromVec;
12569     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12570       VecIn2 = ExtractedFromVec;
12571     } else {
12572       // Too many inputs.
12573       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12574       break;
12575     }
12576   }
12577
12578   // If everything is good, we can make a shuffle operation.
12579   if (VecIn1.getNode()) {
12580     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12581     SmallVector<int, 8> Mask;
12582     for (unsigned i = 0; i != NumInScalars; ++i) {
12583       unsigned Opcode = N->getOperand(i).getOpcode();
12584       if (Opcode == ISD::UNDEF) {
12585         Mask.push_back(-1);
12586         continue;
12587       }
12588
12589       // Operands can also be zero.
12590       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12591         assert(UsesZeroVector &&
12592                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12593                "Unexpected node found!");
12594         Mask.push_back(NumInScalars+i);
12595         continue;
12596       }
12597
12598       // If extracting from the first vector, just use the index directly.
12599       SDValue Extract = N->getOperand(i);
12600       SDValue ExtVal = Extract.getOperand(1);
12601       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12602       if (Extract.getOperand(0) == VecIn1) {
12603         Mask.push_back(ExtIndex);
12604         continue;
12605       }
12606
12607       // Otherwise, use InIdx + InputVecSize
12608       Mask.push_back(InNumElements + ExtIndex);
12609     }
12610
12611     // Avoid introducing illegal shuffles with zero.
12612     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12613       return SDValue();
12614
12615     // We can't generate a shuffle node with mismatched input and output types.
12616     // Attempt to transform a single input vector to the correct type.
12617     if ((VT != VecIn1.getValueType())) {
12618       // If the input vector type has a different base type to the output
12619       // vector type, bail out.
12620       EVT VTElemType = VT.getVectorElementType();
12621       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12622           (VecIn2.getNode() &&
12623            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12624         return SDValue();
12625
12626       // If the input vector is too small, widen it.
12627       // We only support widening of vectors which are half the size of the
12628       // output registers. For example XMM->YMM widening on X86 with AVX.
12629       EVT VecInT = VecIn1.getValueType();
12630       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12631         // If we only have one small input, widen it by adding undef values.
12632         if (!VecIn2.getNode())
12633           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12634                                DAG.getUNDEF(VecIn1.getValueType()));
12635         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12636           // If we have two small inputs of the same type, try to concat them.
12637           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12638           VecIn2 = SDValue(nullptr, 0);
12639         } else
12640           return SDValue();
12641       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12642         // If the input vector is too large, try to split it.
12643         // We don't support having two input vectors that are too large.
12644         // If the zero vector was used, we can not split the vector,
12645         // since we'd need 3 inputs.
12646         if (UsesZeroVector || VecIn2.getNode())
12647           return SDValue();
12648
12649         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12650           return SDValue();
12651
12652         // Try to replace VecIn1 with two extract_subvectors
12653         // No need to update the masks, they should still be correct.
12654         VecIn2 = DAG.getNode(
12655             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12656             DAG.getConstant(VT.getVectorNumElements(), dl,
12657                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12658         VecIn1 = DAG.getNode(
12659             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12660             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12661       } else
12662         return SDValue();
12663     }
12664
12665     if (UsesZeroVector)
12666       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12667                                 DAG.getConstantFP(0.0, dl, VT);
12668     else
12669       // If VecIn2 is unused then change it to undef.
12670       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12671
12672     // Check that we were able to transform all incoming values to the same
12673     // type.
12674     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12675         VecIn1.getValueType() != VT)
12676           return SDValue();
12677
12678     // Return the new VECTOR_SHUFFLE node.
12679     SDValue Ops[2];
12680     Ops[0] = VecIn1;
12681     Ops[1] = VecIn2;
12682     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12683   }
12684
12685   return SDValue();
12686 }
12687
12688 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12689   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12690   EVT OpVT = N->getOperand(0).getValueType();
12691
12692   // If the operands are legal vectors, leave them alone.
12693   if (TLI.isTypeLegal(OpVT))
12694     return SDValue();
12695
12696   SDLoc DL(N);
12697   EVT VT = N->getValueType(0);
12698   SmallVector<SDValue, 8> Ops;
12699
12700   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12701   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12702
12703   // Keep track of what we encounter.
12704   bool AnyInteger = false;
12705   bool AnyFP = false;
12706   for (const SDValue &Op : N->ops()) {
12707     if (ISD::BITCAST == Op.getOpcode() &&
12708         !Op.getOperand(0).getValueType().isVector())
12709       Ops.push_back(Op.getOperand(0));
12710     else if (ISD::UNDEF == Op.getOpcode())
12711       Ops.push_back(ScalarUndef);
12712     else
12713       return SDValue();
12714
12715     // Note whether we encounter an integer or floating point scalar.
12716     // If it's neither, bail out, it could be something weird like x86mmx.
12717     EVT LastOpVT = Ops.back().getValueType();
12718     if (LastOpVT.isFloatingPoint())
12719       AnyFP = true;
12720     else if (LastOpVT.isInteger())
12721       AnyInteger = true;
12722     else
12723       return SDValue();
12724   }
12725
12726   // If any of the operands is a floating point scalar bitcast to a vector,
12727   // use floating point types throughout, and bitcast everything.
12728   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12729   if (AnyFP) {
12730     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12731     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12732     if (AnyInteger) {
12733       for (SDValue &Op : Ops) {
12734         if (Op.getValueType() == SVT)
12735           continue;
12736         if (Op.getOpcode() == ISD::UNDEF)
12737           Op = ScalarUndef;
12738         else
12739           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12740       }
12741     }
12742   }
12743
12744   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12745                                VT.getSizeInBits() / SVT.getSizeInBits());
12746   return DAG.getNode(ISD::BITCAST, DL, VT,
12747                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12748 }
12749
12750 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12751 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12752 // most two distinct vectors the same size as the result, attempt to turn this
12753 // into a legal shuffle.
12754 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12755   EVT VT = N->getValueType(0);
12756   EVT OpVT = N->getOperand(0).getValueType();
12757   int NumElts = VT.getVectorNumElements();
12758   int NumOpElts = OpVT.getVectorNumElements();
12759
12760   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12761   SmallVector<int, 8> Mask;
12762
12763   for (SDValue Op : N->ops()) {
12764     // Peek through any bitcast.
12765     while (Op.getOpcode() == ISD::BITCAST)
12766       Op = Op.getOperand(0);
12767
12768     // UNDEF nodes convert to UNDEF shuffle mask values.
12769     if (Op.getOpcode() == ISD::UNDEF) {
12770       Mask.append((unsigned)NumOpElts, -1);
12771       continue;
12772     }
12773
12774     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12775       return SDValue();
12776
12777     // What vector are we extracting the subvector from and at what index?
12778     SDValue ExtVec = Op.getOperand(0);
12779
12780     // We want the EVT of the original extraction to correctly scale the
12781     // extraction index.
12782     EVT ExtVT = ExtVec.getValueType();
12783
12784     // Peek through any bitcast.
12785     while (ExtVec.getOpcode() == ISD::BITCAST)
12786       ExtVec = ExtVec.getOperand(0);
12787
12788     // UNDEF nodes convert to UNDEF shuffle mask values.
12789     if (ExtVec.getOpcode() == ISD::UNDEF) {
12790       Mask.append((unsigned)NumOpElts, -1);
12791       continue;
12792     }
12793
12794     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12795       return SDValue();
12796     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12797
12798     // Ensure that we are extracting a subvector from a vector the same
12799     // size as the result.
12800     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12801       return SDValue();
12802
12803     // Scale the subvector index to account for any bitcast.
12804     int NumExtElts = ExtVT.getVectorNumElements();
12805     if (0 == (NumExtElts % NumElts))
12806       ExtIdx /= (NumExtElts / NumElts);
12807     else if (0 == (NumElts % NumExtElts))
12808       ExtIdx *= (NumElts / NumExtElts);
12809     else
12810       return SDValue();
12811
12812     // At most we can reference 2 inputs in the final shuffle.
12813     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12814       SV0 = ExtVec;
12815       for (int i = 0; i != NumOpElts; ++i)
12816         Mask.push_back(i + ExtIdx);
12817     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12818       SV1 = ExtVec;
12819       for (int i = 0; i != NumOpElts; ++i)
12820         Mask.push_back(i + ExtIdx + NumElts);
12821     } else {
12822       return SDValue();
12823     }
12824   }
12825
12826   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12827     return SDValue();
12828
12829   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12830                               DAG.getBitcast(VT, SV1), Mask);
12831 }
12832
12833 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12834   // If we only have one input vector, we don't need to do any concatenation.
12835   if (N->getNumOperands() == 1)
12836     return N->getOperand(0);
12837
12838   // Check if all of the operands are undefs.
12839   EVT VT = N->getValueType(0);
12840   if (ISD::allOperandsUndef(N))
12841     return DAG.getUNDEF(VT);
12842
12843   // Optimize concat_vectors where all but the first of the vectors are undef.
12844   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12845         return Op.getOpcode() == ISD::UNDEF;
12846       })) {
12847     SDValue In = N->getOperand(0);
12848     assert(In.getValueType().isVector() && "Must concat vectors");
12849
12850     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12851     if (In->getOpcode() == ISD::BITCAST &&
12852         !In->getOperand(0)->getValueType(0).isVector()) {
12853       SDValue Scalar = In->getOperand(0);
12854
12855       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12856       // look through the trunc so we can still do the transform:
12857       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12858       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12859           !TLI.isTypeLegal(Scalar.getValueType()) &&
12860           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12861         Scalar = Scalar->getOperand(0);
12862
12863       EVT SclTy = Scalar->getValueType(0);
12864
12865       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12866         return SDValue();
12867
12868       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12869                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12870       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12871         return SDValue();
12872
12873       SDLoc dl = SDLoc(N);
12874       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12875       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12876     }
12877   }
12878
12879   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12880   // We have already tested above for an UNDEF only concatenation.
12881   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12882   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12883   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12884     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12885   };
12886   bool AllBuildVectorsOrUndefs =
12887       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12888   if (AllBuildVectorsOrUndefs) {
12889     SmallVector<SDValue, 8> Opnds;
12890     EVT SVT = VT.getScalarType();
12891
12892     EVT MinVT = SVT;
12893     if (!SVT.isFloatingPoint()) {
12894       // If BUILD_VECTOR are from built from integer, they may have different
12895       // operand types. Get the smallest type and truncate all operands to it.
12896       bool FoundMinVT = false;
12897       for (const SDValue &Op : N->ops())
12898         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12899           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12900           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12901           FoundMinVT = true;
12902         }
12903       assert(FoundMinVT && "Concat vector type mismatch");
12904     }
12905
12906     for (const SDValue &Op : N->ops()) {
12907       EVT OpVT = Op.getValueType();
12908       unsigned NumElts = OpVT.getVectorNumElements();
12909
12910       if (ISD::UNDEF == Op.getOpcode())
12911         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12912
12913       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12914         if (SVT.isFloatingPoint()) {
12915           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12916           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12917         } else {
12918           for (unsigned i = 0; i != NumElts; ++i)
12919             Opnds.push_back(
12920                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12921         }
12922       }
12923     }
12924
12925     assert(VT.getVectorNumElements() == Opnds.size() &&
12926            "Concat vector type mismatch");
12927     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12928   }
12929
12930   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12931   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12932     return V;
12933
12934   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12935   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12936     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12937       return V;
12938
12939   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12940   // nodes often generate nop CONCAT_VECTOR nodes.
12941   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12942   // place the incoming vectors at the exact same location.
12943   SDValue SingleSource = SDValue();
12944   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12945
12946   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12947     SDValue Op = N->getOperand(i);
12948
12949     if (Op.getOpcode() == ISD::UNDEF)
12950       continue;
12951
12952     // Check if this is the identity extract:
12953     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12954       return SDValue();
12955
12956     // Find the single incoming vector for the extract_subvector.
12957     if (SingleSource.getNode()) {
12958       if (Op.getOperand(0) != SingleSource)
12959         return SDValue();
12960     } else {
12961       SingleSource = Op.getOperand(0);
12962
12963       // Check the source type is the same as the type of the result.
12964       // If not, this concat may extend the vector, so we can not
12965       // optimize it away.
12966       if (SingleSource.getValueType() != N->getValueType(0))
12967         return SDValue();
12968     }
12969
12970     unsigned IdentityIndex = i * PartNumElem;
12971     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12972     // The extract index must be constant.
12973     if (!CS)
12974       return SDValue();
12975
12976     // Check that we are reading from the identity index.
12977     if (CS->getZExtValue() != IdentityIndex)
12978       return SDValue();
12979   }
12980
12981   if (SingleSource.getNode())
12982     return SingleSource;
12983
12984   return SDValue();
12985 }
12986
12987 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12988   EVT NVT = N->getValueType(0);
12989   SDValue V = N->getOperand(0);
12990
12991   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12992     // Combine:
12993     //    (extract_subvec (concat V1, V2, ...), i)
12994     // Into:
12995     //    Vi if possible
12996     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12997     // type.
12998     if (V->getOperand(0).getValueType() != NVT)
12999       return SDValue();
13000     unsigned Idx = N->getConstantOperandVal(1);
13001     unsigned NumElems = NVT.getVectorNumElements();
13002     assert((Idx % NumElems) == 0 &&
13003            "IDX in concat is not a multiple of the result vector length.");
13004     return V->getOperand(Idx / NumElems);
13005   }
13006
13007   // Skip bitcasting
13008   if (V->getOpcode() == ISD::BITCAST)
13009     V = V.getOperand(0);
13010
13011   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13012     SDLoc dl(N);
13013     // Handle only simple case where vector being inserted and vector
13014     // being extracted are of same type, and are half size of larger vectors.
13015     EVT BigVT = V->getOperand(0).getValueType();
13016     EVT SmallVT = V->getOperand(1).getValueType();
13017     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13018       return SDValue();
13019
13020     // Only handle cases where both indexes are constants with the same type.
13021     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13022     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13023
13024     if (InsIdx && ExtIdx &&
13025         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13026         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13027       // Combine:
13028       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13029       // Into:
13030       //    indices are equal or bit offsets are equal => V1
13031       //    otherwise => (extract_subvec V1, ExtIdx)
13032       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13033           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13034         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
13035       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
13036                          DAG.getNode(ISD::BITCAST, dl,
13037                                      N->getOperand(0).getValueType(),
13038                                      V->getOperand(0)), N->getOperand(1));
13039     }
13040   }
13041
13042   return SDValue();
13043 }
13044
13045 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13046                                                  SDValue V, SelectionDAG &DAG) {
13047   SDLoc DL(V);
13048   EVT VT = V.getValueType();
13049
13050   switch (V.getOpcode()) {
13051   default:
13052     return V;
13053
13054   case ISD::CONCAT_VECTORS: {
13055     EVT OpVT = V->getOperand(0).getValueType();
13056     int OpSize = OpVT.getVectorNumElements();
13057     SmallBitVector OpUsedElements(OpSize, false);
13058     bool FoundSimplification = false;
13059     SmallVector<SDValue, 4> NewOps;
13060     NewOps.reserve(V->getNumOperands());
13061     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13062       SDValue Op = V->getOperand(i);
13063       bool OpUsed = false;
13064       for (int j = 0; j < OpSize; ++j)
13065         if (UsedElements[i * OpSize + j]) {
13066           OpUsedElements[j] = true;
13067           OpUsed = true;
13068         }
13069       NewOps.push_back(
13070           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13071                  : DAG.getUNDEF(OpVT));
13072       FoundSimplification |= Op == NewOps.back();
13073       OpUsedElements.reset();
13074     }
13075     if (FoundSimplification)
13076       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13077     return V;
13078   }
13079
13080   case ISD::INSERT_SUBVECTOR: {
13081     SDValue BaseV = V->getOperand(0);
13082     SDValue SubV = V->getOperand(1);
13083     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13084     if (!IdxN)
13085       return V;
13086
13087     int SubSize = SubV.getValueType().getVectorNumElements();
13088     int Idx = IdxN->getZExtValue();
13089     bool SubVectorUsed = false;
13090     SmallBitVector SubUsedElements(SubSize, false);
13091     for (int i = 0; i < SubSize; ++i)
13092       if (UsedElements[i + Idx]) {
13093         SubVectorUsed = true;
13094         SubUsedElements[i] = true;
13095         UsedElements[i + Idx] = false;
13096       }
13097
13098     // Now recurse on both the base and sub vectors.
13099     SDValue SimplifiedSubV =
13100         SubVectorUsed
13101             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13102             : DAG.getUNDEF(SubV.getValueType());
13103     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13104     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13105       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13106                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13107     return V;
13108   }
13109   }
13110 }
13111
13112 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13113                                        SDValue N1, SelectionDAG &DAG) {
13114   EVT VT = SVN->getValueType(0);
13115   int NumElts = VT.getVectorNumElements();
13116   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13117   for (int M : SVN->getMask())
13118     if (M >= 0 && M < NumElts)
13119       N0UsedElements[M] = true;
13120     else if (M >= NumElts)
13121       N1UsedElements[M - NumElts] = true;
13122
13123   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13124   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13125   if (S0 == N0 && S1 == N1)
13126     return SDValue();
13127
13128   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13129 }
13130
13131 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13132 // or turn a shuffle of a single concat into simpler shuffle then concat.
13133 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13134   EVT VT = N->getValueType(0);
13135   unsigned NumElts = VT.getVectorNumElements();
13136
13137   SDValue N0 = N->getOperand(0);
13138   SDValue N1 = N->getOperand(1);
13139   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13140
13141   SmallVector<SDValue, 4> Ops;
13142   EVT ConcatVT = N0.getOperand(0).getValueType();
13143   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13144   unsigned NumConcats = NumElts / NumElemsPerConcat;
13145
13146   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13147   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13148   // half vector elements.
13149   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13150       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13151                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13152     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13153                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13154     N1 = DAG.getUNDEF(ConcatVT);
13155     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13156   }
13157
13158   // Look at every vector that's inserted. We're looking for exact
13159   // subvector-sized copies from a concatenated vector
13160   for (unsigned I = 0; I != NumConcats; ++I) {
13161     // Make sure we're dealing with a copy.
13162     unsigned Begin = I * NumElemsPerConcat;
13163     bool AllUndef = true, NoUndef = true;
13164     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13165       if (SVN->getMaskElt(J) >= 0)
13166         AllUndef = false;
13167       else
13168         NoUndef = false;
13169     }
13170
13171     if (NoUndef) {
13172       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13173         return SDValue();
13174
13175       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13176         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13177           return SDValue();
13178
13179       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13180       if (FirstElt < N0.getNumOperands())
13181         Ops.push_back(N0.getOperand(FirstElt));
13182       else
13183         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13184
13185     } else if (AllUndef) {
13186       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13187     } else { // Mixed with general masks and undefs, can't do optimization.
13188       return SDValue();
13189     }
13190   }
13191
13192   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13193 }
13194
13195 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13196   EVT VT = N->getValueType(0);
13197   unsigned NumElts = VT.getVectorNumElements();
13198
13199   SDValue N0 = N->getOperand(0);
13200   SDValue N1 = N->getOperand(1);
13201
13202   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13203
13204   // Canonicalize shuffle undef, undef -> undef
13205   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13206     return DAG.getUNDEF(VT);
13207
13208   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13209
13210   // Canonicalize shuffle v, v -> v, undef
13211   if (N0 == N1) {
13212     SmallVector<int, 8> NewMask;
13213     for (unsigned i = 0; i != NumElts; ++i) {
13214       int Idx = SVN->getMaskElt(i);
13215       if (Idx >= (int)NumElts) Idx -= NumElts;
13216       NewMask.push_back(Idx);
13217     }
13218     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13219                                 &NewMask[0]);
13220   }
13221
13222   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13223   if (N0.getOpcode() == ISD::UNDEF) {
13224     SmallVector<int, 8> NewMask;
13225     for (unsigned i = 0; i != NumElts; ++i) {
13226       int Idx = SVN->getMaskElt(i);
13227       if (Idx >= 0) {
13228         if (Idx >= (int)NumElts)
13229           Idx -= NumElts;
13230         else
13231           Idx = -1; // remove reference to lhs
13232       }
13233       NewMask.push_back(Idx);
13234     }
13235     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13236                                 &NewMask[0]);
13237   }
13238
13239   // Remove references to rhs if it is undef
13240   if (N1.getOpcode() == ISD::UNDEF) {
13241     bool Changed = false;
13242     SmallVector<int, 8> NewMask;
13243     for (unsigned i = 0; i != NumElts; ++i) {
13244       int Idx = SVN->getMaskElt(i);
13245       if (Idx >= (int)NumElts) {
13246         Idx = -1;
13247         Changed = true;
13248       }
13249       NewMask.push_back(Idx);
13250     }
13251     if (Changed)
13252       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13253   }
13254
13255   // If it is a splat, check if the argument vector is another splat or a
13256   // build_vector.
13257   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13258     SDNode *V = N0.getNode();
13259
13260     // If this is a bit convert that changes the element type of the vector but
13261     // not the number of vector elements, look through it.  Be careful not to
13262     // look though conversions that change things like v4f32 to v2f64.
13263     if (V->getOpcode() == ISD::BITCAST) {
13264       SDValue ConvInput = V->getOperand(0);
13265       if (ConvInput.getValueType().isVector() &&
13266           ConvInput.getValueType().getVectorNumElements() == NumElts)
13267         V = ConvInput.getNode();
13268     }
13269
13270     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13271       assert(V->getNumOperands() == NumElts &&
13272              "BUILD_VECTOR has wrong number of operands");
13273       SDValue Base;
13274       bool AllSame = true;
13275       for (unsigned i = 0; i != NumElts; ++i) {
13276         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13277           Base = V->getOperand(i);
13278           break;
13279         }
13280       }
13281       // Splat of <u, u, u, u>, return <u, u, u, u>
13282       if (!Base.getNode())
13283         return N0;
13284       for (unsigned i = 0; i != NumElts; ++i) {
13285         if (V->getOperand(i) != Base) {
13286           AllSame = false;
13287           break;
13288         }
13289       }
13290       // Splat of <x, x, x, x>, return <x, x, x, x>
13291       if (AllSame)
13292         return N0;
13293
13294       // Canonicalize any other splat as a build_vector.
13295       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13296       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13297       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13298                                   V->getValueType(0), Ops);
13299
13300       // We may have jumped through bitcasts, so the type of the
13301       // BUILD_VECTOR may not match the type of the shuffle.
13302       if (V->getValueType(0) != VT)
13303         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13304       return NewBV;
13305     }
13306   }
13307
13308   // There are various patterns used to build up a vector from smaller vectors,
13309   // subvectors, or elements. Scan chains of these and replace unused insertions
13310   // or components with undef.
13311   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13312     return S;
13313
13314   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13315       Level < AfterLegalizeVectorOps &&
13316       (N1.getOpcode() == ISD::UNDEF ||
13317       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13318        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13319     SDValue V = partitionShuffleOfConcats(N, DAG);
13320
13321     if (V.getNode())
13322       return V;
13323   }
13324
13325   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13326   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13327   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13328     SmallVector<SDValue, 8> Ops;
13329     for (int M : SVN->getMask()) {
13330       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13331       if (M >= 0) {
13332         int Idx = M % NumElts;
13333         SDValue &S = (M < (int)NumElts ? N0 : N1);
13334         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13335           Op = S.getOperand(Idx);
13336         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13337           if (Idx == 0)
13338             Op = S.getOperand(0);
13339         } else {
13340           // Operand can't be combined - bail out.
13341           break;
13342         }
13343       }
13344       Ops.push_back(Op);
13345     }
13346     if (Ops.size() == VT.getVectorNumElements()) {
13347       // BUILD_VECTOR requires all inputs to be of the same type, find the
13348       // maximum type and extend them all.
13349       EVT SVT = VT.getScalarType();
13350       if (SVT.isInteger())
13351         for (SDValue &Op : Ops)
13352           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13353       if (SVT != VT.getScalarType())
13354         for (SDValue &Op : Ops)
13355           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13356                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13357                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13358       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13359     }
13360   }
13361
13362   // If this shuffle only has a single input that is a bitcasted shuffle,
13363   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13364   // back to their original types.
13365   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13366       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13367       TLI.isTypeLegal(VT)) {
13368
13369     // Peek through the bitcast only if there is one user.
13370     SDValue BC0 = N0;
13371     while (BC0.getOpcode() == ISD::BITCAST) {
13372       if (!BC0.hasOneUse())
13373         break;
13374       BC0 = BC0.getOperand(0);
13375     }
13376
13377     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13378       if (Scale == 1)
13379         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13380
13381       SmallVector<int, 8> NewMask;
13382       for (int M : Mask)
13383         for (int s = 0; s != Scale; ++s)
13384           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13385       return NewMask;
13386     };
13387
13388     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13389       EVT SVT = VT.getScalarType();
13390       EVT InnerVT = BC0->getValueType(0);
13391       EVT InnerSVT = InnerVT.getScalarType();
13392
13393       // Determine which shuffle works with the smaller scalar type.
13394       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13395       EVT ScaleSVT = ScaleVT.getScalarType();
13396
13397       if (TLI.isTypeLegal(ScaleVT) &&
13398           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13399           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13400
13401         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13402         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13403
13404         // Scale the shuffle masks to the smaller scalar type.
13405         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13406         SmallVector<int, 8> InnerMask =
13407             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13408         SmallVector<int, 8> OuterMask =
13409             ScaleShuffleMask(SVN->getMask(), OuterScale);
13410
13411         // Merge the shuffle masks.
13412         SmallVector<int, 8> NewMask;
13413         for (int M : OuterMask)
13414           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13415
13416         // Test for shuffle mask legality over both commutations.
13417         SDValue SV0 = BC0->getOperand(0);
13418         SDValue SV1 = BC0->getOperand(1);
13419         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13420         if (!LegalMask) {
13421           std::swap(SV0, SV1);
13422           ShuffleVectorSDNode::commuteMask(NewMask);
13423           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13424         }
13425
13426         if (LegalMask) {
13427           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13428           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13429           return DAG.getNode(
13430               ISD::BITCAST, SDLoc(N), VT,
13431               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13432         }
13433       }
13434     }
13435   }
13436
13437   // Canonicalize shuffles according to rules:
13438   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13439   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13440   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13441   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13442       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13443       TLI.isTypeLegal(VT)) {
13444     // The incoming shuffle must be of the same type as the result of the
13445     // current shuffle.
13446     assert(N1->getOperand(0).getValueType() == VT &&
13447            "Shuffle types don't match");
13448
13449     SDValue SV0 = N1->getOperand(0);
13450     SDValue SV1 = N1->getOperand(1);
13451     bool HasSameOp0 = N0 == SV0;
13452     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13453     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13454       // Commute the operands of this shuffle so that next rule
13455       // will trigger.
13456       return DAG.getCommutedVectorShuffle(*SVN);
13457   }
13458
13459   // Try to fold according to rules:
13460   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13461   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13462   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13463   // Don't try to fold shuffles with illegal type.
13464   // Only fold if this shuffle is the only user of the other shuffle.
13465   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13466       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13467     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13468
13469     // The incoming shuffle must be of the same type as the result of the
13470     // current shuffle.
13471     assert(OtherSV->getOperand(0).getValueType() == VT &&
13472            "Shuffle types don't match");
13473
13474     SDValue SV0, SV1;
13475     SmallVector<int, 4> Mask;
13476     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13477     // operand, and SV1 as the second operand.
13478     for (unsigned i = 0; i != NumElts; ++i) {
13479       int Idx = SVN->getMaskElt(i);
13480       if (Idx < 0) {
13481         // Propagate Undef.
13482         Mask.push_back(Idx);
13483         continue;
13484       }
13485
13486       SDValue CurrentVec;
13487       if (Idx < (int)NumElts) {
13488         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13489         // shuffle mask to identify which vector is actually referenced.
13490         Idx = OtherSV->getMaskElt(Idx);
13491         if (Idx < 0) {
13492           // Propagate Undef.
13493           Mask.push_back(Idx);
13494           continue;
13495         }
13496
13497         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13498                                            : OtherSV->getOperand(1);
13499       } else {
13500         // This shuffle index references an element within N1.
13501         CurrentVec = N1;
13502       }
13503
13504       // Simple case where 'CurrentVec' is UNDEF.
13505       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13506         Mask.push_back(-1);
13507         continue;
13508       }
13509
13510       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13511       // will be the first or second operand of the combined shuffle.
13512       Idx = Idx % NumElts;
13513       if (!SV0.getNode() || SV0 == CurrentVec) {
13514         // Ok. CurrentVec is the left hand side.
13515         // Update the mask accordingly.
13516         SV0 = CurrentVec;
13517         Mask.push_back(Idx);
13518         continue;
13519       }
13520
13521       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13522       if (SV1.getNode() && SV1 != CurrentVec)
13523         return SDValue();
13524
13525       // Ok. CurrentVec is the right hand side.
13526       // Update the mask accordingly.
13527       SV1 = CurrentVec;
13528       Mask.push_back(Idx + NumElts);
13529     }
13530
13531     // Check if all indices in Mask are Undef. In case, propagate Undef.
13532     bool isUndefMask = true;
13533     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13534       isUndefMask &= Mask[i] < 0;
13535
13536     if (isUndefMask)
13537       return DAG.getUNDEF(VT);
13538
13539     if (!SV0.getNode())
13540       SV0 = DAG.getUNDEF(VT);
13541     if (!SV1.getNode())
13542       SV1 = DAG.getUNDEF(VT);
13543
13544     // Avoid introducing shuffles with illegal mask.
13545     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13546       ShuffleVectorSDNode::commuteMask(Mask);
13547
13548       if (!TLI.isShuffleMaskLegal(Mask, VT))
13549         return SDValue();
13550
13551       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13552       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13553       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13554       std::swap(SV0, SV1);
13555     }
13556
13557     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13558     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13559     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13560     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13561   }
13562
13563   return SDValue();
13564 }
13565
13566 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13567   SDValue InVal = N->getOperand(0);
13568   EVT VT = N->getValueType(0);
13569
13570   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13571   // with a VECTOR_SHUFFLE.
13572   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13573     SDValue InVec = InVal->getOperand(0);
13574     SDValue EltNo = InVal->getOperand(1);
13575
13576     // FIXME: We could support implicit truncation if the shuffle can be
13577     // scaled to a smaller vector scalar type.
13578     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13579     if (C0 && VT == InVec.getValueType() &&
13580         VT.getScalarType() == InVal.getValueType()) {
13581       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13582       int Elt = C0->getZExtValue();
13583       NewMask[0] = Elt;
13584
13585       if (TLI.isShuffleMaskLegal(NewMask, VT))
13586         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13587                                     NewMask);
13588     }
13589   }
13590
13591   return SDValue();
13592 }
13593
13594 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13595   SDValue N0 = N->getOperand(0);
13596   SDValue N2 = N->getOperand(2);
13597
13598   // If the input vector is a concatenation, and the insert replaces
13599   // one of the halves, we can optimize into a single concat_vectors.
13600   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13601       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13602     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13603     EVT VT = N->getValueType(0);
13604
13605     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13606     // (concat_vectors Z, Y)
13607     if (InsIdx == 0)
13608       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13609                          N->getOperand(1), N0.getOperand(1));
13610
13611     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13612     // (concat_vectors X, Z)
13613     if (InsIdx == VT.getVectorNumElements()/2)
13614       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13615                          N0.getOperand(0), N->getOperand(1));
13616   }
13617
13618   return SDValue();
13619 }
13620
13621 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13622   SDValue N0 = N->getOperand(0);
13623
13624   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13625   if (N0->getOpcode() == ISD::FP16_TO_FP)
13626     return N0->getOperand(0);
13627
13628   return SDValue();
13629 }
13630
13631 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13632   SDValue N0 = N->getOperand(0);
13633
13634   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13635   if (N0->getOpcode() == ISD::AND) {
13636     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13637     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13638       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13639                          N0.getOperand(0));
13640     }
13641   }
13642
13643   return SDValue();
13644 }
13645
13646 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13647 /// with the destination vector and a zero vector.
13648 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13649 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13650 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13651   EVT VT = N->getValueType(0);
13652   SDValue LHS = N->getOperand(0);
13653   SDValue RHS = N->getOperand(1);
13654   SDLoc dl(N);
13655
13656   // Make sure we're not running after operation legalization where it
13657   // may have custom lowered the vector shuffles.
13658   if (LegalOperations)
13659     return SDValue();
13660
13661   if (N->getOpcode() != ISD::AND)
13662     return SDValue();
13663
13664   if (RHS.getOpcode() == ISD::BITCAST)
13665     RHS = RHS.getOperand(0);
13666
13667   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13668     return SDValue();
13669
13670   EVT RVT = RHS.getValueType();
13671   unsigned NumElts = RHS.getNumOperands();
13672
13673   // Attempt to create a valid clear mask, splitting the mask into
13674   // sub elements and checking to see if each is
13675   // all zeros or all ones - suitable for shuffle masking.
13676   auto BuildClearMask = [&](int Split) {
13677     int NumSubElts = NumElts * Split;
13678     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13679
13680     SmallVector<int, 8> Indices;
13681     for (int i = 0; i != NumSubElts; ++i) {
13682       int EltIdx = i / Split;
13683       int SubIdx = i % Split;
13684       SDValue Elt = RHS.getOperand(EltIdx);
13685       if (Elt.getOpcode() == ISD::UNDEF) {
13686         Indices.push_back(-1);
13687         continue;
13688       }
13689
13690       APInt Bits;
13691       if (isa<ConstantSDNode>(Elt))
13692         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13693       else if (isa<ConstantFPSDNode>(Elt))
13694         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13695       else
13696         return SDValue();
13697
13698       // Extract the sub element from the constant bit mask.
13699       if (DAG.getDataLayout().isBigEndian()) {
13700         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13701       } else {
13702         Bits = Bits.lshr(SubIdx * NumSubBits);
13703       }
13704
13705       if (Split > 1)
13706         Bits = Bits.trunc(NumSubBits);
13707
13708       if (Bits.isAllOnesValue())
13709         Indices.push_back(i);
13710       else if (Bits == 0)
13711         Indices.push_back(i + NumSubElts);
13712       else
13713         return SDValue();
13714     }
13715
13716     // Let's see if the target supports this vector_shuffle.
13717     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13718     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13719     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13720       return SDValue();
13721
13722     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13723     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13724                                                    DAG.getBitcast(ClearVT, LHS),
13725                                                    Zero, &Indices[0]));
13726   };
13727
13728   // Determine maximum split level (byte level masking).
13729   int MaxSplit = 1;
13730   if (RVT.getScalarSizeInBits() % 8 == 0)
13731     MaxSplit = RVT.getScalarSizeInBits() / 8;
13732
13733   for (int Split = 1; Split <= MaxSplit; ++Split)
13734     if (RVT.getScalarSizeInBits() % Split == 0)
13735       if (SDValue S = BuildClearMask(Split))
13736         return S;
13737
13738   return SDValue();
13739 }
13740
13741 /// Visit a binary vector operation, like ADD.
13742 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13743   assert(N->getValueType(0).isVector() &&
13744          "SimplifyVBinOp only works on vectors!");
13745
13746   SDValue LHS = N->getOperand(0);
13747   SDValue RHS = N->getOperand(1);
13748   SDValue Ops[] = {LHS, RHS};
13749
13750   // See if we can constant fold the vector operation.
13751   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13752           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13753     return Fold;
13754
13755   // Try to convert a constant mask AND into a shuffle clear mask.
13756   if (SDValue Shuffle = XformToShuffleWithZero(N))
13757     return Shuffle;
13758
13759   // Type legalization might introduce new shuffles in the DAG.
13760   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13761   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13762   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13763       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13764       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13765       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13766     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13767     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13768
13769     if (SVN0->getMask().equals(SVN1->getMask())) {
13770       EVT VT = N->getValueType(0);
13771       SDValue UndefVector = LHS.getOperand(1);
13772       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13773                                      LHS.getOperand(0), RHS.getOperand(0),
13774                                      N->getFlags());
13775       AddUsersToWorklist(N);
13776       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13777                                   &SVN0->getMask()[0]);
13778     }
13779   }
13780
13781   return SDValue();
13782 }
13783
13784 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13785                                     SDValue N1, SDValue N2){
13786   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13787
13788   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13789                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13790
13791   // If we got a simplified select_cc node back from SimplifySelectCC, then
13792   // break it down into a new SETCC node, and a new SELECT node, and then return
13793   // the SELECT node, since we were called with a SELECT node.
13794   if (SCC.getNode()) {
13795     // Check to see if we got a select_cc back (to turn into setcc/select).
13796     // Otherwise, just return whatever node we got back, like fabs.
13797     if (SCC.getOpcode() == ISD::SELECT_CC) {
13798       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13799                                   N0.getValueType(),
13800                                   SCC.getOperand(0), SCC.getOperand(1),
13801                                   SCC.getOperand(4));
13802       AddToWorklist(SETCC.getNode());
13803       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13804                            SCC.getOperand(2), SCC.getOperand(3));
13805     }
13806
13807     return SCC;
13808   }
13809   return SDValue();
13810 }
13811
13812 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13813 /// being selected between, see if we can simplify the select.  Callers of this
13814 /// should assume that TheSelect is deleted if this returns true.  As such, they
13815 /// should return the appropriate thing (e.g. the node) back to the top-level of
13816 /// the DAG combiner loop to avoid it being looked at.
13817 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13818                                     SDValue RHS) {
13819
13820   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13821   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13822   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13823     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13824       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13825       SDValue Sqrt = RHS;
13826       ISD::CondCode CC;
13827       SDValue CmpLHS;
13828       const ConstantFPSDNode *NegZero = nullptr;
13829
13830       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13831         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13832         CmpLHS = TheSelect->getOperand(0);
13833         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13834       } else {
13835         // SELECT or VSELECT
13836         SDValue Cmp = TheSelect->getOperand(0);
13837         if (Cmp.getOpcode() == ISD::SETCC) {
13838           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13839           CmpLHS = Cmp.getOperand(0);
13840           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13841         }
13842       }
13843       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13844           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13845           CC == ISD::SETULT || CC == ISD::SETLT)) {
13846         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13847         CombineTo(TheSelect, Sqrt);
13848         return true;
13849       }
13850     }
13851   }
13852   // Cannot simplify select with vector condition
13853   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13854
13855   // If this is a select from two identical things, try to pull the operation
13856   // through the select.
13857   if (LHS.getOpcode() != RHS.getOpcode() ||
13858       !LHS.hasOneUse() || !RHS.hasOneUse())
13859     return false;
13860
13861   // If this is a load and the token chain is identical, replace the select
13862   // of two loads with a load through a select of the address to load from.
13863   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13864   // constants have been dropped into the constant pool.
13865   if (LHS.getOpcode() == ISD::LOAD) {
13866     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13867     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13868
13869     // Token chains must be identical.
13870     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13871         // Do not let this transformation reduce the number of volatile loads.
13872         LLD->isVolatile() || RLD->isVolatile() ||
13873         // FIXME: If either is a pre/post inc/dec load,
13874         // we'd need to split out the address adjustment.
13875         LLD->isIndexed() || RLD->isIndexed() ||
13876         // If this is an EXTLOAD, the VT's must match.
13877         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13878         // If this is an EXTLOAD, the kind of extension must match.
13879         (LLD->getExtensionType() != RLD->getExtensionType() &&
13880          // The only exception is if one of the extensions is anyext.
13881          LLD->getExtensionType() != ISD::EXTLOAD &&
13882          RLD->getExtensionType() != ISD::EXTLOAD) ||
13883         // FIXME: this discards src value information.  This is
13884         // over-conservative. It would be beneficial to be able to remember
13885         // both potential memory locations.  Since we are discarding
13886         // src value info, don't do the transformation if the memory
13887         // locations are not in the default address space.
13888         LLD->getPointerInfo().getAddrSpace() != 0 ||
13889         RLD->getPointerInfo().getAddrSpace() != 0 ||
13890         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13891                                       LLD->getBasePtr().getValueType()))
13892       return false;
13893
13894     // Check that the select condition doesn't reach either load.  If so,
13895     // folding this will induce a cycle into the DAG.  If not, this is safe to
13896     // xform, so create a select of the addresses.
13897     SDValue Addr;
13898     if (TheSelect->getOpcode() == ISD::SELECT) {
13899       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13900       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13901           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13902         return false;
13903       // The loads must not depend on one another.
13904       if (LLD->isPredecessorOf(RLD) ||
13905           RLD->isPredecessorOf(LLD))
13906         return false;
13907       Addr = DAG.getSelect(SDLoc(TheSelect),
13908                            LLD->getBasePtr().getValueType(),
13909                            TheSelect->getOperand(0), LLD->getBasePtr(),
13910                            RLD->getBasePtr());
13911     } else {  // Otherwise SELECT_CC
13912       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13913       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13914
13915       if ((LLD->hasAnyUseOfValue(1) &&
13916            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13917           (RLD->hasAnyUseOfValue(1) &&
13918            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13919         return false;
13920
13921       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13922                          LLD->getBasePtr().getValueType(),
13923                          TheSelect->getOperand(0),
13924                          TheSelect->getOperand(1),
13925                          LLD->getBasePtr(), RLD->getBasePtr(),
13926                          TheSelect->getOperand(4));
13927     }
13928
13929     SDValue Load;
13930     // It is safe to replace the two loads if they have different alignments,
13931     // but the new load must be the minimum (most restrictive) alignment of the
13932     // inputs.
13933     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13934     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13935     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13936       Load = DAG.getLoad(TheSelect->getValueType(0),
13937                          SDLoc(TheSelect),
13938                          // FIXME: Discards pointer and AA info.
13939                          LLD->getChain(), Addr, MachinePointerInfo(),
13940                          LLD->isVolatile(), LLD->isNonTemporal(),
13941                          isInvariant, Alignment);
13942     } else {
13943       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13944                             RLD->getExtensionType() : LLD->getExtensionType(),
13945                             SDLoc(TheSelect),
13946                             TheSelect->getValueType(0),
13947                             // FIXME: Discards pointer and AA info.
13948                             LLD->getChain(), Addr, MachinePointerInfo(),
13949                             LLD->getMemoryVT(), LLD->isVolatile(),
13950                             LLD->isNonTemporal(), isInvariant, Alignment);
13951     }
13952
13953     // Users of the select now use the result of the load.
13954     CombineTo(TheSelect, Load);
13955
13956     // Users of the old loads now use the new load's chain.  We know the
13957     // old-load value is dead now.
13958     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13959     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13960     return true;
13961   }
13962
13963   return false;
13964 }
13965
13966 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13967 /// where 'cond' is the comparison specified by CC.
13968 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13969                                       SDValue N2, SDValue N3,
13970                                       ISD::CondCode CC, bool NotExtCompare) {
13971   // (x ? y : y) -> y.
13972   if (N2 == N3) return N2;
13973
13974   EVT VT = N2.getValueType();
13975   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13976   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13977
13978   // Determine if the condition we're dealing with is constant
13979   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13980                               N0, N1, CC, DL, false);
13981   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13982
13983   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13984     // fold select_cc true, x, y -> x
13985     // fold select_cc false, x, y -> y
13986     return !SCCC->isNullValue() ? N2 : N3;
13987   }
13988
13989   // Check to see if we can simplify the select into an fabs node
13990   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13991     // Allow either -0.0 or 0.0
13992     if (CFP->isZero()) {
13993       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13994       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13995           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13996           N2 == N3.getOperand(0))
13997         return DAG.getNode(ISD::FABS, DL, VT, N0);
13998
13999       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14000       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14001           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14002           N2.getOperand(0) == N3)
14003         return DAG.getNode(ISD::FABS, DL, VT, N3);
14004     }
14005   }
14006
14007   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14008   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14009   // in it.  This is a win when the constant is not otherwise available because
14010   // it replaces two constant pool loads with one.  We only do this if the FP
14011   // type is known to be legal, because if it isn't, then we are before legalize
14012   // types an we want the other legalization to happen first (e.g. to avoid
14013   // messing with soft float) and if the ConstantFP is not legal, because if
14014   // it is legal, we may not need to store the FP constant in a constant pool.
14015   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14016     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14017       if (TLI.isTypeLegal(N2.getValueType()) &&
14018           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14019                TargetLowering::Legal &&
14020            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14021            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14022           // If both constants have multiple uses, then we won't need to do an
14023           // extra load, they are likely around in registers for other users.
14024           (TV->hasOneUse() || FV->hasOneUse())) {
14025         Constant *Elts[] = {
14026           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14027           const_cast<ConstantFP*>(TV->getConstantFPValue())
14028         };
14029         Type *FPTy = Elts[0]->getType();
14030         const DataLayout &TD = DAG.getDataLayout();
14031
14032         // Create a ConstantArray of the two constants.
14033         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14034         SDValue CPIdx =
14035             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14036                                 TD.getPrefTypeAlignment(FPTy));
14037         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14038
14039         // Get the offsets to the 0 and 1 element of the array so that we can
14040         // select between them.
14041         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14042         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14043         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14044
14045         SDValue Cond = DAG.getSetCC(DL,
14046                                     getSetCCResultType(N0.getValueType()),
14047                                     N0, N1, CC);
14048         AddToWorklist(Cond.getNode());
14049         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14050                                           Cond, One, Zero);
14051         AddToWorklist(CstOffset.getNode());
14052         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14053                             CstOffset);
14054         AddToWorklist(CPIdx.getNode());
14055         return DAG.getLoad(
14056             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14057             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14058             false, false, false, Alignment);
14059       }
14060     }
14061
14062   // Check to see if we can perform the "gzip trick", transforming
14063   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14064   if (isNullConstant(N3) && CC == ISD::SETLT &&
14065       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14066        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14067     EVT XType = N0.getValueType();
14068     EVT AType = N2.getValueType();
14069     if (XType.bitsGE(AType)) {
14070       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14071       // single-bit constant.
14072       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14073         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14074         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14075         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14076                                        getShiftAmountTy(N0.getValueType()));
14077         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14078                                     XType, N0, ShCt);
14079         AddToWorklist(Shift.getNode());
14080
14081         if (XType.bitsGT(AType)) {
14082           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14083           AddToWorklist(Shift.getNode());
14084         }
14085
14086         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14087       }
14088
14089       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14090                                   XType, N0,
14091                                   DAG.getConstant(XType.getSizeInBits() - 1,
14092                                                   SDLoc(N0),
14093                                          getShiftAmountTy(N0.getValueType())));
14094       AddToWorklist(Shift.getNode());
14095
14096       if (XType.bitsGT(AType)) {
14097         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14098         AddToWorklist(Shift.getNode());
14099       }
14100
14101       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14102     }
14103   }
14104
14105   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14106   // where y is has a single bit set.
14107   // A plaintext description would be, we can turn the SELECT_CC into an AND
14108   // when the condition can be materialized as an all-ones register.  Any
14109   // single bit-test can be materialized as an all-ones register with
14110   // shift-left and shift-right-arith.
14111   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14112       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14113     SDValue AndLHS = N0->getOperand(0);
14114     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14115     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14116       // Shift the tested bit over the sign bit.
14117       APInt AndMask = ConstAndRHS->getAPIntValue();
14118       SDValue ShlAmt =
14119         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14120                         getShiftAmountTy(AndLHS.getValueType()));
14121       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14122
14123       // Now arithmetic right shift it all the way over, so the result is either
14124       // all-ones, or zero.
14125       SDValue ShrAmt =
14126         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14127                         getShiftAmountTy(Shl.getValueType()));
14128       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14129
14130       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14131     }
14132   }
14133
14134   // fold select C, 16, 0 -> shl C, 4
14135   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14136       TLI.getBooleanContents(N0.getValueType()) ==
14137           TargetLowering::ZeroOrOneBooleanContent) {
14138
14139     // If the caller doesn't want us to simplify this into a zext of a compare,
14140     // don't do it.
14141     if (NotExtCompare && N2C->isOne())
14142       return SDValue();
14143
14144     // Get a SetCC of the condition
14145     // NOTE: Don't create a SETCC if it's not legal on this target.
14146     if (!LegalOperations ||
14147         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14148       SDValue Temp, SCC;
14149       // cast from setcc result type to select result type
14150       if (LegalTypes) {
14151         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14152                             N0, N1, CC);
14153         if (N2.getValueType().bitsLT(SCC.getValueType()))
14154           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14155                                         N2.getValueType());
14156         else
14157           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14158                              N2.getValueType(), SCC);
14159       } else {
14160         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14161         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14162                            N2.getValueType(), SCC);
14163       }
14164
14165       AddToWorklist(SCC.getNode());
14166       AddToWorklist(Temp.getNode());
14167
14168       if (N2C->isOne())
14169         return Temp;
14170
14171       // shl setcc result by log2 n2c
14172       return DAG.getNode(
14173           ISD::SHL, DL, N2.getValueType(), Temp,
14174           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14175                           getShiftAmountTy(Temp.getValueType())));
14176     }
14177   }
14178
14179   // Check to see if this is an integer abs.
14180   // select_cc setg[te] X,  0,  X, -X ->
14181   // select_cc setgt    X, -1,  X, -X ->
14182   // select_cc setl[te] X,  0, -X,  X ->
14183   // select_cc setlt    X,  1, -X,  X ->
14184   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14185   if (N1C) {
14186     ConstantSDNode *SubC = nullptr;
14187     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14188          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14189         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14190       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14191     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14192               (N1C->isOne() && CC == ISD::SETLT)) &&
14193              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14194       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14195
14196     EVT XType = N0.getValueType();
14197     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14198       SDLoc DL(N0);
14199       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14200                                   N0,
14201                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14202                                          getShiftAmountTy(N0.getValueType())));
14203       SDValue Add = DAG.getNode(ISD::ADD, DL,
14204                                 XType, N0, Shift);
14205       AddToWorklist(Shift.getNode());
14206       AddToWorklist(Add.getNode());
14207       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14208     }
14209   }
14210
14211   return SDValue();
14212 }
14213
14214 /// This is a stub for TargetLowering::SimplifySetCC.
14215 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14216                                    SDValue N1, ISD::CondCode Cond,
14217                                    SDLoc DL, bool foldBooleans) {
14218   TargetLowering::DAGCombinerInfo
14219     DagCombineInfo(DAG, Level, false, this);
14220   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14221 }
14222
14223 /// Given an ISD::SDIV node expressing a divide by constant, return
14224 /// a DAG expression to select that will generate the same value by multiplying
14225 /// by a magic number.
14226 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14227 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14228   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14229   if (!C)
14230     return SDValue();
14231
14232   // Avoid division by zero.
14233   if (C->isNullValue())
14234     return SDValue();
14235
14236   std::vector<SDNode*> Built;
14237   SDValue S =
14238       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14239
14240   for (SDNode *N : Built)
14241     AddToWorklist(N);
14242   return S;
14243 }
14244
14245 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14246 /// DAG expression that will generate the same value by right shifting.
14247 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14248   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14249   if (!C)
14250     return SDValue();
14251
14252   // Avoid division by zero.
14253   if (C->isNullValue())
14254     return SDValue();
14255
14256   std::vector<SDNode *> Built;
14257   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14258
14259   for (SDNode *N : Built)
14260     AddToWorklist(N);
14261   return S;
14262 }
14263
14264 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14265 /// expression that will generate the same value by multiplying by a magic
14266 /// number.
14267 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14268 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14269   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14270   if (!C)
14271     return SDValue();
14272
14273   // Avoid division by zero.
14274   if (C->isNullValue())
14275     return SDValue();
14276
14277   std::vector<SDNode*> Built;
14278   SDValue S =
14279       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14280
14281   for (SDNode *N : Built)
14282     AddToWorklist(N);
14283   return S;
14284 }
14285
14286 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14287   if (Level >= AfterLegalizeDAG)
14288     return SDValue();
14289
14290   // Expose the DAG combiner to the target combiner implementations.
14291   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14292
14293   unsigned Iterations = 0;
14294   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14295     if (Iterations) {
14296       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14297       // For the reciprocal, we need to find the zero of the function:
14298       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14299       //     =>
14300       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14301       //     does not require additional intermediate precision]
14302       EVT VT = Op.getValueType();
14303       SDLoc DL(Op);
14304       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14305
14306       AddToWorklist(Est.getNode());
14307
14308       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14309       for (unsigned i = 0; i < Iterations; ++i) {
14310         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14311         AddToWorklist(NewEst.getNode());
14312
14313         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14314         AddToWorklist(NewEst.getNode());
14315
14316         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14317         AddToWorklist(NewEst.getNode());
14318
14319         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14320         AddToWorklist(Est.getNode());
14321       }
14322     }
14323     return Est;
14324   }
14325
14326   return SDValue();
14327 }
14328
14329 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14330 /// For the reciprocal sqrt, we need to find the zero of the function:
14331 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14332 ///     =>
14333 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14334 /// As a result, we precompute A/2 prior to the iteration loop.
14335 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14336                                           unsigned Iterations,
14337                                           SDNodeFlags *Flags) {
14338   EVT VT = Arg.getValueType();
14339   SDLoc DL(Arg);
14340   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14341
14342   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14343   // this entire sequence requires only one FP constant.
14344   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14345   AddToWorklist(HalfArg.getNode());
14346
14347   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14348   AddToWorklist(HalfArg.getNode());
14349
14350   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14351   for (unsigned i = 0; i < Iterations; ++i) {
14352     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14353     AddToWorklist(NewEst.getNode());
14354
14355     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14356     AddToWorklist(NewEst.getNode());
14357
14358     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14359     AddToWorklist(NewEst.getNode());
14360
14361     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14362     AddToWorklist(Est.getNode());
14363   }
14364   return Est;
14365 }
14366
14367 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14368 /// For the reciprocal sqrt, we need to find the zero of the function:
14369 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14370 ///     =>
14371 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14372 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14373                                           unsigned Iterations,
14374                                           SDNodeFlags *Flags) {
14375   EVT VT = Arg.getValueType();
14376   SDLoc DL(Arg);
14377   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14378   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14379
14380   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14381   for (unsigned i = 0; i < Iterations; ++i) {
14382     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14383     AddToWorklist(HalfEst.getNode());
14384
14385     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14386     AddToWorklist(Est.getNode());
14387
14388     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14389     AddToWorklist(Est.getNode());
14390
14391     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14392     AddToWorklist(Est.getNode());
14393
14394     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14395     AddToWorklist(Est.getNode());
14396   }
14397   return Est;
14398 }
14399
14400 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14401   if (Level >= AfterLegalizeDAG)
14402     return SDValue();
14403
14404   // Expose the DAG combiner to the target combiner implementations.
14405   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14406   unsigned Iterations = 0;
14407   bool UseOneConstNR = false;
14408   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14409     AddToWorklist(Est.getNode());
14410     if (Iterations) {
14411       Est = UseOneConstNR ?
14412         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14413         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14414     }
14415     return Est;
14416   }
14417
14418   return SDValue();
14419 }
14420
14421 /// Return true if base is a frame index, which is known not to alias with
14422 /// anything but itself.  Provides base object and offset as results.
14423 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14424                            const GlobalValue *&GV, const void *&CV) {
14425   // Assume it is a primitive operation.
14426   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14427
14428   // If it's an adding a simple constant then integrate the offset.
14429   if (Base.getOpcode() == ISD::ADD) {
14430     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14431       Base = Base.getOperand(0);
14432       Offset += C->getZExtValue();
14433     }
14434   }
14435
14436   // Return the underlying GlobalValue, and update the Offset.  Return false
14437   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14438   // by multiple nodes with different offsets.
14439   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14440     GV = G->getGlobal();
14441     Offset += G->getOffset();
14442     return false;
14443   }
14444
14445   // Return the underlying Constant value, and update the Offset.  Return false
14446   // for ConstantSDNodes since the same constant pool entry may be represented
14447   // by multiple nodes with different offsets.
14448   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14449     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14450                                          : (const void *)C->getConstVal();
14451     Offset += C->getOffset();
14452     return false;
14453   }
14454   // If it's any of the following then it can't alias with anything but itself.
14455   return isa<FrameIndexSDNode>(Base);
14456 }
14457
14458 /// Return true if there is any possibility that the two addresses overlap.
14459 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14460   // If they are the same then they must be aliases.
14461   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14462
14463   // If they are both volatile then they cannot be reordered.
14464   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14465
14466   // If one operation reads from invariant memory, and the other may store, they
14467   // cannot alias. These should really be checking the equivalent of mayWrite,
14468   // but it only matters for memory nodes other than load /store.
14469   if (Op0->isInvariant() && Op1->writeMem())
14470     return false;
14471
14472   if (Op1->isInvariant() && Op0->writeMem())
14473     return false;
14474
14475   // Gather base node and offset information.
14476   SDValue Base1, Base2;
14477   int64_t Offset1, Offset2;
14478   const GlobalValue *GV1, *GV2;
14479   const void *CV1, *CV2;
14480   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14481                                       Base1, Offset1, GV1, CV1);
14482   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14483                                       Base2, Offset2, GV2, CV2);
14484
14485   // If they have a same base address then check to see if they overlap.
14486   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14487     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14488              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14489
14490   // It is possible for different frame indices to alias each other, mostly
14491   // when tail call optimization reuses return address slots for arguments.
14492   // To catch this case, look up the actual index of frame indices to compute
14493   // the real alias relationship.
14494   if (isFrameIndex1 && isFrameIndex2) {
14495     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14496     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14497     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14498     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14499              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14500   }
14501
14502   // Otherwise, if we know what the bases are, and they aren't identical, then
14503   // we know they cannot alias.
14504   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14505     return false;
14506
14507   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14508   // compared to the size and offset of the access, we may be able to prove they
14509   // do not alias.  This check is conservative for now to catch cases created by
14510   // splitting vector types.
14511   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14512       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14513       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14514        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14515       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14516     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14517     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14518
14519     // There is no overlap between these relatively aligned accesses of similar
14520     // size, return no alias.
14521     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14522         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14523       return false;
14524   }
14525
14526   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14527                    ? CombinerGlobalAA
14528                    : DAG.getSubtarget().useAA();
14529 #ifndef NDEBUG
14530   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14531       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14532     UseAA = false;
14533 #endif
14534   if (UseAA &&
14535       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14536     // Use alias analysis information.
14537     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14538                                  Op1->getSrcValueOffset());
14539     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14540         Op0->getSrcValueOffset() - MinOffset;
14541     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14542         Op1->getSrcValueOffset() - MinOffset;
14543     AliasResult AAResult =
14544         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14545                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14546                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14547                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14548     if (AAResult == NoAlias)
14549       return false;
14550   }
14551
14552   // Otherwise we have to assume they alias.
14553   return true;
14554 }
14555
14556 /// Walk up chain skipping non-aliasing memory nodes,
14557 /// looking for aliasing nodes and adding them to the Aliases vector.
14558 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14559                                    SmallVectorImpl<SDValue> &Aliases) {
14560   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14561   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14562
14563   // Get alias information for node.
14564   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14565
14566   // Starting off.
14567   Chains.push_back(OriginalChain);
14568   unsigned Depth = 0;
14569
14570   // Look at each chain and determine if it is an alias.  If so, add it to the
14571   // aliases list.  If not, then continue up the chain looking for the next
14572   // candidate.
14573   while (!Chains.empty()) {
14574     SDValue Chain = Chains.pop_back_val();
14575
14576     // For TokenFactor nodes, look at each operand and only continue up the
14577     // chain until we reach the depth limit.
14578     //
14579     // FIXME: The depth check could be made to return the last non-aliasing
14580     // chain we found before we hit a tokenfactor rather than the original
14581     // chain.
14582     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14583       Aliases.clear();
14584       Aliases.push_back(OriginalChain);
14585       return;
14586     }
14587
14588     // Don't bother if we've been before.
14589     if (!Visited.insert(Chain.getNode()).second)
14590       continue;
14591
14592     switch (Chain.getOpcode()) {
14593     case ISD::EntryToken:
14594       // Entry token is ideal chain operand, but handled in FindBetterChain.
14595       break;
14596
14597     case ISD::LOAD:
14598     case ISD::STORE: {
14599       // Get alias information for Chain.
14600       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14601           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14602
14603       // If chain is alias then stop here.
14604       if (!(IsLoad && IsOpLoad) &&
14605           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14606         Aliases.push_back(Chain);
14607       } else {
14608         // Look further up the chain.
14609         Chains.push_back(Chain.getOperand(0));
14610         ++Depth;
14611       }
14612       break;
14613     }
14614
14615     case ISD::TokenFactor:
14616       // We have to check each of the operands of the token factor for "small"
14617       // token factors, so we queue them up.  Adding the operands to the queue
14618       // (stack) in reverse order maintains the original order and increases the
14619       // likelihood that getNode will find a matching token factor (CSE.)
14620       if (Chain.getNumOperands() > 16) {
14621         Aliases.push_back(Chain);
14622         break;
14623       }
14624       for (unsigned n = Chain.getNumOperands(); n;)
14625         Chains.push_back(Chain.getOperand(--n));
14626       ++Depth;
14627       break;
14628
14629     default:
14630       // For all other instructions we will just have to take what we can get.
14631       Aliases.push_back(Chain);
14632       break;
14633     }
14634   }
14635
14636   // We need to be careful here to also search for aliases through the
14637   // value operand of a store, etc. Consider the following situation:
14638   //   Token1 = ...
14639   //   L1 = load Token1, %52
14640   //   S1 = store Token1, L1, %51
14641   //   L2 = load Token1, %52+8
14642   //   S2 = store Token1, L2, %51+8
14643   //   Token2 = Token(S1, S2)
14644   //   L3 = load Token2, %53
14645   //   S3 = store Token2, L3, %52
14646   //   L4 = load Token2, %53+8
14647   //   S4 = store Token2, L4, %52+8
14648   // If we search for aliases of S3 (which loads address %52), and we look
14649   // only through the chain, then we'll miss the trivial dependence on L1
14650   // (which also loads from %52). We then might change all loads and
14651   // stores to use Token1 as their chain operand, which could result in
14652   // copying %53 into %52 before copying %52 into %51 (which should
14653   // happen first).
14654   //
14655   // The problem is, however, that searching for such data dependencies
14656   // can become expensive, and the cost is not directly related to the
14657   // chain depth. Instead, we'll rule out such configurations here by
14658   // insisting that we've visited all chain users (except for users
14659   // of the original chain, which is not necessary). When doing this,
14660   // we need to look through nodes we don't care about (otherwise, things
14661   // like register copies will interfere with trivial cases).
14662
14663   SmallVector<const SDNode *, 16> Worklist;
14664   for (const SDNode *N : Visited)
14665     if (N != OriginalChain.getNode())
14666       Worklist.push_back(N);
14667
14668   while (!Worklist.empty()) {
14669     const SDNode *M = Worklist.pop_back_val();
14670
14671     // We have already visited M, and want to make sure we've visited any uses
14672     // of M that we care about. For uses that we've not visisted, and don't
14673     // care about, queue them to the worklist.
14674
14675     for (SDNode::use_iterator UI = M->use_begin(),
14676          UIE = M->use_end(); UI != UIE; ++UI)
14677       if (UI.getUse().getValueType() == MVT::Other &&
14678           Visited.insert(*UI).second) {
14679         if (isa<MemSDNode>(*UI)) {
14680           // We've not visited this use, and we care about it (it could have an
14681           // ordering dependency with the original node).
14682           Aliases.clear();
14683           Aliases.push_back(OriginalChain);
14684           return;
14685         }
14686
14687         // We've not visited this use, but we don't care about it. Mark it as
14688         // visited and enqueue it to the worklist.
14689         Worklist.push_back(*UI);
14690       }
14691   }
14692 }
14693
14694 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14695 /// (aliasing node.)
14696 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14697   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14698
14699   // Accumulate all the aliases to this node.
14700   GatherAllAliases(N, OldChain, Aliases);
14701
14702   // If no operands then chain to entry token.
14703   if (Aliases.size() == 0)
14704     return DAG.getEntryNode();
14705
14706   // If a single operand then chain to it.  We don't need to revisit it.
14707   if (Aliases.size() == 1)
14708     return Aliases[0];
14709
14710   // Construct a custom tailored token factor.
14711   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14712 }
14713
14714 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14715   // This holds the base pointer, index, and the offset in bytes from the base
14716   // pointer.
14717   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14718
14719   // We must have a base and an offset.
14720   if (!BasePtr.Base.getNode())
14721     return false;
14722
14723   // Do not handle stores to undef base pointers.
14724   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14725     return false;
14726
14727   SmallVector<StoreSDNode *, 8> ChainedStores;
14728   ChainedStores.push_back(St);
14729
14730   // Walk up the chain and look for nodes with offsets from the same
14731   // base pointer. Stop when reaching an instruction with a different kind
14732   // or instruction which has a different base pointer.
14733   StoreSDNode *Index = St;
14734   while (Index) {
14735     // If the chain has more than one use, then we can't reorder the mem ops.
14736     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14737       break;
14738
14739     if (Index->isVolatile() || Index->isIndexed())
14740       break;
14741
14742     // Find the base pointer and offset for this memory node.
14743     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14744
14745     // Check that the base pointer is the same as the original one.
14746     if (!Ptr.equalBaseIndex(BasePtr))
14747       break;
14748
14749     // Find the next memory operand in the chain. If the next operand in the
14750     // chain is a store then move up and continue the scan with the next
14751     // memory operand. If the next operand is a load save it and use alias
14752     // information to check if it interferes with anything.
14753     SDNode *NextInChain = Index->getChain().getNode();
14754     while (true) {
14755       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14756         // We found a store node. Use it for the next iteration.
14757         ChainedStores.push_back(STn);
14758         Index = STn;
14759         break;
14760       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14761         NextInChain = Ldn->getChain().getNode();
14762         continue;
14763       } else {
14764         Index = nullptr;
14765         break;
14766       }
14767     }
14768   }
14769
14770   bool MadeChange = false;
14771   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14772
14773   for (StoreSDNode *ChainedStore : ChainedStores) {
14774     SDValue Chain = ChainedStore->getChain();
14775     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14776
14777     if (Chain != BetterChain) {
14778       MadeChange = true;
14779       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14780     }
14781   }
14782
14783   // Do all replacements after finding the replacements to make to avoid making
14784   // the chains more complicated by introducing new TokenFactors.
14785   for (auto Replacement : BetterChains)
14786     replaceStoreChain(Replacement.first, Replacement.second);
14787
14788   return MadeChange;
14789 }
14790
14791 /// This is the entry point for the file.
14792 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14793                            CodeGenOpt::Level OptLevel) {
14794   /// This is the main entry point to this class.
14795   DAGCombiner(*this, AA, OptLevel).Run(Level);
14796 }