[CodeGen] Check FoldConstantArithmetic result before using it.
[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     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitIMINMAX(SDNode *N);
249     SDValue visitAND(SDNode *N);
250     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251     SDValue visitOR(SDNode *N);
252     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitXOR(SDNode *N);
254     SDValue SimplifyVBinOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitBSWAP(SDNode *N);
260     SDValue visitCTLZ(SDNode *N);
261     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTTZ(SDNode *N);
263     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTPOP(SDNode *N);
265     SDValue visitSELECT(SDNode *N);
266     SDValue visitVSELECT(SDNode *N);
267     SDValue visitSELECT_CC(SDNode *N);
268     SDValue visitSETCC(SDNode *N);
269     SDValue visitSIGN_EXTEND(SDNode *N);
270     SDValue visitZERO_EXTEND(SDNode *N);
271     SDValue visitANY_EXTEND(SDNode *N);
272     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274     SDValue visitTRUNCATE(SDNode *N);
275     SDValue visitBITCAST(SDNode *N);
276     SDValue visitBUILD_PAIR(SDNode *N);
277     SDValue visitFADD(SDNode *N);
278     SDValue visitFSUB(SDNode *N);
279     SDValue visitFMUL(SDNode *N);
280     SDValue visitFMA(SDNode *N);
281     SDValue visitFDIV(SDNode *N);
282     SDValue visitFREM(SDNode *N);
283     SDValue visitFSQRT(SDNode *N);
284     SDValue visitFCOPYSIGN(SDNode *N);
285     SDValue visitSINT_TO_FP(SDNode *N);
286     SDValue visitUINT_TO_FP(SDNode *N);
287     SDValue visitFP_TO_SINT(SDNode *N);
288     SDValue visitFP_TO_UINT(SDNode *N);
289     SDValue visitFP_ROUND(SDNode *N);
290     SDValue visitFP_ROUND_INREG(SDNode *N);
291     SDValue visitFP_EXTEND(SDNode *N);
292     SDValue visitFNEG(SDNode *N);
293     SDValue visitFABS(SDNode *N);
294     SDValue visitFCEIL(SDNode *N);
295     SDValue visitFTRUNC(SDNode *N);
296     SDValue visitFFLOOR(SDNode *N);
297     SDValue visitFMINNUM(SDNode *N);
298     SDValue visitFMAXNUM(SDNode *N);
299     SDValue visitBRCOND(SDNode *N);
300     SDValue visitBR_CC(SDNode *N);
301     SDValue visitLOAD(SDNode *N);
302     SDValue visitSTORE(SDNode *N);
303     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
304     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
305     SDValue visitBUILD_VECTOR(SDNode *N);
306     SDValue visitCONCAT_VECTORS(SDNode *N);
307     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
308     SDValue visitVECTOR_SHUFFLE(SDNode *N);
309     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
310     SDValue visitINSERT_SUBVECTOR(SDNode *N);
311     SDValue visitMLOAD(SDNode *N);
312     SDValue visitMSTORE(SDNode *N);
313     SDValue visitMGATHER(SDNode *N);
314     SDValue visitMSCATTER(SDNode *N);
315     SDValue visitFP_TO_FP16(SDNode *N);
316     SDValue visitFP16_TO_FP(SDNode *N);
317
318     SDValue visitFADDForFMACombine(SDNode *N);
319     SDValue visitFSUBForFMACombine(SDNode *N);
320
321     SDValue XformToShuffleWithZero(SDNode *N);
322     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
323
324     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
325
326     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
327     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
328     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
329     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
330                              SDValue N3, ISD::CondCode CC,
331                              bool NotExtCompare = false);
332     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
333                           SDLoc DL, bool foldBooleans = true);
334
335     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
336                            SDValue &CC) const;
337     bool isOneUseSetCC(SDValue N) const;
338
339     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
340                                          unsigned HiOp);
341     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
342     SDValue CombineExtLoad(SDNode *N);
343     SDValue combineRepeatedFPDivisors(SDNode *N);
344     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
345     SDValue BuildSDIV(SDNode *N);
346     SDValue BuildSDIVPow2(SDNode *N);
347     SDValue BuildUDIV(SDNode *N);
348     SDValue BuildReciprocalEstimate(SDValue Op);
349     SDValue BuildRsqrtEstimate(SDValue Op);
350     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
351     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
352     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
353                                bool DemandHighBits = true);
354     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
355     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
356                               SDValue InnerPos, SDValue InnerNeg,
357                               unsigned PosOpcode, unsigned NegOpcode,
358                               SDLoc DL);
359     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
360     SDValue ReduceLoadWidth(SDNode *N);
361     SDValue ReduceLoadOpStoreWidth(SDNode *N);
362     SDValue TransformFPLoadStorePair(SDNode *N);
363     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
364     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
365
366     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
367
368     /// Walk up chain skipping non-aliasing memory nodes,
369     /// looking for aliasing nodes and adding them to the Aliases vector.
370     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
371                           SmallVectorImpl<SDValue> &Aliases);
372
373     /// Return true if there is any possibility that the two addresses overlap.
374     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
375
376     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
377     /// chain (aliasing node.)
378     SDValue FindBetterChain(SDNode *N, SDValue Chain);
379
380     /// Holds a pointer to an LSBaseSDNode as well as information on where it
381     /// is located in a sequence of memory operations connected by a chain.
382     struct MemOpLink {
383       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
384       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
385       // Ptr to the mem node.
386       LSBaseSDNode *MemNode;
387       // Offset from the base ptr.
388       int64_t OffsetFromBase;
389       // What is the sequence number of this mem node.
390       // Lowest mem operand in the DAG starts at zero.
391       unsigned SequenceNum;
392     };
393
394     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
395     /// constant build_vector of the stored constant values in Stores.
396     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
397                                          SDLoc SL,
398                                          ArrayRef<MemOpLink> Stores,
399                                          EVT Ty) const;
400
401     /// This is a helper function for MergeConsecutiveStores. When the source
402     /// elements of the consecutive stores are all constants or all extracted
403     /// vector elements, try to merge them into one larger store.
404     /// \return True if a merged store was created.
405     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
406                                          EVT MemVT, unsigned NumElem,
407                                          bool IsConstantSrc, bool UseVector);
408
409     /// This is a helper function for MergeConsecutiveStores.
410     /// Stores that may be merged are placed in StoreNodes.
411     /// Loads that may alias with those stores are placed in AliasLoadNodes.
412     void getStoreMergeAndAliasCandidates(
413         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
414         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
415
416     /// Merge consecutive store operations into a wide store.
417     /// This optimization uses wide integers or vectors when possible.
418     /// \return True if some memory operations were changed.
419     bool MergeConsecutiveStores(StoreSDNode *N);
420
421     /// \brief Try to transform a truncation where C is a constant:
422     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
423     ///
424     /// \p N needs to be a truncation and its first operand an AND. Other
425     /// requirements are checked by the function (e.g. that trunc is
426     /// single-use) and if missed an empty SDValue is returned.
427     SDValue distributeTruncateThroughAnd(SDNode *N);
428
429   public:
430     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
431         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
432           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
433       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
434     }
435
436     /// Runs the dag combiner on all nodes in the work list
437     void Run(CombineLevel AtLevel);
438
439     SelectionDAG &getDAG() const { return DAG; }
440
441     /// Returns a type large enough to hold any valid shift amount - before type
442     /// legalization these can be huge.
443     EVT getShiftAmountTy(EVT LHSTy) {
444       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
445       if (LHSTy.isVector())
446         return LHSTy;
447       auto &DL = DAG.getDataLayout();
448       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
449                         : TLI.getPointerTy(DL);
450     }
451
452     /// This method returns true if we are running before type legalization or
453     /// if the specified VT is legal.
454     bool isTypeLegal(const EVT &VT) {
455       if (!LegalTypes) return true;
456       return TLI.isTypeLegal(VT);
457     }
458
459     /// Convenience wrapper around TargetLowering::getSetCCResultType
460     EVT getSetCCResultType(EVT VT) const {
461       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
462     }
463   };
464 }
465
466
467 namespace {
468 /// This class is a DAGUpdateListener that removes any deleted
469 /// nodes from the worklist.
470 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
471   DAGCombiner &DC;
472 public:
473   explicit WorklistRemover(DAGCombiner &dc)
474     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
475
476   void NodeDeleted(SDNode *N, SDNode *E) override {
477     DC.removeFromWorklist(N);
478   }
479 };
480 }
481
482 //===----------------------------------------------------------------------===//
483 //  TargetLowering::DAGCombinerInfo implementation
484 //===----------------------------------------------------------------------===//
485
486 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
487   ((DAGCombiner*)DC)->AddToWorklist(N);
488 }
489
490 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
491   ((DAGCombiner*)DC)->removeFromWorklist(N);
492 }
493
494 SDValue TargetLowering::DAGCombinerInfo::
495 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
496   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
497 }
498
499 SDValue TargetLowering::DAGCombinerInfo::
500 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
501   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
502 }
503
504
505 SDValue TargetLowering::DAGCombinerInfo::
506 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
507   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
508 }
509
510 void TargetLowering::DAGCombinerInfo::
511 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
512   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
513 }
514
515 //===----------------------------------------------------------------------===//
516 // Helper Functions
517 //===----------------------------------------------------------------------===//
518
519 void DAGCombiner::deleteAndRecombine(SDNode *N) {
520   removeFromWorklist(N);
521
522   // If the operands of this node are only used by the node, they will now be
523   // dead. Make sure to re-visit them and recursively delete dead nodes.
524   for (const SDValue &Op : N->ops())
525     // For an operand generating multiple values, one of the values may
526     // become dead allowing further simplification (e.g. split index
527     // arithmetic from an indexed load).
528     if (Op->hasOneUse() || Op->getNumValues() > 1)
529       AddToWorklist(Op.getNode());
530
531   DAG.DeleteNode(N);
532 }
533
534 /// Return 1 if we can compute the negated form of the specified expression for
535 /// the same cost as the expression itself, or 2 if we can compute the negated
536 /// form more cheaply than the expression itself.
537 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
538                                const TargetLowering &TLI,
539                                const TargetOptions *Options,
540                                unsigned Depth = 0) {
541   // fneg is removable even if it has multiple uses.
542   if (Op.getOpcode() == ISD::FNEG) return 2;
543
544   // Don't allow anything with multiple uses.
545   if (!Op.hasOneUse()) return 0;
546
547   // Don't recurse exponentially.
548   if (Depth > 6) return 0;
549
550   switch (Op.getOpcode()) {
551   default: return false;
552   case ISD::ConstantFP:
553     // Don't invert constant FP values after legalize.  The negated constant
554     // isn't necessarily legal.
555     return LegalOperations ? 0 : 1;
556   case ISD::FADD:
557     // FIXME: determine better conditions for this xform.
558     if (!Options->UnsafeFPMath) return 0;
559
560     // After operation legalization, it might not be legal to create new FSUBs.
561     if (LegalOperations &&
562         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
563       return 0;
564
565     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572   case ISD::FSUB:
573     // We can't turn -(A-B) into B-A when we honor signed zeros.
574     if (!Options->UnsafeFPMath) return 0;
575
576     // fold (fneg (fsub A, B)) -> (fsub B, A)
577     return 1;
578
579   case ISD::FMUL:
580   case ISD::FDIV:
581     if (Options->HonorSignDependentRoundingFPMath()) return 0;
582
583     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
584     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
585                                     Options, Depth + 1))
586       return V;
587
588     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
589                               Depth + 1);
590
591   case ISD::FP_EXTEND:
592   case ISD::FP_ROUND:
593   case ISD::FSIN:
594     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
595                               Depth + 1);
596   }
597 }
598
599 /// If isNegatibleForFree returns true, return the newly negated expression.
600 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
601                                     bool LegalOperations, unsigned Depth = 0) {
602   const TargetOptions &Options = DAG.getTarget().Options;
603   // fneg is removable even if it has multiple uses.
604   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
605
606   // Don't allow anything with multiple uses.
607   assert(Op.hasOneUse() && "Unknown reuse!");
608
609   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
610   switch (Op.getOpcode()) {
611   default: llvm_unreachable("Unknown code");
612   case ISD::ConstantFP: {
613     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
614     V.changeSign();
615     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
616   }
617   case ISD::FADD:
618     // FIXME: determine better conditions for this xform.
619     assert(Options.UnsafeFPMath);
620
621     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
622     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
623                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
624       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
625                          GetNegatedExpression(Op.getOperand(0), DAG,
626                                               LegalOperations, Depth+1),
627                          Op.getOperand(1));
628     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
629     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
630                        GetNegatedExpression(Op.getOperand(1), DAG,
631                                             LegalOperations, Depth+1),
632                        Op.getOperand(0));
633   case ISD::FSUB:
634     // We can't turn -(A-B) into B-A when we honor signed zeros.
635     assert(Options.UnsafeFPMath);
636
637     // fold (fneg (fsub 0, B)) -> B
638     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
639       if (N0CFP->isZero())
640         return Op.getOperand(1);
641
642     // fold (fneg (fsub A, B)) -> (fsub B, A)
643     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
644                        Op.getOperand(1), Op.getOperand(0));
645
646   case ISD::FMUL:
647   case ISD::FDIV:
648     assert(!Options.HonorSignDependentRoundingFPMath());
649
650     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
651     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
652                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
653       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
654                          GetNegatedExpression(Op.getOperand(0), DAG,
655                                               LegalOperations, Depth+1),
656                          Op.getOperand(1));
657
658     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
659     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
660                        Op.getOperand(0),
661                        GetNegatedExpression(Op.getOperand(1), DAG,
662                                             LegalOperations, Depth+1));
663
664   case ISD::FP_EXTEND:
665   case ISD::FSIN:
666     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
667                        GetNegatedExpression(Op.getOperand(0), DAG,
668                                             LegalOperations, Depth+1));
669   case ISD::FP_ROUND:
670       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
671                          GetNegatedExpression(Op.getOperand(0), DAG,
672                                               LegalOperations, Depth+1),
673                          Op.getOperand(1));
674   }
675 }
676
677 // Return true if this node is a setcc, or is a select_cc
678 // that selects between the target values used for true and false, making it
679 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
680 // the appropriate nodes based on the type of node we are checking. This
681 // simplifies life a bit for the callers.
682 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
683                                     SDValue &CC) const {
684   if (N.getOpcode() == ISD::SETCC) {
685     LHS = N.getOperand(0);
686     RHS = N.getOperand(1);
687     CC  = N.getOperand(2);
688     return true;
689   }
690
691   if (N.getOpcode() != ISD::SELECT_CC ||
692       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
693       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
694     return false;
695
696   if (TLI.getBooleanContents(N.getValueType()) ==
697       TargetLowering::UndefinedBooleanContent)
698     return false;
699
700   LHS = N.getOperand(0);
701   RHS = N.getOperand(1);
702   CC  = N.getOperand(4);
703   return true;
704 }
705
706 /// Return true if this is a SetCC-equivalent operation with only one use.
707 /// If this is true, it allows the users to invert the operation for free when
708 /// it is profitable to do so.
709 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
710   SDValue N0, N1, N2;
711   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
712     return true;
713   return false;
714 }
715
716 /// Returns true if N is a BUILD_VECTOR node whose
717 /// elements are all the same constant or undefined.
718 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
719   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
720   if (!C)
721     return false;
722
723   APInt SplatUndef;
724   unsigned SplatBitSize;
725   bool HasAnyUndefs;
726   EVT EltVT = N->getValueType(0).getVectorElementType();
727   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
728                              HasAnyUndefs) &&
729           EltVT.getSizeInBits() >= SplatBitSize);
730 }
731
732 // \brief Returns the SDNode if it is a constant integer BuildVector
733 // or constant integer.
734 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
735   if (isa<ConstantSDNode>(N))
736     return N.getNode();
737   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
738     return N.getNode();
739   return nullptr;
740 }
741
742 // \brief Returns the SDNode if it is a constant float BuildVector
743 // or constant float.
744 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
745   if (isa<ConstantFPSDNode>(N))
746     return N.getNode();
747   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
748     return N.getNode();
749   return nullptr;
750 }
751
752 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
753 // int.
754 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
755   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
756     return CN;
757
758   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
759     BitVector UndefElements;
760     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
761
762     // BuildVectors can truncate their operands. Ignore that case here.
763     // FIXME: We blindly ignore splats which include undef which is overly
764     // pessimistic.
765     if (CN && UndefElements.none() &&
766         CN->getValueType(0) == N.getValueType().getScalarType())
767       return CN;
768   }
769
770   return nullptr;
771 }
772
773 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
774 // float.
775 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
776   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
777     return CN;
778
779   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
780     BitVector UndefElements;
781     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
782
783     if (CN && UndefElements.none())
784       return CN;
785   }
786
787   return nullptr;
788 }
789
790 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
791                                     SDValue N0, SDValue N1) {
792   EVT VT = N0.getValueType();
793   if (N0.getOpcode() == Opc) {
794     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
795       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
796         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
797         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
798           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
799         return SDValue();
800       }
801       if (N0.hasOneUse()) {
802         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
803         // use
804         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
805         if (!OpNode.getNode())
806           return SDValue();
807         AddToWorklist(OpNode.getNode());
808         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
809       }
810     }
811   }
812
813   if (N1.getOpcode() == Opc) {
814     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
815       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
816         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
817         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
818           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
819         return SDValue();
820       }
821       if (N1.hasOneUse()) {
822         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
823         // use
824         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
825         if (!OpNode.getNode())
826           return SDValue();
827         AddToWorklist(OpNode.getNode());
828         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
829       }
830     }
831   }
832
833   return SDValue();
834 }
835
836 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
837                                bool AddTo) {
838   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
839   ++NodesCombined;
840   DEBUG(dbgs() << "\nReplacing.1 ";
841         N->dump(&DAG);
842         dbgs() << "\nWith: ";
843         To[0].getNode()->dump(&DAG);
844         dbgs() << " and " << NumTo-1 << " other values\n");
845   for (unsigned i = 0, e = NumTo; i != e; ++i)
846     assert((!To[i].getNode() ||
847             N->getValueType(i) == To[i].getValueType()) &&
848            "Cannot combine value to value of different type!");
849
850   WorklistRemover DeadNodes(*this);
851   DAG.ReplaceAllUsesWith(N, To);
852   if (AddTo) {
853     // Push the new nodes and any users onto the worklist
854     for (unsigned i = 0, e = NumTo; i != e; ++i) {
855       if (To[i].getNode()) {
856         AddToWorklist(To[i].getNode());
857         AddUsersToWorklist(To[i].getNode());
858       }
859     }
860   }
861
862   // Finally, if the node is now dead, remove it from the graph.  The node
863   // may not be dead if the replacement process recursively simplified to
864   // something else needing this node.
865   if (N->use_empty())
866     deleteAndRecombine(N);
867   return SDValue(N, 0);
868 }
869
870 void DAGCombiner::
871 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
872   // Replace all uses.  If any nodes become isomorphic to other nodes and
873   // are deleted, make sure to remove them from our worklist.
874   WorklistRemover DeadNodes(*this);
875   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
876
877   // Push the new node and any (possibly new) users onto the worklist.
878   AddToWorklist(TLO.New.getNode());
879   AddUsersToWorklist(TLO.New.getNode());
880
881   // Finally, if the node is now dead, remove it from the graph.  The node
882   // may not be dead if the replacement process recursively simplified to
883   // something else needing this node.
884   if (TLO.Old.getNode()->use_empty())
885     deleteAndRecombine(TLO.Old.getNode());
886 }
887
888 /// Check the specified integer node value to see if it can be simplified or if
889 /// things it uses can be simplified by bit propagation. If so, return true.
890 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
891   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
892   APInt KnownZero, KnownOne;
893   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
894     return false;
895
896   // Revisit the node.
897   AddToWorklist(Op.getNode());
898
899   // Replace the old value with the new one.
900   ++NodesCombined;
901   DEBUG(dbgs() << "\nReplacing.2 ";
902         TLO.Old.getNode()->dump(&DAG);
903         dbgs() << "\nWith: ";
904         TLO.New.getNode()->dump(&DAG);
905         dbgs() << '\n');
906
907   CommitTargetLoweringOpt(TLO);
908   return true;
909 }
910
911 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
912   SDLoc dl(Load);
913   EVT VT = Load->getValueType(0);
914   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
915
916   DEBUG(dbgs() << "\nReplacing.9 ";
917         Load->dump(&DAG);
918         dbgs() << "\nWith: ";
919         Trunc.getNode()->dump(&DAG);
920         dbgs() << '\n');
921   WorklistRemover DeadNodes(*this);
922   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
923   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
924   deleteAndRecombine(Load);
925   AddToWorklist(Trunc.getNode());
926 }
927
928 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
929   Replace = false;
930   SDLoc dl(Op);
931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
932     EVT MemVT = LD->getMemoryVT();
933     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
934       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
935                                                        : ISD::EXTLOAD)
936       : LD->getExtensionType();
937     Replace = true;
938     return DAG.getExtLoad(ExtType, dl, PVT,
939                           LD->getChain(), LD->getBasePtr(),
940                           MemVT, LD->getMemOperand());
941   }
942
943   unsigned Opc = Op.getOpcode();
944   switch (Opc) {
945   default: break;
946   case ISD::AssertSext:
947     return DAG.getNode(ISD::AssertSext, dl, PVT,
948                        SExtPromoteOperand(Op.getOperand(0), PVT),
949                        Op.getOperand(1));
950   case ISD::AssertZext:
951     return DAG.getNode(ISD::AssertZext, dl, PVT,
952                        ZExtPromoteOperand(Op.getOperand(0), PVT),
953                        Op.getOperand(1));
954   case ISD::Constant: {
955     unsigned ExtOpc =
956       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
957     return DAG.getNode(ExtOpc, dl, PVT, Op);
958   }
959   }
960
961   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
962     return SDValue();
963   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
964 }
965
966 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
967   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
968     return SDValue();
969   EVT OldVT = Op.getValueType();
970   SDLoc dl(Op);
971   bool Replace = false;
972   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
973   if (!NewOp.getNode())
974     return SDValue();
975   AddToWorklist(NewOp.getNode());
976
977   if (Replace)
978     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
979   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
980                      DAG.getValueType(OldVT));
981 }
982
983 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
984   EVT OldVT = Op.getValueType();
985   SDLoc dl(Op);
986   bool Replace = false;
987   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
988   if (!NewOp.getNode())
989     return SDValue();
990   AddToWorklist(NewOp.getNode());
991
992   if (Replace)
993     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
994   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
995 }
996
997 /// Promote the specified integer binary operation if the target indicates it is
998 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
999 /// i32 since i16 instructions are longer.
1000 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1001   if (!LegalOperations)
1002     return SDValue();
1003
1004   EVT VT = Op.getValueType();
1005   if (VT.isVector() || !VT.isInteger())
1006     return SDValue();
1007
1008   // If operation type is 'undesirable', e.g. i16 on x86, consider
1009   // promoting it.
1010   unsigned Opc = Op.getOpcode();
1011   if (TLI.isTypeDesirableForOp(Opc, VT))
1012     return SDValue();
1013
1014   EVT PVT = VT;
1015   // Consult target whether it is a good idea to promote this operation and
1016   // what's the right type to promote it to.
1017   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1018     assert(PVT != VT && "Don't know what type to promote to!");
1019
1020     bool Replace0 = false;
1021     SDValue N0 = Op.getOperand(0);
1022     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1023     if (!NN0.getNode())
1024       return SDValue();
1025
1026     bool Replace1 = false;
1027     SDValue N1 = Op.getOperand(1);
1028     SDValue NN1;
1029     if (N0 == N1)
1030       NN1 = NN0;
1031     else {
1032       NN1 = PromoteOperand(N1, PVT, Replace1);
1033       if (!NN1.getNode())
1034         return SDValue();
1035     }
1036
1037     AddToWorklist(NN0.getNode());
1038     if (NN1.getNode())
1039       AddToWorklist(NN1.getNode());
1040
1041     if (Replace0)
1042       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1043     if (Replace1)
1044       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1045
1046     DEBUG(dbgs() << "\nPromoting ";
1047           Op.getNode()->dump(&DAG));
1048     SDLoc dl(Op);
1049     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1050                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1051   }
1052   return SDValue();
1053 }
1054
1055 /// Promote the specified integer shift operation if the target indicates it is
1056 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1057 /// i32 since i16 instructions are longer.
1058 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1059   if (!LegalOperations)
1060     return SDValue();
1061
1062   EVT VT = Op.getValueType();
1063   if (VT.isVector() || !VT.isInteger())
1064     return SDValue();
1065
1066   // If operation type is 'undesirable', e.g. i16 on x86, consider
1067   // promoting it.
1068   unsigned Opc = Op.getOpcode();
1069   if (TLI.isTypeDesirableForOp(Opc, VT))
1070     return SDValue();
1071
1072   EVT PVT = VT;
1073   // Consult target whether it is a good idea to promote this operation and
1074   // what's the right type to promote it to.
1075   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1076     assert(PVT != VT && "Don't know what type to promote to!");
1077
1078     bool Replace = false;
1079     SDValue N0 = Op.getOperand(0);
1080     if (Opc == ISD::SRA)
1081       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1082     else if (Opc == ISD::SRL)
1083       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1084     else
1085       N0 = PromoteOperand(N0, PVT, Replace);
1086     if (!N0.getNode())
1087       return SDValue();
1088
1089     AddToWorklist(N0.getNode());
1090     if (Replace)
1091       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1092
1093     DEBUG(dbgs() << "\nPromoting ";
1094           Op.getNode()->dump(&DAG));
1095     SDLoc dl(Op);
1096     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1097                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1098   }
1099   return SDValue();
1100 }
1101
1102 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1103   if (!LegalOperations)
1104     return SDValue();
1105
1106   EVT VT = Op.getValueType();
1107   if (VT.isVector() || !VT.isInteger())
1108     return SDValue();
1109
1110   // If operation type is 'undesirable', e.g. i16 on x86, consider
1111   // promoting it.
1112   unsigned Opc = Op.getOpcode();
1113   if (TLI.isTypeDesirableForOp(Opc, VT))
1114     return SDValue();
1115
1116   EVT PVT = VT;
1117   // Consult target whether it is a good idea to promote this operation and
1118   // what's the right type to promote it to.
1119   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1120     assert(PVT != VT && "Don't know what type to promote to!");
1121     // fold (aext (aext x)) -> (aext x)
1122     // fold (aext (zext x)) -> (zext x)
1123     // fold (aext (sext x)) -> (sext x)
1124     DEBUG(dbgs() << "\nPromoting ";
1125           Op.getNode()->dump(&DAG));
1126     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1127   }
1128   return SDValue();
1129 }
1130
1131 bool DAGCombiner::PromoteLoad(SDValue Op) {
1132   if (!LegalOperations)
1133     return false;
1134
1135   EVT VT = Op.getValueType();
1136   if (VT.isVector() || !VT.isInteger())
1137     return false;
1138
1139   // If operation type is 'undesirable', e.g. i16 on x86, consider
1140   // promoting it.
1141   unsigned Opc = Op.getOpcode();
1142   if (TLI.isTypeDesirableForOp(Opc, VT))
1143     return false;
1144
1145   EVT PVT = VT;
1146   // Consult target whether it is a good idea to promote this operation and
1147   // what's the right type to promote it to.
1148   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1149     assert(PVT != VT && "Don't know what type to promote to!");
1150
1151     SDLoc dl(Op);
1152     SDNode *N = Op.getNode();
1153     LoadSDNode *LD = cast<LoadSDNode>(N);
1154     EVT MemVT = LD->getMemoryVT();
1155     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1156       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1157                                                        : ISD::EXTLOAD)
1158       : LD->getExtensionType();
1159     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1160                                    LD->getChain(), LD->getBasePtr(),
1161                                    MemVT, LD->getMemOperand());
1162     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1163
1164     DEBUG(dbgs() << "\nPromoting ";
1165           N->dump(&DAG);
1166           dbgs() << "\nTo: ";
1167           Result.getNode()->dump(&DAG);
1168           dbgs() << '\n');
1169     WorklistRemover DeadNodes(*this);
1170     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1171     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1172     deleteAndRecombine(N);
1173     AddToWorklist(Result.getNode());
1174     return true;
1175   }
1176   return false;
1177 }
1178
1179 /// \brief Recursively delete a node which has no uses and any operands for
1180 /// which it is the only use.
1181 ///
1182 /// Note that this both deletes the nodes and removes them from the worklist.
1183 /// It also adds any nodes who have had a user deleted to the worklist as they
1184 /// may now have only one use and subject to other combines.
1185 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1186   if (!N->use_empty())
1187     return false;
1188
1189   SmallSetVector<SDNode *, 16> Nodes;
1190   Nodes.insert(N);
1191   do {
1192     N = Nodes.pop_back_val();
1193     if (!N)
1194       continue;
1195
1196     if (N->use_empty()) {
1197       for (const SDValue &ChildN : N->op_values())
1198         Nodes.insert(ChildN.getNode());
1199
1200       removeFromWorklist(N);
1201       DAG.DeleteNode(N);
1202     } else {
1203       AddToWorklist(N);
1204     }
1205   } while (!Nodes.empty());
1206   return true;
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 //  Main DAG Combiner implementation
1211 //===----------------------------------------------------------------------===//
1212
1213 void DAGCombiner::Run(CombineLevel AtLevel) {
1214   // set the instance variables, so that the various visit routines may use it.
1215   Level = AtLevel;
1216   LegalOperations = Level >= AfterLegalizeVectorOps;
1217   LegalTypes = Level >= AfterLegalizeTypes;
1218
1219   // Add all the dag nodes to the worklist.
1220   for (SDNode &Node : DAG.allnodes())
1221     AddToWorklist(&Node);
1222
1223   // Create a dummy node (which is not added to allnodes), that adds a reference
1224   // to the root node, preventing it from being deleted, and tracking any
1225   // changes of the root.
1226   HandleSDNode Dummy(DAG.getRoot());
1227
1228   // while the worklist isn't empty, find a node and
1229   // try and combine it.
1230   while (!WorklistMap.empty()) {
1231     SDNode *N;
1232     // The Worklist holds the SDNodes in order, but it may contain null entries.
1233     do {
1234       N = Worklist.pop_back_val();
1235     } while (!N);
1236
1237     bool GoodWorklistEntry = WorklistMap.erase(N);
1238     (void)GoodWorklistEntry;
1239     assert(GoodWorklistEntry &&
1240            "Found a worklist entry without a corresponding map entry!");
1241
1242     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1243     // N is deleted from the DAG, since they too may now be dead or may have a
1244     // reduced number of uses, allowing other xforms.
1245     if (recursivelyDeleteUnusedNodes(N))
1246       continue;
1247
1248     WorklistRemover DeadNodes(*this);
1249
1250     // If this combine is running after legalizing the DAG, re-legalize any
1251     // nodes pulled off the worklist.
1252     if (Level == AfterLegalizeDAG) {
1253       SmallSetVector<SDNode *, 16> UpdatedNodes;
1254       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1255
1256       for (SDNode *LN : UpdatedNodes) {
1257         AddToWorklist(LN);
1258         AddUsersToWorklist(LN);
1259       }
1260       if (!NIsValid)
1261         continue;
1262     }
1263
1264     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1265
1266     // Add any operands of the new node which have not yet been combined to the
1267     // worklist as well. Because the worklist uniques things already, this
1268     // won't repeatedly process the same operand.
1269     CombinedNodes.insert(N);
1270     for (const SDValue &ChildN : N->op_values())
1271       if (!CombinedNodes.count(ChildN.getNode()))
1272         AddToWorklist(ChildN.getNode());
1273
1274     SDValue RV = combine(N);
1275
1276     if (!RV.getNode())
1277       continue;
1278
1279     ++NodesCombined;
1280
1281     // If we get back the same node we passed in, rather than a new node or
1282     // zero, we know that the node must have defined multiple values and
1283     // CombineTo was used.  Since CombineTo takes care of the worklist
1284     // mechanics for us, we have no work to do in this case.
1285     if (RV.getNode() == N)
1286       continue;
1287
1288     assert(N->getOpcode() != ISD::DELETED_NODE &&
1289            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1290            "Node was deleted but visit returned new node!");
1291
1292     DEBUG(dbgs() << " ... into: ";
1293           RV.getNode()->dump(&DAG));
1294
1295     // Transfer debug value.
1296     DAG.TransferDbgValues(SDValue(N, 0), RV);
1297     if (N->getNumValues() == RV.getNode()->getNumValues())
1298       DAG.ReplaceAllUsesWith(N, RV.getNode());
1299     else {
1300       assert(N->getValueType(0) == RV.getValueType() &&
1301              N->getNumValues() == 1 && "Type mismatch");
1302       SDValue OpV = RV;
1303       DAG.ReplaceAllUsesWith(N, &OpV);
1304     }
1305
1306     // Push the new node and any users onto the worklist
1307     AddToWorklist(RV.getNode());
1308     AddUsersToWorklist(RV.getNode());
1309
1310     // Finally, if the node is now dead, remove it from the graph.  The node
1311     // may not be dead if the replacement process recursively simplified to
1312     // something else needing this node. This will also take care of adding any
1313     // operands which have lost a user to the worklist.
1314     recursivelyDeleteUnusedNodes(N);
1315   }
1316
1317   // If the root changed (e.g. it was a dead load, update the root).
1318   DAG.setRoot(Dummy.getValue());
1319   DAG.RemoveDeadNodes();
1320 }
1321
1322 SDValue DAGCombiner::visit(SDNode *N) {
1323   switch (N->getOpcode()) {
1324   default: break;
1325   case ISD::TokenFactor:        return visitTokenFactor(N);
1326   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1327   case ISD::ADD:                return visitADD(N);
1328   case ISD::SUB:                return visitSUB(N);
1329   case ISD::ADDC:               return visitADDC(N);
1330   case ISD::SUBC:               return visitSUBC(N);
1331   case ISD::ADDE:               return visitADDE(N);
1332   case ISD::SUBE:               return visitSUBE(N);
1333   case ISD::MUL:                return visitMUL(N);
1334   case ISD::SDIV:               return visitSDIV(N);
1335   case ISD::UDIV:               return visitUDIV(N);
1336   case ISD::SREM:               return visitSREM(N);
1337   case ISD::UREM:               return visitUREM(N);
1338   case ISD::MULHU:              return visitMULHU(N);
1339   case ISD::MULHS:              return visitMULHS(N);
1340   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1341   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1342   case ISD::SMULO:              return visitSMULO(N);
1343   case ISD::UMULO:              return visitUMULO(N);
1344   case ISD::SDIVREM:            return visitSDIVREM(N);
1345   case ISD::UDIVREM:            return visitUDIVREM(N);
1346   case ISD::SMIN:
1347   case ISD::SMAX:
1348   case ISD::UMIN:
1349   case ISD::UMAX:               return visitIMINMAX(N);
1350   case ISD::AND:                return visitAND(N);
1351   case ISD::OR:                 return visitOR(N);
1352   case ISD::XOR:                return visitXOR(N);
1353   case ISD::SHL:                return visitSHL(N);
1354   case ISD::SRA:                return visitSRA(N);
1355   case ISD::SRL:                return visitSRL(N);
1356   case ISD::ROTR:
1357   case ISD::ROTL:               return visitRotate(N);
1358   case ISD::BSWAP:              return visitBSWAP(N);
1359   case ISD::CTLZ:               return visitCTLZ(N);
1360   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1361   case ISD::CTTZ:               return visitCTTZ(N);
1362   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1363   case ISD::CTPOP:              return visitCTPOP(N);
1364   case ISD::SELECT:             return visitSELECT(N);
1365   case ISD::VSELECT:            return visitVSELECT(N);
1366   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1367   case ISD::SETCC:              return visitSETCC(N);
1368   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1369   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1370   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1371   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1372   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1373   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1374   case ISD::BITCAST:            return visitBITCAST(N);
1375   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1376   case ISD::FADD:               return visitFADD(N);
1377   case ISD::FSUB:               return visitFSUB(N);
1378   case ISD::FMUL:               return visitFMUL(N);
1379   case ISD::FMA:                return visitFMA(N);
1380   case ISD::FDIV:               return visitFDIV(N);
1381   case ISD::FREM:               return visitFREM(N);
1382   case ISD::FSQRT:              return visitFSQRT(N);
1383   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1384   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1385   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1386   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1387   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1388   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1389   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1390   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1391   case ISD::FNEG:               return visitFNEG(N);
1392   case ISD::FABS:               return visitFABS(N);
1393   case ISD::FFLOOR:             return visitFFLOOR(N);
1394   case ISD::FMINNUM:            return visitFMINNUM(N);
1395   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1396   case ISD::FCEIL:              return visitFCEIL(N);
1397   case ISD::FTRUNC:             return visitFTRUNC(N);
1398   case ISD::BRCOND:             return visitBRCOND(N);
1399   case ISD::BR_CC:              return visitBR_CC(N);
1400   case ISD::LOAD:               return visitLOAD(N);
1401   case ISD::STORE:              return visitSTORE(N);
1402   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1403   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1404   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1405   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1406   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1407   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1408   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1409   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1410   case ISD::MGATHER:            return visitMGATHER(N);
1411   case ISD::MLOAD:              return visitMLOAD(N);
1412   case ISD::MSCATTER:           return visitMSCATTER(N);
1413   case ISD::MSTORE:             return visitMSTORE(N);
1414   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1415   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1416   }
1417   return SDValue();
1418 }
1419
1420 SDValue DAGCombiner::combine(SDNode *N) {
1421   SDValue RV = visit(N);
1422
1423   // If nothing happened, try a target-specific DAG combine.
1424   if (!RV.getNode()) {
1425     assert(N->getOpcode() != ISD::DELETED_NODE &&
1426            "Node was deleted but visit returned NULL!");
1427
1428     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1429         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1430
1431       // Expose the DAG combiner to the target combiner impls.
1432       TargetLowering::DAGCombinerInfo
1433         DagCombineInfo(DAG, Level, false, this);
1434
1435       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1436     }
1437   }
1438
1439   // If nothing happened still, try promoting the operation.
1440   if (!RV.getNode()) {
1441     switch (N->getOpcode()) {
1442     default: break;
1443     case ISD::ADD:
1444     case ISD::SUB:
1445     case ISD::MUL:
1446     case ISD::AND:
1447     case ISD::OR:
1448     case ISD::XOR:
1449       RV = PromoteIntBinOp(SDValue(N, 0));
1450       break;
1451     case ISD::SHL:
1452     case ISD::SRA:
1453     case ISD::SRL:
1454       RV = PromoteIntShiftOp(SDValue(N, 0));
1455       break;
1456     case ISD::SIGN_EXTEND:
1457     case ISD::ZERO_EXTEND:
1458     case ISD::ANY_EXTEND:
1459       RV = PromoteExtend(SDValue(N, 0));
1460       break;
1461     case ISD::LOAD:
1462       if (PromoteLoad(SDValue(N, 0)))
1463         RV = SDValue(N, 0);
1464       break;
1465     }
1466   }
1467
1468   // If N is a commutative binary node, try commuting it to enable more
1469   // sdisel CSE.
1470   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1471       N->getNumValues() == 1) {
1472     SDValue N0 = N->getOperand(0);
1473     SDValue N1 = N->getOperand(1);
1474
1475     // Constant operands are canonicalized to RHS.
1476     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1477       SDValue Ops[] = {N1, N0};
1478       SDNode *CSENode;
1479       if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1480         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1481                                       &BinNode->Flags);
1482       } else {
1483         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1484       }
1485       if (CSENode)
1486         return SDValue(CSENode, 0);
1487     }
1488   }
1489
1490   return RV;
1491 }
1492
1493 /// Given a node, return its input chain if it has one, otherwise return a null
1494 /// sd operand.
1495 static SDValue getInputChainForNode(SDNode *N) {
1496   if (unsigned NumOps = N->getNumOperands()) {
1497     if (N->getOperand(0).getValueType() == MVT::Other)
1498       return N->getOperand(0);
1499     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1500       return N->getOperand(NumOps-1);
1501     for (unsigned i = 1; i < NumOps-1; ++i)
1502       if (N->getOperand(i).getValueType() == MVT::Other)
1503         return N->getOperand(i);
1504   }
1505   return SDValue();
1506 }
1507
1508 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1509   // If N has two operands, where one has an input chain equal to the other,
1510   // the 'other' chain is redundant.
1511   if (N->getNumOperands() == 2) {
1512     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1513       return N->getOperand(0);
1514     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1515       return N->getOperand(1);
1516   }
1517
1518   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1519   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1520   SmallPtrSet<SDNode*, 16> SeenOps;
1521   bool Changed = false;             // If we should replace this token factor.
1522
1523   // Start out with this token factor.
1524   TFs.push_back(N);
1525
1526   // Iterate through token factors.  The TFs grows when new token factors are
1527   // encountered.
1528   for (unsigned i = 0; i < TFs.size(); ++i) {
1529     SDNode *TF = TFs[i];
1530
1531     // Check each of the operands.
1532     for (const SDValue &Op : TF->op_values()) {
1533
1534       switch (Op.getOpcode()) {
1535       case ISD::EntryToken:
1536         // Entry tokens don't need to be added to the list. They are
1537         // redundant.
1538         Changed = true;
1539         break;
1540
1541       case ISD::TokenFactor:
1542         if (Op.hasOneUse() &&
1543             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1544           // Queue up for processing.
1545           TFs.push_back(Op.getNode());
1546           // Clean up in case the token factor is removed.
1547           AddToWorklist(Op.getNode());
1548           Changed = true;
1549           break;
1550         }
1551         // Fall thru
1552
1553       default:
1554         // Only add if it isn't already in the list.
1555         if (SeenOps.insert(Op.getNode()).second)
1556           Ops.push_back(Op);
1557         else
1558           Changed = true;
1559         break;
1560       }
1561     }
1562   }
1563
1564   SDValue Result;
1565
1566   // If we've changed things around then replace token factor.
1567   if (Changed) {
1568     if (Ops.empty()) {
1569       // The entry token is the only possible outcome.
1570       Result = DAG.getEntryNode();
1571     } else {
1572       // New and improved token factor.
1573       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1574     }
1575
1576     // Add users to worklist if AA is enabled, since it may introduce
1577     // a lot of new chained token factors while removing memory deps.
1578     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1579       : DAG.getSubtarget().useAA();
1580     return CombineTo(N, Result, UseAA /*add to worklist*/);
1581   }
1582
1583   return Result;
1584 }
1585
1586 /// MERGE_VALUES can always be eliminated.
1587 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1588   WorklistRemover DeadNodes(*this);
1589   // Replacing results may cause a different MERGE_VALUES to suddenly
1590   // be CSE'd with N, and carry its uses with it. Iterate until no
1591   // uses remain, to ensure that the node can be safely deleted.
1592   // First add the users of this node to the work list so that they
1593   // can be tried again once they have new operands.
1594   AddUsersToWorklist(N);
1595   do {
1596     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1597       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1598   } while (!N->use_empty());
1599   deleteAndRecombine(N);
1600   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1601 }
1602
1603 static bool isNullConstant(SDValue V) {
1604   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1605   return Const != nullptr && Const->isNullValue();
1606 }
1607
1608 static bool isNullFPConstant(SDValue V) {
1609   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1610   return Const != nullptr && Const->isZero() && !Const->isNegative();
1611 }
1612
1613 static bool isAllOnesConstant(SDValue V) {
1614   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1615   return Const != nullptr && Const->isAllOnesValue();
1616 }
1617
1618 static bool isOneConstant(SDValue V) {
1619   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1620   return Const != nullptr && Const->isOne();
1621 }
1622
1623 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1624 /// ContantSDNode pointer else nullptr.
1625 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1626   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1627   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1628 }
1629
1630 SDValue DAGCombiner::visitADD(SDNode *N) {
1631   SDValue N0 = N->getOperand(0);
1632   SDValue N1 = N->getOperand(1);
1633   EVT VT = N0.getValueType();
1634
1635   // fold vector ops
1636   if (VT.isVector()) {
1637     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1638       return FoldedVOp;
1639
1640     // fold (add x, 0) -> x, vector edition
1641     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1642       return N0;
1643     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1644       return N1;
1645   }
1646
1647   // fold (add x, undef) -> undef
1648   if (N0.getOpcode() == ISD::UNDEF)
1649     return N0;
1650   if (N1.getOpcode() == ISD::UNDEF)
1651     return N1;
1652   // fold (add c1, c2) -> c1+c2
1653   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1654   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1655   if (N0C && N1C)
1656     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1657   // canonicalize constant to RHS
1658   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1659      !isConstantIntBuildVectorOrConstantInt(N1))
1660     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1661   // fold (add x, 0) -> x
1662   if (isNullConstant(N1))
1663     return N0;
1664   // fold (add Sym, c) -> Sym+c
1665   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1666     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1667         GA->getOpcode() == ISD::GlobalAddress)
1668       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1669                                   GA->getOffset() +
1670                                     (uint64_t)N1C->getSExtValue());
1671   // fold ((c1-A)+c2) -> (c1+c2)-A
1672   if (N1C && N0.getOpcode() == ISD::SUB)
1673     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1674       SDLoc DL(N);
1675       return DAG.getNode(ISD::SUB, DL, VT,
1676                          DAG.getConstant(N1C->getAPIntValue()+
1677                                          N0C->getAPIntValue(), DL, VT),
1678                          N0.getOperand(1));
1679     }
1680   // reassociate add
1681   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1682     return RADD;
1683   // fold ((0-A) + B) -> B-A
1684   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1685     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1686   // fold (A + (0-B)) -> A-B
1687   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1688     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1689   // fold (A+(B-A)) -> B
1690   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1691     return N1.getOperand(0);
1692   // fold ((B-A)+A) -> B
1693   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1694     return N0.getOperand(0);
1695   // fold (A+(B-(A+C))) to (B-C)
1696   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1697       N0 == N1.getOperand(1).getOperand(0))
1698     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1699                        N1.getOperand(1).getOperand(1));
1700   // fold (A+(B-(C+A))) to (B-C)
1701   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1702       N0 == N1.getOperand(1).getOperand(1))
1703     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1704                        N1.getOperand(1).getOperand(0));
1705   // fold (A+((B-A)+or-C)) to (B+or-C)
1706   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1707       N1.getOperand(0).getOpcode() == ISD::SUB &&
1708       N0 == N1.getOperand(0).getOperand(1))
1709     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1710                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1711
1712   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1713   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1714     SDValue N00 = N0.getOperand(0);
1715     SDValue N01 = N0.getOperand(1);
1716     SDValue N10 = N1.getOperand(0);
1717     SDValue N11 = N1.getOperand(1);
1718
1719     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1720       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1721                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1722                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1723   }
1724
1725   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1726     return SDValue(N, 0);
1727
1728   // fold (a+b) -> (a|b) iff a and b share no bits.
1729   if (VT.isInteger() && !VT.isVector()) {
1730     APInt LHSZero, LHSOne;
1731     APInt RHSZero, RHSOne;
1732     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1733
1734     if (LHSZero.getBoolValue()) {
1735       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1736
1737       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1738       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1739       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1740         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1741           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1742       }
1743     }
1744   }
1745
1746   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1747   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1748       isNullConstant(N1.getOperand(0).getOperand(0)))
1749     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1750                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751                                    N1.getOperand(0).getOperand(1),
1752                                    N1.getOperand(1)));
1753   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1754       isNullConstant(N0.getOperand(0).getOperand(0)))
1755     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1756                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1757                                    N0.getOperand(0).getOperand(1),
1758                                    N0.getOperand(1)));
1759
1760   if (N1.getOpcode() == ISD::AND) {
1761     SDValue AndOp0 = N1.getOperand(0);
1762     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1763     unsigned DestBits = VT.getScalarType().getSizeInBits();
1764
1765     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1766     // and similar xforms where the inner op is either ~0 or 0.
1767     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1768       SDLoc DL(N);
1769       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1770     }
1771   }
1772
1773   // add (sext i1), X -> sub X, (zext i1)
1774   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1775       N0.getOperand(0).getValueType() == MVT::i1 &&
1776       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1777     SDLoc DL(N);
1778     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1779     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1780   }
1781
1782   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1783   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1784     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1785     if (TN->getVT() == MVT::i1) {
1786       SDLoc DL(N);
1787       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1788                                  DAG.getConstant(1, DL, VT));
1789       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1790     }
1791   }
1792
1793   return SDValue();
1794 }
1795
1796 SDValue DAGCombiner::visitADDC(SDNode *N) {
1797   SDValue N0 = N->getOperand(0);
1798   SDValue N1 = N->getOperand(1);
1799   EVT VT = N0.getValueType();
1800
1801   // If the flag result is dead, turn this into an ADD.
1802   if (!N->hasAnyUseOfValue(1))
1803     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1804                      DAG.getNode(ISD::CARRY_FALSE,
1805                                  SDLoc(N), MVT::Glue));
1806
1807   // canonicalize constant to RHS.
1808   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1809   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1810   if (N0C && !N1C)
1811     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1812
1813   // fold (addc x, 0) -> x + no carry out
1814   if (isNullConstant(N1))
1815     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1816                                         SDLoc(N), MVT::Glue));
1817
1818   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1819   APInt LHSZero, LHSOne;
1820   APInt RHSZero, RHSOne;
1821   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1822
1823   if (LHSZero.getBoolValue()) {
1824     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1825
1826     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1827     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1828     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1829       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1830                        DAG.getNode(ISD::CARRY_FALSE,
1831                                    SDLoc(N), MVT::Glue));
1832   }
1833
1834   return SDValue();
1835 }
1836
1837 SDValue DAGCombiner::visitADDE(SDNode *N) {
1838   SDValue N0 = N->getOperand(0);
1839   SDValue N1 = N->getOperand(1);
1840   SDValue CarryIn = N->getOperand(2);
1841
1842   // canonicalize constant to RHS
1843   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1844   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1845   if (N0C && !N1C)
1846     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1847                        N1, N0, CarryIn);
1848
1849   // fold (adde x, y, false) -> (addc x, y)
1850   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1851     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1852
1853   return SDValue();
1854 }
1855
1856 // Since it may not be valid to emit a fold to zero for vector initializers
1857 // check if we can before folding.
1858 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1859                              SelectionDAG &DAG,
1860                              bool LegalOperations, bool LegalTypes) {
1861   if (!VT.isVector())
1862     return DAG.getConstant(0, DL, VT);
1863   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1864     return DAG.getConstant(0, DL, VT);
1865   return SDValue();
1866 }
1867
1868 SDValue DAGCombiner::visitSUB(SDNode *N) {
1869   SDValue N0 = N->getOperand(0);
1870   SDValue N1 = N->getOperand(1);
1871   EVT VT = N0.getValueType();
1872
1873   // fold vector ops
1874   if (VT.isVector()) {
1875     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1876       return FoldedVOp;
1877
1878     // fold (sub x, 0) -> x, vector edition
1879     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1880       return N0;
1881   }
1882
1883   // fold (sub x, x) -> 0
1884   // FIXME: Refactor this and xor and other similar operations together.
1885   if (N0 == N1)
1886     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1887   // fold (sub c1, c2) -> c1-c2
1888   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1889   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1890   if (N0C && N1C)
1891     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1892   // fold (sub x, c) -> (add x, -c)
1893   if (N1C) {
1894     SDLoc DL(N);
1895     return DAG.getNode(ISD::ADD, DL, VT, N0,
1896                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1897   }
1898   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1899   if (isAllOnesConstant(N0))
1900     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1901   // fold A-(A-B) -> B
1902   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1903     return N1.getOperand(1);
1904   // fold (A+B)-A -> B
1905   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1906     return N0.getOperand(1);
1907   // fold (A+B)-B -> A
1908   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1909     return N0.getOperand(0);
1910   // fold C2-(A+C1) -> (C2-C1)-A
1911   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1912     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1913   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1914     SDLoc DL(N);
1915     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1916                                    DL, VT);
1917     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1918                        N1.getOperand(0));
1919   }
1920   // fold ((A+(B+or-C))-B) -> A+or-C
1921   if (N0.getOpcode() == ISD::ADD &&
1922       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1923        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1924       N0.getOperand(1).getOperand(0) == N1)
1925     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1926                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1927   // fold ((A+(C+B))-B) -> A+C
1928   if (N0.getOpcode() == ISD::ADD &&
1929       N0.getOperand(1).getOpcode() == ISD::ADD &&
1930       N0.getOperand(1).getOperand(1) == N1)
1931     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1932                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1933   // fold ((A-(B-C))-C) -> A-B
1934   if (N0.getOpcode() == ISD::SUB &&
1935       N0.getOperand(1).getOpcode() == ISD::SUB &&
1936       N0.getOperand(1).getOperand(1) == N1)
1937     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1938                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1939
1940   // If either operand of a sub is undef, the result is undef
1941   if (N0.getOpcode() == ISD::UNDEF)
1942     return N0;
1943   if (N1.getOpcode() == ISD::UNDEF)
1944     return N1;
1945
1946   // If the relocation model supports it, consider symbol offsets.
1947   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1948     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1949       // fold (sub Sym, c) -> Sym-c
1950       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1951         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1952                                     GA->getOffset() -
1953                                       (uint64_t)N1C->getSExtValue());
1954       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1955       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1956         if (GA->getGlobal() == GB->getGlobal())
1957           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1958                                  SDLoc(N), VT);
1959     }
1960
1961   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1962   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1963     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1964     if (TN->getVT() == MVT::i1) {
1965       SDLoc DL(N);
1966       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1967                                  DAG.getConstant(1, DL, VT));
1968       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1969     }
1970   }
1971
1972   return SDValue();
1973 }
1974
1975 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1976   SDValue N0 = N->getOperand(0);
1977   SDValue N1 = N->getOperand(1);
1978   EVT VT = N0.getValueType();
1979
1980   // If the flag result is dead, turn this into an SUB.
1981   if (!N->hasAnyUseOfValue(1))
1982     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1983                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1984                                  MVT::Glue));
1985
1986   // fold (subc x, x) -> 0 + no borrow
1987   if (N0 == N1) {
1988     SDLoc DL(N);
1989     return CombineTo(N, DAG.getConstant(0, DL, VT),
1990                      DAG.getNode(ISD::CARRY_FALSE, DL,
1991                                  MVT::Glue));
1992   }
1993
1994   // fold (subc x, 0) -> x + no borrow
1995   if (isNullConstant(N1))
1996     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1997                                         MVT::Glue));
1998
1999   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2000   if (isAllOnesConstant(N0))
2001     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2002                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2003                                  MVT::Glue));
2004
2005   return SDValue();
2006 }
2007
2008 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2009   SDValue N0 = N->getOperand(0);
2010   SDValue N1 = N->getOperand(1);
2011   SDValue CarryIn = N->getOperand(2);
2012
2013   // fold (sube x, y, false) -> (subc x, y)
2014   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2015     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2016
2017   return SDValue();
2018 }
2019
2020 SDValue DAGCombiner::visitMUL(SDNode *N) {
2021   SDValue N0 = N->getOperand(0);
2022   SDValue N1 = N->getOperand(1);
2023   EVT VT = N0.getValueType();
2024
2025   // fold (mul x, undef) -> 0
2026   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2027     return DAG.getConstant(0, SDLoc(N), VT);
2028
2029   bool N0IsConst = false;
2030   bool N1IsConst = false;
2031   bool N1IsOpaqueConst = false;
2032   bool N0IsOpaqueConst = false;
2033   APInt ConstValue0, ConstValue1;
2034   // fold vector ops
2035   if (VT.isVector()) {
2036     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2037       return FoldedVOp;
2038
2039     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2040     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2041   } else {
2042     N0IsConst = isa<ConstantSDNode>(N0);
2043     if (N0IsConst) {
2044       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2045       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2046     }
2047     N1IsConst = isa<ConstantSDNode>(N1);
2048     if (N1IsConst) {
2049       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2050       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2051     }
2052   }
2053
2054   // fold (mul c1, c2) -> c1*c2
2055   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2056     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2057                                       N0.getNode(), N1.getNode());
2058
2059   // canonicalize constant to RHS (vector doesn't have to splat)
2060   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2061      !isConstantIntBuildVectorOrConstantInt(N1))
2062     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2063   // fold (mul x, 0) -> 0
2064   if (N1IsConst && ConstValue1 == 0)
2065     return N1;
2066   // We require a splat of the entire scalar bit width for non-contiguous
2067   // bit patterns.
2068   bool IsFullSplat =
2069     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2070   // fold (mul x, 1) -> x
2071   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2072     return N0;
2073   // fold (mul x, -1) -> 0-x
2074   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2075     SDLoc DL(N);
2076     return DAG.getNode(ISD::SUB, DL, VT,
2077                        DAG.getConstant(0, DL, VT), N0);
2078   }
2079   // fold (mul x, (1 << c)) -> x << c
2080   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2081       IsFullSplat) {
2082     SDLoc DL(N);
2083     return DAG.getNode(ISD::SHL, DL, VT, N0,
2084                        DAG.getConstant(ConstValue1.logBase2(), DL,
2085                                        getShiftAmountTy(N0.getValueType())));
2086   }
2087   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2088   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2089       IsFullSplat) {
2090     unsigned Log2Val = (-ConstValue1).logBase2();
2091     SDLoc DL(N);
2092     // FIXME: If the input is something that is easily negated (e.g. a
2093     // single-use add), we should put the negate there.
2094     return DAG.getNode(ISD::SUB, DL, VT,
2095                        DAG.getConstant(0, DL, VT),
2096                        DAG.getNode(ISD::SHL, DL, VT, N0,
2097                             DAG.getConstant(Log2Val, DL,
2098                                       getShiftAmountTy(N0.getValueType()))));
2099   }
2100
2101   APInt Val;
2102   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2103   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2104       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2105                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2106     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2107                              N1, N0.getOperand(1));
2108     AddToWorklist(C3.getNode());
2109     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2110                        N0.getOperand(0), C3);
2111   }
2112
2113   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2114   // use.
2115   {
2116     SDValue Sh(nullptr,0), Y(nullptr,0);
2117     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2118     if (N0.getOpcode() == ISD::SHL &&
2119         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2120                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2121         N0.getNode()->hasOneUse()) {
2122       Sh = N0; Y = N1;
2123     } else if (N1.getOpcode() == ISD::SHL &&
2124                isa<ConstantSDNode>(N1.getOperand(1)) &&
2125                N1.getNode()->hasOneUse()) {
2126       Sh = N1; Y = N0;
2127     }
2128
2129     if (Sh.getNode()) {
2130       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2131                                 Sh.getOperand(0), Y);
2132       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2133                          Mul, Sh.getOperand(1));
2134     }
2135   }
2136
2137   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2138   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2139       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2140                      isa<ConstantSDNode>(N0.getOperand(1))))
2141     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2142                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2143                                    N0.getOperand(0), N1),
2144                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2145                                    N0.getOperand(1), N1));
2146
2147   // reassociate mul
2148   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2149     return RMUL;
2150
2151   return SDValue();
2152 }
2153
2154 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2155   SDValue N0 = N->getOperand(0);
2156   SDValue N1 = N->getOperand(1);
2157   EVT VT = N->getValueType(0);
2158
2159   // fold vector ops
2160   if (VT.isVector())
2161     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2162       return FoldedVOp;
2163
2164   // fold (sdiv c1, c2) -> c1/c2
2165   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2166   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2167   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2168     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2169   // fold (sdiv X, 1) -> X
2170   if (N1C && N1C->isOne())
2171     return N0;
2172   // fold (sdiv X, -1) -> 0-X
2173   if (N1C && N1C->isAllOnesValue()) {
2174     SDLoc DL(N);
2175     return DAG.getNode(ISD::SUB, DL, VT,
2176                        DAG.getConstant(0, DL, VT), N0);
2177   }
2178   // If we know the sign bits of both operands are zero, strength reduce to a
2179   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2180   if (!VT.isVector()) {
2181     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2182       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2183                          N0, N1);
2184   }
2185
2186   // fold (sdiv X, pow2) -> simple ops after legalize
2187   // FIXME: We check for the exact bit here because the generic lowering gives
2188   // better results in that case. The target-specific lowering should learn how
2189   // to handle exact sdivs efficiently.
2190   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2191       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2192       (N1C->getAPIntValue().isPowerOf2() ||
2193        (-N1C->getAPIntValue()).isPowerOf2())) {
2194     // Target-specific implementation of sdiv x, pow2.
2195     if (SDValue Res = BuildSDIVPow2(N))
2196       return Res;
2197
2198     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2199     SDLoc DL(N);
2200
2201     // Splat the sign bit into the register
2202     SDValue SGN =
2203         DAG.getNode(ISD::SRA, DL, VT, N0,
2204                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2205                                     getShiftAmountTy(N0.getValueType())));
2206     AddToWorklist(SGN.getNode());
2207
2208     // Add (N0 < 0) ? abs2 - 1 : 0;
2209     SDValue SRL =
2210         DAG.getNode(ISD::SRL, DL, VT, SGN,
2211                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2212                                     getShiftAmountTy(SGN.getValueType())));
2213     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2214     AddToWorklist(SRL.getNode());
2215     AddToWorklist(ADD.getNode());    // Divide by pow2
2216     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2217                   DAG.getConstant(lg2, DL,
2218                                   getShiftAmountTy(ADD.getValueType())));
2219
2220     // If we're dividing by a positive value, we're done.  Otherwise, we must
2221     // negate the result.
2222     if (N1C->getAPIntValue().isNonNegative())
2223       return SRA;
2224
2225     AddToWorklist(SRA.getNode());
2226     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2227   }
2228
2229   // If integer divide is expensive and we satisfy the requirements, emit an
2230   // alternate sequence.  Targets may check function attributes for size/speed
2231   // trade-offs.
2232   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2233   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2234     if (SDValue Op = BuildSDIV(N))
2235       return Op;
2236
2237   // undef / X -> 0
2238   if (N0.getOpcode() == ISD::UNDEF)
2239     return DAG.getConstant(0, SDLoc(N), VT);
2240   // X / undef -> undef
2241   if (N1.getOpcode() == ISD::UNDEF)
2242     return N1;
2243
2244   return SDValue();
2245 }
2246
2247 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2248   SDValue N0 = N->getOperand(0);
2249   SDValue N1 = N->getOperand(1);
2250   EVT VT = N->getValueType(0);
2251
2252   // fold vector ops
2253   if (VT.isVector())
2254     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2255       return FoldedVOp;
2256
2257   // fold (udiv c1, c2) -> c1/c2
2258   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2259   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2260   if (N0C && N1C)
2261     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2262                                                     N0C, N1C))
2263       return Folded;
2264   // fold (udiv x, (1 << c)) -> x >>u c
2265   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2266     SDLoc DL(N);
2267     return DAG.getNode(ISD::SRL, DL, VT, N0,
2268                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2269                                        getShiftAmountTy(N0.getValueType())));
2270   }
2271   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2272   if (N1.getOpcode() == ISD::SHL) {
2273     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2274       if (SHC->getAPIntValue().isPowerOf2()) {
2275         EVT ADDVT = N1.getOperand(1).getValueType();
2276         SDLoc DL(N);
2277         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2278                                   N1.getOperand(1),
2279                                   DAG.getConstant(SHC->getAPIntValue()
2280                                                                   .logBase2(),
2281                                                   DL, ADDVT));
2282         AddToWorklist(Add.getNode());
2283         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2284       }
2285     }
2286   }
2287
2288   // fold (udiv x, c) -> alternate
2289   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2290   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2291     if (SDValue Op = BuildUDIV(N))
2292       return Op;
2293
2294   // undef / X -> 0
2295   if (N0.getOpcode() == ISD::UNDEF)
2296     return DAG.getConstant(0, SDLoc(N), VT);
2297   // X / undef -> undef
2298   if (N1.getOpcode() == ISD::UNDEF)
2299     return N1;
2300
2301   return SDValue();
2302 }
2303
2304 SDValue DAGCombiner::visitSREM(SDNode *N) {
2305   SDValue N0 = N->getOperand(0);
2306   SDValue N1 = N->getOperand(1);
2307   EVT VT = N->getValueType(0);
2308
2309   // fold (srem c1, c2) -> c1%c2
2310   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2311   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2312   if (N0C && N1C)
2313     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2314                                                     N0C, N1C))
2315       return Folded;
2316   // If we know the sign bits of both operands are zero, strength reduce to a
2317   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2318   if (!VT.isVector()) {
2319     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2320       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2321   }
2322
2323   // If X/C can be simplified by the division-by-constant logic, lower
2324   // X%C to the equivalent of X-X/C*C.
2325   if (N1C && !N1C->isNullValue()) {
2326     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2327     AddToWorklist(Div.getNode());
2328     SDValue OptimizedDiv = combine(Div.getNode());
2329     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2330       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2331                                 OptimizedDiv, N1);
2332       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2333       AddToWorklist(Mul.getNode());
2334       return Sub;
2335     }
2336   }
2337
2338   // undef % X -> 0
2339   if (N0.getOpcode() == ISD::UNDEF)
2340     return DAG.getConstant(0, SDLoc(N), VT);
2341   // X % undef -> undef
2342   if (N1.getOpcode() == ISD::UNDEF)
2343     return N1;
2344
2345   return SDValue();
2346 }
2347
2348 SDValue DAGCombiner::visitUREM(SDNode *N) {
2349   SDValue N0 = N->getOperand(0);
2350   SDValue N1 = N->getOperand(1);
2351   EVT VT = N->getValueType(0);
2352
2353   // fold (urem c1, c2) -> c1%c2
2354   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2355   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2356   if (N0C && N1C)
2357     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2358                                                     N0C, N1C))
2359       return Folded;
2360   // fold (urem x, pow2) -> (and x, pow2-1)
2361   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2362       N1C->getAPIntValue().isPowerOf2()) {
2363     SDLoc DL(N);
2364     return DAG.getNode(ISD::AND, DL, VT, N0,
2365                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2366   }
2367   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2368   if (N1.getOpcode() == ISD::SHL) {
2369     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2370       if (SHC->getAPIntValue().isPowerOf2()) {
2371         SDLoc DL(N);
2372         SDValue Add =
2373           DAG.getNode(ISD::ADD, DL, VT, N1,
2374                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2375                                  VT));
2376         AddToWorklist(Add.getNode());
2377         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2378       }
2379     }
2380   }
2381
2382   // If X/C can be simplified by the division-by-constant logic, lower
2383   // X%C to the equivalent of X-X/C*C.
2384   if (N1C && !N1C->isNullValue()) {
2385     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2386     AddToWorklist(Div.getNode());
2387     SDValue OptimizedDiv = combine(Div.getNode());
2388     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2389       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2390                                 OptimizedDiv, N1);
2391       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2392       AddToWorklist(Mul.getNode());
2393       return Sub;
2394     }
2395   }
2396
2397   // undef % X -> 0
2398   if (N0.getOpcode() == ISD::UNDEF)
2399     return DAG.getConstant(0, SDLoc(N), VT);
2400   // X % undef -> undef
2401   if (N1.getOpcode() == ISD::UNDEF)
2402     return N1;
2403
2404   return SDValue();
2405 }
2406
2407 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2408   SDValue N0 = N->getOperand(0);
2409   SDValue N1 = N->getOperand(1);
2410   EVT VT = N->getValueType(0);
2411   SDLoc DL(N);
2412
2413   // fold (mulhs x, 0) -> 0
2414   if (isNullConstant(N1))
2415     return N1;
2416   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2417   if (isOneConstant(N1)) {
2418     SDLoc DL(N);
2419     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2420                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2421                                        DL,
2422                                        getShiftAmountTy(N0.getValueType())));
2423   }
2424   // fold (mulhs x, undef) -> 0
2425   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2426     return DAG.getConstant(0, SDLoc(N), VT);
2427
2428   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2429   // plus a shift.
2430   if (VT.isSimple() && !VT.isVector()) {
2431     MVT Simple = VT.getSimpleVT();
2432     unsigned SimpleSize = Simple.getSizeInBits();
2433     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2436       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2437       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2438       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2439             DAG.getConstant(SimpleSize, DL,
2440                             getShiftAmountTy(N1.getValueType())));
2441       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2442     }
2443   }
2444
2445   return SDValue();
2446 }
2447
2448 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2449   SDValue N0 = N->getOperand(0);
2450   SDValue N1 = N->getOperand(1);
2451   EVT VT = N->getValueType(0);
2452   SDLoc DL(N);
2453
2454   // fold (mulhu x, 0) -> 0
2455   if (isNullConstant(N1))
2456     return N1;
2457   // fold (mulhu x, 1) -> 0
2458   if (isOneConstant(N1))
2459     return DAG.getConstant(0, DL, N0.getValueType());
2460   // fold (mulhu x, undef) -> 0
2461   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2462     return DAG.getConstant(0, DL, VT);
2463
2464   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2465   // plus a shift.
2466   if (VT.isSimple() && !VT.isVector()) {
2467     MVT Simple = VT.getSimpleVT();
2468     unsigned SimpleSize = Simple.getSizeInBits();
2469     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2470     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2471       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2472       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2473       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2474       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2475             DAG.getConstant(SimpleSize, DL,
2476                             getShiftAmountTy(N1.getValueType())));
2477       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2478     }
2479   }
2480
2481   return SDValue();
2482 }
2483
2484 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2485 /// give the opcodes for the two computations that are being performed. Return
2486 /// true if a simplification was made.
2487 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2488                                                 unsigned HiOp) {
2489   // If the high half is not needed, just compute the low half.
2490   bool HiExists = N->hasAnyUseOfValue(1);
2491   if (!HiExists &&
2492       (!LegalOperations ||
2493        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2494     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2495     return CombineTo(N, Res, Res);
2496   }
2497
2498   // If the low half is not needed, just compute the high half.
2499   bool LoExists = N->hasAnyUseOfValue(0);
2500   if (!LoExists &&
2501       (!LegalOperations ||
2502        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2503     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2504     return CombineTo(N, Res, Res);
2505   }
2506
2507   // If both halves are used, return as it is.
2508   if (LoExists && HiExists)
2509     return SDValue();
2510
2511   // If the two computed results can be simplified separately, separate them.
2512   if (LoExists) {
2513     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2514     AddToWorklist(Lo.getNode());
2515     SDValue LoOpt = combine(Lo.getNode());
2516     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2517         (!LegalOperations ||
2518          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2519       return CombineTo(N, LoOpt, LoOpt);
2520   }
2521
2522   if (HiExists) {
2523     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2524     AddToWorklist(Hi.getNode());
2525     SDValue HiOpt = combine(Hi.getNode());
2526     if (HiOpt.getNode() && HiOpt != Hi &&
2527         (!LegalOperations ||
2528          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2529       return CombineTo(N, HiOpt, HiOpt);
2530   }
2531
2532   return SDValue();
2533 }
2534
2535 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2536   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2537     return Res;
2538
2539   EVT VT = N->getValueType(0);
2540   SDLoc DL(N);
2541
2542   // If the type is twice as wide is legal, transform the mulhu to a wider
2543   // multiply plus a shift.
2544   if (VT.isSimple() && !VT.isVector()) {
2545     MVT Simple = VT.getSimpleVT();
2546     unsigned SimpleSize = Simple.getSizeInBits();
2547     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2548     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2549       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2550       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2551       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2552       // Compute the high part as N1.
2553       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2554             DAG.getConstant(SimpleSize, DL,
2555                             getShiftAmountTy(Lo.getValueType())));
2556       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2557       // Compute the low part as N0.
2558       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2559       return CombineTo(N, Lo, Hi);
2560     }
2561   }
2562
2563   return SDValue();
2564 }
2565
2566 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2567   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2568     return Res;
2569
2570   EVT VT = N->getValueType(0);
2571   SDLoc DL(N);
2572
2573   // If the type is twice as wide is legal, transform the mulhu to a wider
2574   // multiply plus a shift.
2575   if (VT.isSimple() && !VT.isVector()) {
2576     MVT Simple = VT.getSimpleVT();
2577     unsigned SimpleSize = Simple.getSizeInBits();
2578     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2579     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2580       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2581       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2582       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2583       // Compute the high part as N1.
2584       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2585             DAG.getConstant(SimpleSize, DL,
2586                             getShiftAmountTy(Lo.getValueType())));
2587       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2588       // Compute the low part as N0.
2589       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2590       return CombineTo(N, Lo, Hi);
2591     }
2592   }
2593
2594   return SDValue();
2595 }
2596
2597 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2598   // (smulo x, 2) -> (saddo x, x)
2599   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2600     if (C2->getAPIntValue() == 2)
2601       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2602                          N->getOperand(0), N->getOperand(0));
2603
2604   return SDValue();
2605 }
2606
2607 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2608   // (umulo x, 2) -> (uaddo x, x)
2609   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2610     if (C2->getAPIntValue() == 2)
2611       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2612                          N->getOperand(0), N->getOperand(0));
2613
2614   return SDValue();
2615 }
2616
2617 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2618   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2619     return Res;
2620
2621   return SDValue();
2622 }
2623
2624 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2625   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2626     return Res;
2627
2628   return SDValue();
2629 }
2630
2631 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2632   SDValue N0 = N->getOperand(0);
2633   SDValue N1 = N->getOperand(1);
2634   EVT VT = N0.getValueType();
2635
2636   // fold vector ops
2637   if (VT.isVector())
2638     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2639       return FoldedVOp;
2640
2641   // fold (add c1, c2) -> c1+c2
2642   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2643   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2644   if (N0C && N1C)
2645     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2646
2647   // canonicalize constant to RHS
2648   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2649      !isConstantIntBuildVectorOrConstantInt(N1))
2650     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2651
2652   return SDValue();
2653 }
2654
2655 /// If this is a binary operator with two operands of the same opcode, try to
2656 /// simplify it.
2657 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2658   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2659   EVT VT = N0.getValueType();
2660   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2661
2662   // Bail early if none of these transforms apply.
2663   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2664
2665   // For each of OP in AND/OR/XOR:
2666   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2667   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2668   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2669   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2670   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2671   //
2672   // do not sink logical op inside of a vector extend, since it may combine
2673   // into a vsetcc.
2674   EVT Op0VT = N0.getOperand(0).getValueType();
2675   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2676        N0.getOpcode() == ISD::SIGN_EXTEND ||
2677        N0.getOpcode() == ISD::BSWAP ||
2678        // Avoid infinite looping with PromoteIntBinOp.
2679        (N0.getOpcode() == ISD::ANY_EXTEND &&
2680         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2681        (N0.getOpcode() == ISD::TRUNCATE &&
2682         (!TLI.isZExtFree(VT, Op0VT) ||
2683          !TLI.isTruncateFree(Op0VT, VT)) &&
2684         TLI.isTypeLegal(Op0VT))) &&
2685       !VT.isVector() &&
2686       Op0VT == N1.getOperand(0).getValueType() &&
2687       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2688     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2689                                  N0.getOperand(0).getValueType(),
2690                                  N0.getOperand(0), N1.getOperand(0));
2691     AddToWorklist(ORNode.getNode());
2692     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2693   }
2694
2695   // For each of OP in SHL/SRL/SRA/AND...
2696   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2697   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2698   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2699   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2700        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2701       N0.getOperand(1) == N1.getOperand(1)) {
2702     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2703                                  N0.getOperand(0).getValueType(),
2704                                  N0.getOperand(0), N1.getOperand(0));
2705     AddToWorklist(ORNode.getNode());
2706     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2707                        ORNode, N0.getOperand(1));
2708   }
2709
2710   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2711   // Only perform this optimization after type legalization and before
2712   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2713   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2714   // we don't want to undo this promotion.
2715   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2716   // on scalars.
2717   if ((N0.getOpcode() == ISD::BITCAST ||
2718        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2719       Level == AfterLegalizeTypes) {
2720     SDValue In0 = N0.getOperand(0);
2721     SDValue In1 = N1.getOperand(0);
2722     EVT In0Ty = In0.getValueType();
2723     EVT In1Ty = In1.getValueType();
2724     SDLoc DL(N);
2725     // If both incoming values are integers, and the original types are the
2726     // same.
2727     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2728       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2729       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2730       AddToWorklist(Op.getNode());
2731       return BC;
2732     }
2733   }
2734
2735   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2736   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2737   // If both shuffles use the same mask, and both shuffle within a single
2738   // vector, then it is worthwhile to move the swizzle after the operation.
2739   // The type-legalizer generates this pattern when loading illegal
2740   // vector types from memory. In many cases this allows additional shuffle
2741   // optimizations.
2742   // There are other cases where moving the shuffle after the xor/and/or
2743   // is profitable even if shuffles don't perform a swizzle.
2744   // If both shuffles use the same mask, and both shuffles have the same first
2745   // or second operand, then it might still be profitable to move the shuffle
2746   // after the xor/and/or operation.
2747   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2748     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2749     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2750
2751     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2752            "Inputs to shuffles are not the same type");
2753
2754     // Check that both shuffles use the same mask. The masks are known to be of
2755     // the same length because the result vector type is the same.
2756     // Check also that shuffles have only one use to avoid introducing extra
2757     // instructions.
2758     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2759         SVN0->getMask().equals(SVN1->getMask())) {
2760       SDValue ShOp = N0->getOperand(1);
2761
2762       // Don't try to fold this node if it requires introducing a
2763       // build vector of all zeros that might be illegal at this stage.
2764       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2765         if (!LegalTypes)
2766           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2767         else
2768           ShOp = SDValue();
2769       }
2770
2771       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2772       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2773       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2774       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2775         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2776                                       N0->getOperand(0), N1->getOperand(0));
2777         AddToWorklist(NewNode.getNode());
2778         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2779                                     &SVN0->getMask()[0]);
2780       }
2781
2782       // Don't try to fold this node if it requires introducing a
2783       // build vector of all zeros that might be illegal at this stage.
2784       ShOp = N0->getOperand(0);
2785       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2786         if (!LegalTypes)
2787           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2788         else
2789           ShOp = SDValue();
2790       }
2791
2792       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2793       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2794       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2795       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2796         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2797                                       N0->getOperand(1), N1->getOperand(1));
2798         AddToWorklist(NewNode.getNode());
2799         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2800                                     &SVN0->getMask()[0]);
2801       }
2802     }
2803   }
2804
2805   return SDValue();
2806 }
2807
2808 /// This contains all DAGCombine rules which reduce two values combined by
2809 /// an And operation to a single value. This makes them reusable in the context
2810 /// of visitSELECT(). Rules involving constants are not included as
2811 /// visitSELECT() already handles those cases.
2812 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2813                                   SDNode *LocReference) {
2814   EVT VT = N1.getValueType();
2815
2816   // fold (and x, undef) -> 0
2817   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2818     return DAG.getConstant(0, SDLoc(LocReference), VT);
2819   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2820   SDValue LL, LR, RL, RR, CC0, CC1;
2821   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2822     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2823     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2824
2825     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2826         LL.getValueType().isInteger()) {
2827       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2828       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2829         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2830                                      LR.getValueType(), LL, RL);
2831         AddToWorklist(ORNode.getNode());
2832         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2833       }
2834       if (isAllOnesConstant(LR)) {
2835         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2836         if (Op1 == ISD::SETEQ) {
2837           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2838                                         LR.getValueType(), LL, RL);
2839           AddToWorklist(ANDNode.getNode());
2840           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2841         }
2842         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2843         if (Op1 == ISD::SETGT) {
2844           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2845                                        LR.getValueType(), LL, RL);
2846           AddToWorklist(ORNode.getNode());
2847           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2848         }
2849       }
2850     }
2851     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2852     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2853         Op0 == Op1 && LL.getValueType().isInteger() &&
2854       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2855                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2856       SDLoc DL(N0);
2857       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2858                                     LL, DAG.getConstant(1, DL,
2859                                                         LL.getValueType()));
2860       AddToWorklist(ADDNode.getNode());
2861       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2862                           DAG.getConstant(2, DL, LL.getValueType()),
2863                           ISD::SETUGE);
2864     }
2865     // canonicalize equivalent to ll == rl
2866     if (LL == RR && LR == RL) {
2867       Op1 = ISD::getSetCCSwappedOperands(Op1);
2868       std::swap(RL, RR);
2869     }
2870     if (LL == RL && LR == RR) {
2871       bool isInteger = LL.getValueType().isInteger();
2872       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2873       if (Result != ISD::SETCC_INVALID &&
2874           (!LegalOperations ||
2875            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2876             TLI.isOperationLegal(ISD::SETCC,
2877                             getSetCCResultType(N0.getSimpleValueType())))))
2878         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2879                             LL, LR, Result);
2880     }
2881   }
2882
2883   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2884       VT.getSizeInBits() <= 64) {
2885     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2886       APInt ADDC = ADDI->getAPIntValue();
2887       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2888         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2889         // immediate for an add, but it is legal if its top c2 bits are set,
2890         // transform the ADD so the immediate doesn't need to be materialized
2891         // in a register.
2892         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2893           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2894                                              SRLI->getZExtValue());
2895           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2896             ADDC |= Mask;
2897             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2898               SDLoc DL(N0);
2899               SDValue NewAdd =
2900                 DAG.getNode(ISD::ADD, DL, VT,
2901                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2902               CombineTo(N0.getNode(), NewAdd);
2903               // Return N so it doesn't get rechecked!
2904               return SDValue(LocReference, 0);
2905             }
2906           }
2907         }
2908       }
2909     }
2910   }
2911
2912   return SDValue();
2913 }
2914
2915 SDValue DAGCombiner::visitAND(SDNode *N) {
2916   SDValue N0 = N->getOperand(0);
2917   SDValue N1 = N->getOperand(1);
2918   EVT VT = N1.getValueType();
2919
2920   // fold vector ops
2921   if (VT.isVector()) {
2922     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2923       return FoldedVOp;
2924
2925     // fold (and x, 0) -> 0, vector edition
2926     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2927       // do not return N0, because undef node may exist in N0
2928       return DAG.getConstant(
2929           APInt::getNullValue(
2930               N0.getValueType().getScalarType().getSizeInBits()),
2931           SDLoc(N), N0.getValueType());
2932     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2933       // do not return N1, because undef node may exist in N1
2934       return DAG.getConstant(
2935           APInt::getNullValue(
2936               N1.getValueType().getScalarType().getSizeInBits()),
2937           SDLoc(N), N1.getValueType());
2938
2939     // fold (and x, -1) -> x, vector edition
2940     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2941       return N1;
2942     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2943       return N0;
2944   }
2945
2946   // fold (and c1, c2) -> c1&c2
2947   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2948   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2949   if (N0C && N1C && !N1C->isOpaque())
2950     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2951   // canonicalize constant to RHS
2952   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2953      !isConstantIntBuildVectorOrConstantInt(N1))
2954     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2955   // fold (and x, -1) -> x
2956   if (isAllOnesConstant(N1))
2957     return N0;
2958   // if (and x, c) is known to be zero, return 0
2959   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2960   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2961                                    APInt::getAllOnesValue(BitWidth)))
2962     return DAG.getConstant(0, SDLoc(N), VT);
2963   // reassociate and
2964   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2965     return RAND;
2966   // fold (and (or x, C), D) -> D if (C & D) == D
2967   if (N1C && N0.getOpcode() == ISD::OR)
2968     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2969       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2970         return N1;
2971   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2972   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2973     SDValue N0Op0 = N0.getOperand(0);
2974     APInt Mask = ~N1C->getAPIntValue();
2975     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2976     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2977       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2978                                  N0.getValueType(), N0Op0);
2979
2980       // Replace uses of the AND with uses of the Zero extend node.
2981       CombineTo(N, Zext);
2982
2983       // We actually want to replace all uses of the any_extend with the
2984       // zero_extend, to avoid duplicating things.  This will later cause this
2985       // AND to be folded.
2986       CombineTo(N0.getNode(), Zext);
2987       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2988     }
2989   }
2990   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2991   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2992   // already be zero by virtue of the width of the base type of the load.
2993   //
2994   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2995   // more cases.
2996   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2997        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2998       N0.getOpcode() == ISD::LOAD) {
2999     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3000                                          N0 : N0.getOperand(0) );
3001
3002     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3003     // This can be a pure constant or a vector splat, in which case we treat the
3004     // vector as a scalar and use the splat value.
3005     APInt Constant = APInt::getNullValue(1);
3006     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3007       Constant = C->getAPIntValue();
3008     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3009       APInt SplatValue, SplatUndef;
3010       unsigned SplatBitSize;
3011       bool HasAnyUndefs;
3012       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3013                                              SplatBitSize, HasAnyUndefs);
3014       if (IsSplat) {
3015         // Undef bits can contribute to a possible optimisation if set, so
3016         // set them.
3017         SplatValue |= SplatUndef;
3018
3019         // The splat value may be something like "0x00FFFFFF", which means 0 for
3020         // the first vector value and FF for the rest, repeating. We need a mask
3021         // that will apply equally to all members of the vector, so AND all the
3022         // lanes of the constant together.
3023         EVT VT = Vector->getValueType(0);
3024         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3025
3026         // If the splat value has been compressed to a bitlength lower
3027         // than the size of the vector lane, we need to re-expand it to
3028         // the lane size.
3029         if (BitWidth > SplatBitSize)
3030           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3031                SplatBitSize < BitWidth;
3032                SplatBitSize = SplatBitSize * 2)
3033             SplatValue |= SplatValue.shl(SplatBitSize);
3034
3035         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3036         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3037         if (SplatBitSize % BitWidth == 0) {
3038           Constant = APInt::getAllOnesValue(BitWidth);
3039           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3040             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3041         }
3042       }
3043     }
3044
3045     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3046     // actually legal and isn't going to get expanded, else this is a false
3047     // optimisation.
3048     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3049                                                     Load->getValueType(0),
3050                                                     Load->getMemoryVT());
3051
3052     // Resize the constant to the same size as the original memory access before
3053     // extension. If it is still the AllOnesValue then this AND is completely
3054     // unneeded.
3055     Constant =
3056       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3057
3058     bool B;
3059     switch (Load->getExtensionType()) {
3060     default: B = false; break;
3061     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3062     case ISD::ZEXTLOAD:
3063     case ISD::NON_EXTLOAD: B = true; break;
3064     }
3065
3066     if (B && Constant.isAllOnesValue()) {
3067       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3068       // preserve semantics once we get rid of the AND.
3069       SDValue NewLoad(Load, 0);
3070       if (Load->getExtensionType() == ISD::EXTLOAD) {
3071         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3072                               Load->getValueType(0), SDLoc(Load),
3073                               Load->getChain(), Load->getBasePtr(),
3074                               Load->getOffset(), Load->getMemoryVT(),
3075                               Load->getMemOperand());
3076         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3077         if (Load->getNumValues() == 3) {
3078           // PRE/POST_INC loads have 3 values.
3079           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3080                            NewLoad.getValue(2) };
3081           CombineTo(Load, To, 3, true);
3082         } else {
3083           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3084         }
3085       }
3086
3087       // Fold the AND away, taking care not to fold to the old load node if we
3088       // replaced it.
3089       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3090
3091       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3092     }
3093   }
3094
3095   // fold (and (load x), 255) -> (zextload x, i8)
3096   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3097   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3098   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3099               (N0.getOpcode() == ISD::ANY_EXTEND &&
3100                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3101     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3102     LoadSDNode *LN0 = HasAnyExt
3103       ? cast<LoadSDNode>(N0.getOperand(0))
3104       : cast<LoadSDNode>(N0);
3105     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3106         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3107       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3108       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3109         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3110         EVT LoadedVT = LN0->getMemoryVT();
3111         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3112
3113         if (ExtVT == LoadedVT &&
3114             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3115                                                     ExtVT))) {
3116
3117           SDValue NewLoad =
3118             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3119                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3120                            LN0->getMemOperand());
3121           AddToWorklist(N);
3122           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3123           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3124         }
3125
3126         // Do not change the width of a volatile load.
3127         // Do not generate loads of non-round integer types since these can
3128         // be expensive (and would be wrong if the type is not byte sized).
3129         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3130             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3131                                                     ExtVT))) {
3132           EVT PtrType = LN0->getOperand(1).getValueType();
3133
3134           unsigned Alignment = LN0->getAlignment();
3135           SDValue NewPtr = LN0->getBasePtr();
3136
3137           // For big endian targets, we need to add an offset to the pointer
3138           // to load the correct bytes.  For little endian systems, we merely
3139           // need to read fewer bytes from the same pointer.
3140           if (DAG.getDataLayout().isBigEndian()) {
3141             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3142             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3143             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3144             SDLoc DL(LN0);
3145             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3146                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3147             Alignment = MinAlign(Alignment, PtrOff);
3148           }
3149
3150           AddToWorklist(NewPtr.getNode());
3151
3152           SDValue Load =
3153             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3154                            LN0->getChain(), NewPtr,
3155                            LN0->getPointerInfo(),
3156                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3157                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3158           AddToWorklist(N);
3159           CombineTo(LN0, Load, Load.getValue(1));
3160           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3161         }
3162       }
3163     }
3164   }
3165
3166   if (SDValue Combined = visitANDLike(N0, N1, N))
3167     return Combined;
3168
3169   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3170   if (N0.getOpcode() == N1.getOpcode())
3171     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3172       return Tmp;
3173
3174   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3175   // fold (and (sra)) -> (and (srl)) when possible.
3176   if (!VT.isVector() &&
3177       SimplifyDemandedBits(SDValue(N, 0)))
3178     return SDValue(N, 0);
3179
3180   // fold (zext_inreg (extload x)) -> (zextload x)
3181   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3182     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3183     EVT MemVT = LN0->getMemoryVT();
3184     // If we zero all the possible extended bits, then we can turn this into
3185     // a zextload if we are running before legalize or the operation is legal.
3186     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3187     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3188                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3189         ((!LegalOperations && !LN0->isVolatile()) ||
3190          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3191       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3192                                        LN0->getChain(), LN0->getBasePtr(),
3193                                        MemVT, LN0->getMemOperand());
3194       AddToWorklist(N);
3195       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3196       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3197     }
3198   }
3199   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3200   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3201       N0.hasOneUse()) {
3202     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3203     EVT MemVT = LN0->getMemoryVT();
3204     // If we zero all the possible extended bits, then we can turn this into
3205     // a zextload if we are running before legalize or the operation is legal.
3206     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3207     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3208                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3209         ((!LegalOperations && !LN0->isVolatile()) ||
3210          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3211       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3212                                        LN0->getChain(), LN0->getBasePtr(),
3213                                        MemVT, LN0->getMemOperand());
3214       AddToWorklist(N);
3215       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3216       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3217     }
3218   }
3219   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3220   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3221     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3222                                        N0.getOperand(1), false);
3223     if (BSwap.getNode())
3224       return BSwap;
3225   }
3226
3227   return SDValue();
3228 }
3229
3230 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3231 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3232                                         bool DemandHighBits) {
3233   if (!LegalOperations)
3234     return SDValue();
3235
3236   EVT VT = N->getValueType(0);
3237   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3238     return SDValue();
3239   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3240     return SDValue();
3241
3242   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3243   bool LookPassAnd0 = false;
3244   bool LookPassAnd1 = false;
3245   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3246       std::swap(N0, N1);
3247   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3248       std::swap(N0, N1);
3249   if (N0.getOpcode() == ISD::AND) {
3250     if (!N0.getNode()->hasOneUse())
3251       return SDValue();
3252     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3253     if (!N01C || N01C->getZExtValue() != 0xFF00)
3254       return SDValue();
3255     N0 = N0.getOperand(0);
3256     LookPassAnd0 = true;
3257   }
3258
3259   if (N1.getOpcode() == ISD::AND) {
3260     if (!N1.getNode()->hasOneUse())
3261       return SDValue();
3262     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3263     if (!N11C || N11C->getZExtValue() != 0xFF)
3264       return SDValue();
3265     N1 = N1.getOperand(0);
3266     LookPassAnd1 = true;
3267   }
3268
3269   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3270     std::swap(N0, N1);
3271   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3272     return SDValue();
3273   if (!N0.getNode()->hasOneUse() ||
3274       !N1.getNode()->hasOneUse())
3275     return SDValue();
3276
3277   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3278   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3279   if (!N01C || !N11C)
3280     return SDValue();
3281   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3282     return SDValue();
3283
3284   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3285   SDValue N00 = N0->getOperand(0);
3286   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3287     if (!N00.getNode()->hasOneUse())
3288       return SDValue();
3289     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3290     if (!N001C || N001C->getZExtValue() != 0xFF)
3291       return SDValue();
3292     N00 = N00.getOperand(0);
3293     LookPassAnd0 = true;
3294   }
3295
3296   SDValue N10 = N1->getOperand(0);
3297   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3298     if (!N10.getNode()->hasOneUse())
3299       return SDValue();
3300     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3301     if (!N101C || N101C->getZExtValue() != 0xFF00)
3302       return SDValue();
3303     N10 = N10.getOperand(0);
3304     LookPassAnd1 = true;
3305   }
3306
3307   if (N00 != N10)
3308     return SDValue();
3309
3310   // Make sure everything beyond the low halfword gets set to zero since the SRL
3311   // 16 will clear the top bits.
3312   unsigned OpSizeInBits = VT.getSizeInBits();
3313   if (DemandHighBits && OpSizeInBits > 16) {
3314     // If the left-shift isn't masked out then the only way this is a bswap is
3315     // if all bits beyond the low 8 are 0. In that case the entire pattern
3316     // reduces to a left shift anyway: leave it for other parts of the combiner.
3317     if (!LookPassAnd0)
3318       return SDValue();
3319
3320     // However, if the right shift isn't masked out then it might be because
3321     // it's not needed. See if we can spot that too.
3322     if (!LookPassAnd1 &&
3323         !DAG.MaskedValueIsZero(
3324             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3325       return SDValue();
3326   }
3327
3328   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3329   if (OpSizeInBits > 16) {
3330     SDLoc DL(N);
3331     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3332                       DAG.getConstant(OpSizeInBits - 16, DL,
3333                                       getShiftAmountTy(VT)));
3334   }
3335   return Res;
3336 }
3337
3338 /// Return true if the specified node is an element that makes up a 32-bit
3339 /// packed halfword byteswap.
3340 /// ((x & 0x000000ff) << 8) |
3341 /// ((x & 0x0000ff00) >> 8) |
3342 /// ((x & 0x00ff0000) << 8) |
3343 /// ((x & 0xff000000) >> 8)
3344 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3345   if (!N.getNode()->hasOneUse())
3346     return false;
3347
3348   unsigned Opc = N.getOpcode();
3349   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3350     return false;
3351
3352   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3353   if (!N1C)
3354     return false;
3355
3356   unsigned Num;
3357   switch (N1C->getZExtValue()) {
3358   default:
3359     return false;
3360   case 0xFF:       Num = 0; break;
3361   case 0xFF00:     Num = 1; break;
3362   case 0xFF0000:   Num = 2; break;
3363   case 0xFF000000: Num = 3; break;
3364   }
3365
3366   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3367   SDValue N0 = N.getOperand(0);
3368   if (Opc == ISD::AND) {
3369     if (Num == 0 || Num == 2) {
3370       // (x >> 8) & 0xff
3371       // (x >> 8) & 0xff0000
3372       if (N0.getOpcode() != ISD::SRL)
3373         return false;
3374       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3375       if (!C || C->getZExtValue() != 8)
3376         return false;
3377     } else {
3378       // (x << 8) & 0xff00
3379       // (x << 8) & 0xff000000
3380       if (N0.getOpcode() != ISD::SHL)
3381         return false;
3382       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3383       if (!C || C->getZExtValue() != 8)
3384         return false;
3385     }
3386   } else if (Opc == ISD::SHL) {
3387     // (x & 0xff) << 8
3388     // (x & 0xff0000) << 8
3389     if (Num != 0 && Num != 2)
3390       return false;
3391     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3392     if (!C || C->getZExtValue() != 8)
3393       return false;
3394   } else { // Opc == ISD::SRL
3395     // (x & 0xff00) >> 8
3396     // (x & 0xff000000) >> 8
3397     if (Num != 1 && Num != 3)
3398       return false;
3399     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3400     if (!C || C->getZExtValue() != 8)
3401       return false;
3402   }
3403
3404   if (Parts[Num])
3405     return false;
3406
3407   Parts[Num] = N0.getOperand(0).getNode();
3408   return true;
3409 }
3410
3411 /// Match a 32-bit packed halfword bswap. That is
3412 /// ((x & 0x000000ff) << 8) |
3413 /// ((x & 0x0000ff00) >> 8) |
3414 /// ((x & 0x00ff0000) << 8) |
3415 /// ((x & 0xff000000) >> 8)
3416 /// => (rotl (bswap x), 16)
3417 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3418   if (!LegalOperations)
3419     return SDValue();
3420
3421   EVT VT = N->getValueType(0);
3422   if (VT != MVT::i32)
3423     return SDValue();
3424   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3425     return SDValue();
3426
3427   // Look for either
3428   // (or (or (and), (and)), (or (and), (and)))
3429   // (or (or (or (and), (and)), (and)), (and))
3430   if (N0.getOpcode() != ISD::OR)
3431     return SDValue();
3432   SDValue N00 = N0.getOperand(0);
3433   SDValue N01 = N0.getOperand(1);
3434   SDNode *Parts[4] = {};
3435
3436   if (N1.getOpcode() == ISD::OR &&
3437       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3438     // (or (or (and), (and)), (or (and), (and)))
3439     SDValue N000 = N00.getOperand(0);
3440     if (!isBSwapHWordElement(N000, Parts))
3441       return SDValue();
3442
3443     SDValue N001 = N00.getOperand(1);
3444     if (!isBSwapHWordElement(N001, Parts))
3445       return SDValue();
3446     SDValue N010 = N01.getOperand(0);
3447     if (!isBSwapHWordElement(N010, Parts))
3448       return SDValue();
3449     SDValue N011 = N01.getOperand(1);
3450     if (!isBSwapHWordElement(N011, Parts))
3451       return SDValue();
3452   } else {
3453     // (or (or (or (and), (and)), (and)), (and))
3454     if (!isBSwapHWordElement(N1, Parts))
3455       return SDValue();
3456     if (!isBSwapHWordElement(N01, Parts))
3457       return SDValue();
3458     if (N00.getOpcode() != ISD::OR)
3459       return SDValue();
3460     SDValue N000 = N00.getOperand(0);
3461     if (!isBSwapHWordElement(N000, Parts))
3462       return SDValue();
3463     SDValue N001 = N00.getOperand(1);
3464     if (!isBSwapHWordElement(N001, Parts))
3465       return SDValue();
3466   }
3467
3468   // Make sure the parts are all coming from the same node.
3469   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3470     return SDValue();
3471
3472   SDLoc DL(N);
3473   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3474                               SDValue(Parts[0], 0));
3475
3476   // Result of the bswap should be rotated by 16. If it's not legal, then
3477   // do  (x << 16) | (x >> 16).
3478   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3479   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3480     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3481   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3482     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3483   return DAG.getNode(ISD::OR, DL, VT,
3484                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3485                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3486 }
3487
3488 /// This contains all DAGCombine rules which reduce two values combined by
3489 /// an Or operation to a single value \see visitANDLike().
3490 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3491   EVT VT = N1.getValueType();
3492   // fold (or x, undef) -> -1
3493   if (!LegalOperations &&
3494       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3495     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3496     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3497                            SDLoc(LocReference), VT);
3498   }
3499   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3500   SDValue LL, LR, RL, RR, CC0, CC1;
3501   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3502     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3503     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3504
3505     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3506       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3507       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3508       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3509         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3510                                      LR.getValueType(), LL, RL);
3511         AddToWorklist(ORNode.getNode());
3512         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3513       }
3514       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3515       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3516       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3517         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3518                                       LR.getValueType(), LL, RL);
3519         AddToWorklist(ANDNode.getNode());
3520         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3521       }
3522     }
3523     // canonicalize equivalent to ll == rl
3524     if (LL == RR && LR == RL) {
3525       Op1 = ISD::getSetCCSwappedOperands(Op1);
3526       std::swap(RL, RR);
3527     }
3528     if (LL == RL && LR == RR) {
3529       bool isInteger = LL.getValueType().isInteger();
3530       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3531       if (Result != ISD::SETCC_INVALID &&
3532           (!LegalOperations ||
3533            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3534             TLI.isOperationLegal(ISD::SETCC,
3535               getSetCCResultType(N0.getValueType())))))
3536         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3537                             LL, LR, Result);
3538     }
3539   }
3540
3541   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3542   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3543       // Don't increase # computations.
3544       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3545     // We can only do this xform if we know that bits from X that are set in C2
3546     // but not in C1 are already zero.  Likewise for Y.
3547     if (const ConstantSDNode *N0O1C =
3548         getAsNonOpaqueConstant(N0.getOperand(1))) {
3549       if (const ConstantSDNode *N1O1C =
3550           getAsNonOpaqueConstant(N1.getOperand(1))) {
3551         // We can only do this xform if we know that bits from X that are set in
3552         // C2 but not in C1 are already zero.  Likewise for Y.
3553         const APInt &LHSMask = N0O1C->getAPIntValue();
3554         const APInt &RHSMask = N1O1C->getAPIntValue();
3555
3556         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3557             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3558           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3559                                   N0.getOperand(0), N1.getOperand(0));
3560           SDLoc DL(LocReference);
3561           return DAG.getNode(ISD::AND, DL, VT, X,
3562                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3563         }
3564       }
3565     }
3566   }
3567
3568   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3569   if (N0.getOpcode() == ISD::AND &&
3570       N1.getOpcode() == ISD::AND &&
3571       N0.getOperand(0) == N1.getOperand(0) &&
3572       // Don't increase # computations.
3573       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3574     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3575                             N0.getOperand(1), N1.getOperand(1));
3576     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3577   }
3578
3579   return SDValue();
3580 }
3581
3582 SDValue DAGCombiner::visitOR(SDNode *N) {
3583   SDValue N0 = N->getOperand(0);
3584   SDValue N1 = N->getOperand(1);
3585   EVT VT = N1.getValueType();
3586
3587   // fold vector ops
3588   if (VT.isVector()) {
3589     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3590       return FoldedVOp;
3591
3592     // fold (or x, 0) -> x, vector edition
3593     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3594       return N1;
3595     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3596       return N0;
3597
3598     // fold (or x, -1) -> -1, vector edition
3599     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3600       // do not return N0, because undef node may exist in N0
3601       return DAG.getConstant(
3602           APInt::getAllOnesValue(
3603               N0.getValueType().getScalarType().getSizeInBits()),
3604           SDLoc(N), N0.getValueType());
3605     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3606       // do not return N1, because undef node may exist in N1
3607       return DAG.getConstant(
3608           APInt::getAllOnesValue(
3609               N1.getValueType().getScalarType().getSizeInBits()),
3610           SDLoc(N), N1.getValueType());
3611
3612     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3613     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3614     // Do this only if the resulting shuffle is legal.
3615     if (isa<ShuffleVectorSDNode>(N0) &&
3616         isa<ShuffleVectorSDNode>(N1) &&
3617         // Avoid folding a node with illegal type.
3618         TLI.isTypeLegal(VT) &&
3619         N0->getOperand(1) == N1->getOperand(1) &&
3620         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3621       bool CanFold = true;
3622       unsigned NumElts = VT.getVectorNumElements();
3623       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3624       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3625       // We construct two shuffle masks:
3626       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3627       // and N1 as the second operand.
3628       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3629       // and N0 as the second operand.
3630       // We do this because OR is commutable and therefore there might be
3631       // two ways to fold this node into a shuffle.
3632       SmallVector<int,4> Mask1;
3633       SmallVector<int,4> Mask2;
3634
3635       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3636         int M0 = SV0->getMaskElt(i);
3637         int M1 = SV1->getMaskElt(i);
3638
3639         // Both shuffle indexes are undef. Propagate Undef.
3640         if (M0 < 0 && M1 < 0) {
3641           Mask1.push_back(M0);
3642           Mask2.push_back(M0);
3643           continue;
3644         }
3645
3646         if (M0 < 0 || M1 < 0 ||
3647             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3648             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3649           CanFold = false;
3650           break;
3651         }
3652
3653         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3654         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3655       }
3656
3657       if (CanFold) {
3658         // Fold this sequence only if the resulting shuffle is 'legal'.
3659         if (TLI.isShuffleMaskLegal(Mask1, VT))
3660           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3661                                       N1->getOperand(0), &Mask1[0]);
3662         if (TLI.isShuffleMaskLegal(Mask2, VT))
3663           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3664                                       N0->getOperand(0), &Mask2[0]);
3665       }
3666     }
3667   }
3668
3669   // fold (or c1, c2) -> c1|c2
3670   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3671   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3672   if (N0C && N1C && !N1C->isOpaque())
3673     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3674   // canonicalize constant to RHS
3675   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3676      !isConstantIntBuildVectorOrConstantInt(N1))
3677     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3678   // fold (or x, 0) -> x
3679   if (isNullConstant(N1))
3680     return N0;
3681   // fold (or x, -1) -> -1
3682   if (isAllOnesConstant(N1))
3683     return N1;
3684   // fold (or x, c) -> c iff (x & ~c) == 0
3685   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3686     return N1;
3687
3688   if (SDValue Combined = visitORLike(N0, N1, N))
3689     return Combined;
3690
3691   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3692   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3693     return BSwap;
3694   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3695     return BSwap;
3696
3697   // reassociate or
3698   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3699     return ROR;
3700   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3701   // iff (c1 & c2) == 0.
3702   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3703              isa<ConstantSDNode>(N0.getOperand(1))) {
3704     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3705     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3706       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3707                                                    N1C, C1))
3708         return DAG.getNode(
3709             ISD::AND, SDLoc(N), VT,
3710             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3711       return SDValue();
3712     }
3713   }
3714   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3715   if (N0.getOpcode() == N1.getOpcode())
3716     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3717       return Tmp;
3718
3719   // See if this is some rotate idiom.
3720   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3721     return SDValue(Rot, 0);
3722
3723   // Simplify the operands using demanded-bits information.
3724   if (!VT.isVector() &&
3725       SimplifyDemandedBits(SDValue(N, 0)))
3726     return SDValue(N, 0);
3727
3728   return SDValue();
3729 }
3730
3731 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3732 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3733   if (Op.getOpcode() == ISD::AND) {
3734     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3735       Mask = Op.getOperand(1);
3736       Op = Op.getOperand(0);
3737     } else {
3738       return false;
3739     }
3740   }
3741
3742   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3743     Shift = Op;
3744     return true;
3745   }
3746
3747   return false;
3748 }
3749
3750 // Return true if we can prove that, whenever Neg and Pos are both in the
3751 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3752 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3753 //
3754 //     (or (shift1 X, Neg), (shift2 X, Pos))
3755 //
3756 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3757 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3758 // to consider shift amounts with defined behavior.
3759 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3760   // If OpSize is a power of 2 then:
3761   //
3762   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3763   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3764   //
3765   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3766   // for the stronger condition:
3767   //
3768   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3769   //
3770   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3771   // we can just replace Neg with Neg' for the rest of the function.
3772   //
3773   // In other cases we check for the even stronger condition:
3774   //
3775   //     Neg == OpSize - Pos                                    [B]
3776   //
3777   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3778   // behavior if Pos == 0 (and consequently Neg == OpSize).
3779   //
3780   // We could actually use [A] whenever OpSize is a power of 2, but the
3781   // only extra cases that it would match are those uninteresting ones
3782   // where Neg and Pos are never in range at the same time.  E.g. for
3783   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3784   // as well as (sub 32, Pos), but:
3785   //
3786   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3787   //
3788   // always invokes undefined behavior for 32-bit X.
3789   //
3790   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3791   unsigned MaskLoBits = 0;
3792   if (Neg.getOpcode() == ISD::AND &&
3793       isPowerOf2_64(OpSize) &&
3794       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3795       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3796     Neg = Neg.getOperand(0);
3797     MaskLoBits = Log2_64(OpSize);
3798   }
3799
3800   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3801   if (Neg.getOpcode() != ISD::SUB)
3802     return 0;
3803   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3804   if (!NegC)
3805     return 0;
3806   SDValue NegOp1 = Neg.getOperand(1);
3807
3808   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3809   // Pos'.  The truncation is redundant for the purpose of the equality.
3810   if (MaskLoBits &&
3811       Pos.getOpcode() == ISD::AND &&
3812       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3813       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3814     Pos = Pos.getOperand(0);
3815
3816   // The condition we need is now:
3817   //
3818   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3819   //
3820   // If NegOp1 == Pos then we need:
3821   //
3822   //              OpSize & Mask == NegC & Mask
3823   //
3824   // (because "x & Mask" is a truncation and distributes through subtraction).
3825   APInt Width;
3826   if (Pos == NegOp1)
3827     Width = NegC->getAPIntValue();
3828   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3829   // Then the condition we want to prove becomes:
3830   //
3831   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3832   //
3833   // which, again because "x & Mask" is a truncation, becomes:
3834   //
3835   //                NegC & Mask == (OpSize - PosC) & Mask
3836   //              OpSize & Mask == (NegC + PosC) & Mask
3837   else if (Pos.getOpcode() == ISD::ADD &&
3838            Pos.getOperand(0) == NegOp1 &&
3839            Pos.getOperand(1).getOpcode() == ISD::Constant)
3840     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3841              NegC->getAPIntValue());
3842   else
3843     return false;
3844
3845   // Now we just need to check that OpSize & Mask == Width & Mask.
3846   if (MaskLoBits)
3847     // Opsize & Mask is 0 since Mask is Opsize - 1.
3848     return Width.getLoBits(MaskLoBits) == 0;
3849   return Width == OpSize;
3850 }
3851
3852 // A subroutine of MatchRotate used once we have found an OR of two opposite
3853 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3854 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3855 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3856 // Neg with outer conversions stripped away.
3857 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3858                                        SDValue Neg, SDValue InnerPos,
3859                                        SDValue InnerNeg, unsigned PosOpcode,
3860                                        unsigned NegOpcode, SDLoc DL) {
3861   // fold (or (shl x, (*ext y)),
3862   //          (srl x, (*ext (sub 32, y)))) ->
3863   //   (rotl x, y) or (rotr x, (sub 32, y))
3864   //
3865   // fold (or (shl x, (*ext (sub 32, y))),
3866   //          (srl x, (*ext y))) ->
3867   //   (rotr x, y) or (rotl x, (sub 32, y))
3868   EVT VT = Shifted.getValueType();
3869   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3870     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3871     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3872                        HasPos ? Pos : Neg).getNode();
3873   }
3874
3875   return nullptr;
3876 }
3877
3878 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3879 // idioms for rotate, and if the target supports rotation instructions, generate
3880 // a rot[lr].
3881 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3882   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3883   EVT VT = LHS.getValueType();
3884   if (!TLI.isTypeLegal(VT)) return nullptr;
3885
3886   // The target must have at least one rotate flavor.
3887   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3888   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3889   if (!HasROTL && !HasROTR) return nullptr;
3890
3891   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3892   SDValue LHSShift;   // The shift.
3893   SDValue LHSMask;    // AND value if any.
3894   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3895     return nullptr; // Not part of a rotate.
3896
3897   SDValue RHSShift;   // The shift.
3898   SDValue RHSMask;    // AND value if any.
3899   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3900     return nullptr; // Not part of a rotate.
3901
3902   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3903     return nullptr;   // Not shifting the same value.
3904
3905   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3906     return nullptr;   // Shifts must disagree.
3907
3908   // Canonicalize shl to left side in a shl/srl pair.
3909   if (RHSShift.getOpcode() == ISD::SHL) {
3910     std::swap(LHS, RHS);
3911     std::swap(LHSShift, RHSShift);
3912     std::swap(LHSMask , RHSMask );
3913   }
3914
3915   unsigned OpSizeInBits = VT.getSizeInBits();
3916   SDValue LHSShiftArg = LHSShift.getOperand(0);
3917   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3918   SDValue RHSShiftArg = RHSShift.getOperand(0);
3919   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3920
3921   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3922   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3923   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3924       RHSShiftAmt.getOpcode() == ISD::Constant) {
3925     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3926     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3927     if ((LShVal + RShVal) != OpSizeInBits)
3928       return nullptr;
3929
3930     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3931                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3932
3933     // If there is an AND of either shifted operand, apply it to the result.
3934     if (LHSMask.getNode() || RHSMask.getNode()) {
3935       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3936
3937       if (LHSMask.getNode()) {
3938         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3939         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3940       }
3941       if (RHSMask.getNode()) {
3942         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3943         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3944       }
3945
3946       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3947     }
3948
3949     return Rot.getNode();
3950   }
3951
3952   // If there is a mask here, and we have a variable shift, we can't be sure
3953   // that we're masking out the right stuff.
3954   if (LHSMask.getNode() || RHSMask.getNode())
3955     return nullptr;
3956
3957   // If the shift amount is sign/zext/any-extended just peel it off.
3958   SDValue LExtOp0 = LHSShiftAmt;
3959   SDValue RExtOp0 = RHSShiftAmt;
3960   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3961        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3962        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3963        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3964       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3965        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3966        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3967        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3968     LExtOp0 = LHSShiftAmt.getOperand(0);
3969     RExtOp0 = RHSShiftAmt.getOperand(0);
3970   }
3971
3972   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3973                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3974   if (TryL)
3975     return TryL;
3976
3977   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3978                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3979   if (TryR)
3980     return TryR;
3981
3982   return nullptr;
3983 }
3984
3985 SDValue DAGCombiner::visitXOR(SDNode *N) {
3986   SDValue N0 = N->getOperand(0);
3987   SDValue N1 = N->getOperand(1);
3988   EVT VT = N0.getValueType();
3989
3990   // fold vector ops
3991   if (VT.isVector()) {
3992     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3993       return FoldedVOp;
3994
3995     // fold (xor x, 0) -> x, vector edition
3996     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3997       return N1;
3998     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3999       return N0;
4000   }
4001
4002   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4003   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4004     return DAG.getConstant(0, SDLoc(N), VT);
4005   // fold (xor x, undef) -> undef
4006   if (N0.getOpcode() == ISD::UNDEF)
4007     return N0;
4008   if (N1.getOpcode() == ISD::UNDEF)
4009     return N1;
4010   // fold (xor c1, c2) -> c1^c2
4011   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4012   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4013   if (N0C && N1C)
4014     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4015   // canonicalize constant to RHS
4016   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4017      !isConstantIntBuildVectorOrConstantInt(N1))
4018     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4019   // fold (xor x, 0) -> x
4020   if (isNullConstant(N1))
4021     return N0;
4022   // reassociate xor
4023   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4024     return RXOR;
4025
4026   // fold !(x cc y) -> (x !cc y)
4027   SDValue LHS, RHS, CC;
4028   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4029     bool isInt = LHS.getValueType().isInteger();
4030     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4031                                                isInt);
4032
4033     if (!LegalOperations ||
4034         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4035       switch (N0.getOpcode()) {
4036       default:
4037         llvm_unreachable("Unhandled SetCC Equivalent!");
4038       case ISD::SETCC:
4039         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4040       case ISD::SELECT_CC:
4041         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4042                                N0.getOperand(3), NotCC);
4043       }
4044     }
4045   }
4046
4047   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4048   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4049       N0.getNode()->hasOneUse() &&
4050       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4051     SDValue V = N0.getOperand(0);
4052     SDLoc DL(N0);
4053     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4054                     DAG.getConstant(1, DL, V.getValueType()));
4055     AddToWorklist(V.getNode());
4056     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4057   }
4058
4059   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4060   if (isOneConstant(N1) && VT == MVT::i1 &&
4061       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4062     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4063     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4064       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4065       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4066       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4067       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4068       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4069     }
4070   }
4071   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4072   if (isAllOnesConstant(N1) &&
4073       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4074     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4075     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4076       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4077       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4078       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4079       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4080       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4081     }
4082   }
4083   // fold (xor (and x, y), y) -> (and (not x), y)
4084   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4085       N0->getOperand(1) == N1) {
4086     SDValue X = N0->getOperand(0);
4087     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4088     AddToWorklist(NotX.getNode());
4089     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4090   }
4091   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4092   if (N1C && N0.getOpcode() == ISD::XOR) {
4093     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4094       SDLoc DL(N);
4095       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4096                          DAG.getConstant(N1C->getAPIntValue() ^
4097                                          N00C->getAPIntValue(), DL, VT));
4098     }
4099     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4100       SDLoc DL(N);
4101       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4102                          DAG.getConstant(N1C->getAPIntValue() ^
4103                                          N01C->getAPIntValue(), DL, VT));
4104     }
4105   }
4106   // fold (xor x, x) -> 0
4107   if (N0 == N1)
4108     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4109
4110   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4111   // Here is a concrete example of this equivalence:
4112   // i16   x ==  14
4113   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4114   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4115   //
4116   // =>
4117   //
4118   // i16     ~1      == 0b1111111111111110
4119   // i16 rol(~1, 14) == 0b1011111111111111
4120   //
4121   // Some additional tips to help conceptualize this transform:
4122   // - Try to see the operation as placing a single zero in a value of all ones.
4123   // - There exists no value for x which would allow the result to contain zero.
4124   // - Values of x larger than the bitwidth are undefined and do not require a
4125   //   consistent result.
4126   // - Pushing the zero left requires shifting one bits in from the right.
4127   // A rotate left of ~1 is a nice way of achieving the desired result.
4128   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4129       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4130     SDLoc DL(N);
4131     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4132                        N0.getOperand(1));
4133   }
4134
4135   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4136   if (N0.getOpcode() == N1.getOpcode())
4137     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4138       return Tmp;
4139
4140   // Simplify the expression using non-local knowledge.
4141   if (!VT.isVector() &&
4142       SimplifyDemandedBits(SDValue(N, 0)))
4143     return SDValue(N, 0);
4144
4145   return SDValue();
4146 }
4147
4148 /// Handle transforms common to the three shifts, when the shift amount is a
4149 /// constant.
4150 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4151   SDNode *LHS = N->getOperand(0).getNode();
4152   if (!LHS->hasOneUse()) return SDValue();
4153
4154   // We want to pull some binops through shifts, so that we have (and (shift))
4155   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4156   // thing happens with address calculations, so it's important to canonicalize
4157   // it.
4158   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4159
4160   switch (LHS->getOpcode()) {
4161   default: return SDValue();
4162   case ISD::OR:
4163   case ISD::XOR:
4164     HighBitSet = false; // We can only transform sra if the high bit is clear.
4165     break;
4166   case ISD::AND:
4167     HighBitSet = true;  // We can only transform sra if the high bit is set.
4168     break;
4169   case ISD::ADD:
4170     if (N->getOpcode() != ISD::SHL)
4171       return SDValue(); // only shl(add) not sr[al](add).
4172     HighBitSet = false; // We can only transform sra if the high bit is clear.
4173     break;
4174   }
4175
4176   // We require the RHS of the binop to be a constant and not opaque as well.
4177   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4178   if (!BinOpCst) return SDValue();
4179
4180   // FIXME: disable this unless the input to the binop is a shift by a constant.
4181   // If it is not a shift, it pessimizes some common cases like:
4182   //
4183   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4184   //    int bar(int *X, int i) { return X[i & 255]; }
4185   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4186   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4187        BinOpLHSVal->getOpcode() != ISD::SRA &&
4188        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4189       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4190     return SDValue();
4191
4192   EVT VT = N->getValueType(0);
4193
4194   // If this is a signed shift right, and the high bit is modified by the
4195   // logical operation, do not perform the transformation. The highBitSet
4196   // boolean indicates the value of the high bit of the constant which would
4197   // cause it to be modified for this operation.
4198   if (N->getOpcode() == ISD::SRA) {
4199     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4200     if (BinOpRHSSignSet != HighBitSet)
4201       return SDValue();
4202   }
4203
4204   if (!TLI.isDesirableToCommuteWithShift(LHS))
4205     return SDValue();
4206
4207   // Fold the constants, shifting the binop RHS by the shift amount.
4208   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4209                                N->getValueType(0),
4210                                LHS->getOperand(1), N->getOperand(1));
4211   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4212
4213   // Create the new shift.
4214   SDValue NewShift = DAG.getNode(N->getOpcode(),
4215                                  SDLoc(LHS->getOperand(0)),
4216                                  VT, LHS->getOperand(0), N->getOperand(1));
4217
4218   // Create the new binop.
4219   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4220 }
4221
4222 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4223   assert(N->getOpcode() == ISD::TRUNCATE);
4224   assert(N->getOperand(0).getOpcode() == ISD::AND);
4225
4226   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4227   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4228     SDValue N01 = N->getOperand(0).getOperand(1);
4229
4230     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4231       if (!N01C->isOpaque()) {
4232         EVT TruncVT = N->getValueType(0);
4233         SDValue N00 = N->getOperand(0).getOperand(0);
4234         APInt TruncC = N01C->getAPIntValue();
4235         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4236         SDLoc DL(N);
4237
4238         return DAG.getNode(ISD::AND, DL, TruncVT,
4239                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4240                            DAG.getConstant(TruncC, DL, TruncVT));
4241       }
4242     }
4243   }
4244
4245   return SDValue();
4246 }
4247
4248 SDValue DAGCombiner::visitRotate(SDNode *N) {
4249   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4250   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4251       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4252     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4253     if (NewOp1.getNode())
4254       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4255                          N->getOperand(0), NewOp1);
4256   }
4257   return SDValue();
4258 }
4259
4260 SDValue DAGCombiner::visitSHL(SDNode *N) {
4261   SDValue N0 = N->getOperand(0);
4262   SDValue N1 = N->getOperand(1);
4263   EVT VT = N0.getValueType();
4264   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4265
4266   // fold vector ops
4267   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4268   if (VT.isVector()) {
4269     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4270       return FoldedVOp;
4271
4272     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4273     // If setcc produces all-one true value then:
4274     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4275     if (N1CV && N1CV->isConstant()) {
4276       if (N0.getOpcode() == ISD::AND) {
4277         SDValue N00 = N0->getOperand(0);
4278         SDValue N01 = N0->getOperand(1);
4279         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4280
4281         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4282             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4283                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4284           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4285                                                      N01CV, N1CV))
4286             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4287         }
4288       } else {
4289         N1C = isConstOrConstSplat(N1);
4290       }
4291     }
4292   }
4293
4294   // fold (shl c1, c2) -> c1<<c2
4295   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4296   if (N0C && N1C && !N1C->isOpaque())
4297     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4298   // fold (shl 0, x) -> 0
4299   if (isNullConstant(N0))
4300     return N0;
4301   // fold (shl x, c >= size(x)) -> undef
4302   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4303     return DAG.getUNDEF(VT);
4304   // fold (shl x, 0) -> x
4305   if (N1C && N1C->isNullValue())
4306     return N0;
4307   // fold (shl undef, x) -> 0
4308   if (N0.getOpcode() == ISD::UNDEF)
4309     return DAG.getConstant(0, SDLoc(N), VT);
4310   // if (shl x, c) is known to be zero, return 0
4311   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4312                             APInt::getAllOnesValue(OpSizeInBits)))
4313     return DAG.getConstant(0, SDLoc(N), VT);
4314   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4315   if (N1.getOpcode() == ISD::TRUNCATE &&
4316       N1.getOperand(0).getOpcode() == ISD::AND) {
4317     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4318     if (NewOp1.getNode())
4319       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4320   }
4321
4322   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4323     return SDValue(N, 0);
4324
4325   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4326   if (N1C && N0.getOpcode() == ISD::SHL) {
4327     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4328       uint64_t c1 = N0C1->getZExtValue();
4329       uint64_t c2 = N1C->getZExtValue();
4330       SDLoc DL(N);
4331       if (c1 + c2 >= OpSizeInBits)
4332         return DAG.getConstant(0, DL, VT);
4333       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4334                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4335     }
4336   }
4337
4338   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4339   // For this to be valid, the second form must not preserve any of the bits
4340   // that are shifted out by the inner shift in the first form.  This means
4341   // the outer shift size must be >= the number of bits added by the ext.
4342   // As a corollary, we don't care what kind of ext it is.
4343   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4344               N0.getOpcode() == ISD::ANY_EXTEND ||
4345               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4346       N0.getOperand(0).getOpcode() == ISD::SHL) {
4347     SDValue N0Op0 = N0.getOperand(0);
4348     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4349       uint64_t c1 = N0Op0C1->getZExtValue();
4350       uint64_t c2 = N1C->getZExtValue();
4351       EVT InnerShiftVT = N0Op0.getValueType();
4352       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4353       if (c2 >= OpSizeInBits - InnerShiftSize) {
4354         SDLoc DL(N0);
4355         if (c1 + c2 >= OpSizeInBits)
4356           return DAG.getConstant(0, DL, VT);
4357         return DAG.getNode(ISD::SHL, DL, VT,
4358                            DAG.getNode(N0.getOpcode(), DL, VT,
4359                                        N0Op0->getOperand(0)),
4360                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4361       }
4362     }
4363   }
4364
4365   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4366   // Only fold this if the inner zext has no other uses to avoid increasing
4367   // the total number of instructions.
4368   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4369       N0.getOperand(0).getOpcode() == ISD::SRL) {
4370     SDValue N0Op0 = N0.getOperand(0);
4371     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4372       uint64_t c1 = N0Op0C1->getZExtValue();
4373       if (c1 < VT.getScalarSizeInBits()) {
4374         uint64_t c2 = N1C->getZExtValue();
4375         if (c1 == c2) {
4376           SDValue NewOp0 = N0.getOperand(0);
4377           EVT CountVT = NewOp0.getOperand(1).getValueType();
4378           SDLoc DL(N);
4379           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4380                                        NewOp0,
4381                                        DAG.getConstant(c2, DL, CountVT));
4382           AddToWorklist(NewSHL.getNode());
4383           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4384         }
4385       }
4386     }
4387   }
4388
4389   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4390   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4391   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4392       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4393     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4394       uint64_t C1 = N0C1->getZExtValue();
4395       uint64_t C2 = N1C->getZExtValue();
4396       SDLoc DL(N);
4397       if (C1 <= C2)
4398         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4400       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4401                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4402     }
4403   }
4404
4405   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4406   //                               (and (srl x, (sub c1, c2), MASK)
4407   // Only fold this if the inner shift has no other uses -- if it does, folding
4408   // this will increase the total number of instructions.
4409   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4410     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4411       uint64_t c1 = N0C1->getZExtValue();
4412       if (c1 < OpSizeInBits) {
4413         uint64_t c2 = N1C->getZExtValue();
4414         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4415         SDValue Shift;
4416         if (c2 > c1) {
4417           Mask = Mask.shl(c2 - c1);
4418           SDLoc DL(N);
4419           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4420                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4421         } else {
4422           Mask = Mask.lshr(c1 - c2);
4423           SDLoc DL(N);
4424           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4425                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4426         }
4427         SDLoc DL(N0);
4428         return DAG.getNode(ISD::AND, DL, VT, Shift,
4429                            DAG.getConstant(Mask, DL, VT));
4430       }
4431     }
4432   }
4433   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4434   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4435     unsigned BitSize = VT.getScalarSizeInBits();
4436     SDLoc DL(N);
4437     SDValue HiBitsMask =
4438       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4439                                             BitSize - N1C->getZExtValue()),
4440                       DL, VT);
4441     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4442                        HiBitsMask);
4443   }
4444
4445   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4446   // Variant of version done on multiply, except mul by a power of 2 is turned
4447   // into a shift.
4448   APInt Val;
4449   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4450       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4451        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4452     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4453     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4454     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4455   }
4456
4457   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4458   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4459     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4460       if (SDValue Folded =
4461               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4462         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4463     }
4464   }
4465
4466   if (N1C && !N1C->isOpaque())
4467     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4468       return NewSHL;
4469
4470   return SDValue();
4471 }
4472
4473 SDValue DAGCombiner::visitSRA(SDNode *N) {
4474   SDValue N0 = N->getOperand(0);
4475   SDValue N1 = N->getOperand(1);
4476   EVT VT = N0.getValueType();
4477   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4478
4479   // fold vector ops
4480   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4481   if (VT.isVector()) {
4482     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4483       return FoldedVOp;
4484
4485     N1C = isConstOrConstSplat(N1);
4486   }
4487
4488   // fold (sra c1, c2) -> (sra c1, c2)
4489   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4490   if (N0C && N1C && !N1C->isOpaque())
4491     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4492   // fold (sra 0, x) -> 0
4493   if (isNullConstant(N0))
4494     return N0;
4495   // fold (sra -1, x) -> -1
4496   if (isAllOnesConstant(N0))
4497     return N0;
4498   // fold (sra x, (setge c, size(x))) -> undef
4499   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4500     return DAG.getUNDEF(VT);
4501   // fold (sra x, 0) -> x
4502   if (N1C && N1C->isNullValue())
4503     return N0;
4504   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4505   // sext_inreg.
4506   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4507     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4508     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4509     if (VT.isVector())
4510       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4511                                ExtVT, VT.getVectorNumElements());
4512     if ((!LegalOperations ||
4513          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4514       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4515                          N0.getOperand(0), DAG.getValueType(ExtVT));
4516   }
4517
4518   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4519   if (N1C && N0.getOpcode() == ISD::SRA) {
4520     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4521       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4522       if (Sum >= OpSizeInBits)
4523         Sum = OpSizeInBits - 1;
4524       SDLoc DL(N);
4525       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4526                          DAG.getConstant(Sum, DL, N1.getValueType()));
4527     }
4528   }
4529
4530   // fold (sra (shl X, m), (sub result_size, n))
4531   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4532   // result_size - n != m.
4533   // If truncate is free for the target sext(shl) is likely to result in better
4534   // code.
4535   if (N0.getOpcode() == ISD::SHL && N1C) {
4536     // Get the two constanst of the shifts, CN0 = m, CN = n.
4537     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4538     if (N01C) {
4539       LLVMContext &Ctx = *DAG.getContext();
4540       // Determine what the truncate's result bitsize and type would be.
4541       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4542
4543       if (VT.isVector())
4544         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4545
4546       // Determine the residual right-shift amount.
4547       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4548
4549       // If the shift is not a no-op (in which case this should be just a sign
4550       // extend already), the truncated to type is legal, sign_extend is legal
4551       // on that type, and the truncate to that type is both legal and free,
4552       // perform the transform.
4553       if ((ShiftAmt > 0) &&
4554           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4555           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4556           TLI.isTruncateFree(VT, TruncVT)) {
4557
4558         SDLoc DL(N);
4559         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4560             getShiftAmountTy(N0.getOperand(0).getValueType()));
4561         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4562                                     N0.getOperand(0), Amt);
4563         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4564                                     Shift);
4565         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4566                            N->getValueType(0), Trunc);
4567       }
4568     }
4569   }
4570
4571   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4572   if (N1.getOpcode() == ISD::TRUNCATE &&
4573       N1.getOperand(0).getOpcode() == ISD::AND) {
4574     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4575     if (NewOp1.getNode())
4576       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4577   }
4578
4579   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4580   //      if c1 is equal to the number of bits the trunc removes
4581   if (N0.getOpcode() == ISD::TRUNCATE &&
4582       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4583        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4584       N0.getOperand(0).hasOneUse() &&
4585       N0.getOperand(0).getOperand(1).hasOneUse() &&
4586       N1C) {
4587     SDValue N0Op0 = N0.getOperand(0);
4588     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4589       unsigned LargeShiftVal = LargeShift->getZExtValue();
4590       EVT LargeVT = N0Op0.getValueType();
4591
4592       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4593         SDLoc DL(N);
4594         SDValue Amt =
4595           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4596                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4597         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4598                                   N0Op0.getOperand(0), Amt);
4599         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4600       }
4601     }
4602   }
4603
4604   // Simplify, based on bits shifted out of the LHS.
4605   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4606     return SDValue(N, 0);
4607
4608
4609   // If the sign bit is known to be zero, switch this to a SRL.
4610   if (DAG.SignBitIsZero(N0))
4611     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4612
4613   if (N1C && !N1C->isOpaque())
4614     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4615       return NewSRA;
4616
4617   return SDValue();
4618 }
4619
4620 SDValue DAGCombiner::visitSRL(SDNode *N) {
4621   SDValue N0 = N->getOperand(0);
4622   SDValue N1 = N->getOperand(1);
4623   EVT VT = N0.getValueType();
4624   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4625
4626   // fold vector ops
4627   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4628   if (VT.isVector()) {
4629     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4630       return FoldedVOp;
4631
4632     N1C = isConstOrConstSplat(N1);
4633   }
4634
4635   // fold (srl c1, c2) -> c1 >>u c2
4636   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4637   if (N0C && N1C && !N1C->isOpaque())
4638     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4639   // fold (srl 0, x) -> 0
4640   if (isNullConstant(N0))
4641     return N0;
4642   // fold (srl x, c >= size(x)) -> undef
4643   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4644     return DAG.getUNDEF(VT);
4645   // fold (srl x, 0) -> x
4646   if (N1C && N1C->isNullValue())
4647     return N0;
4648   // if (srl x, c) is known to be zero, return 0
4649   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4650                                    APInt::getAllOnesValue(OpSizeInBits)))
4651     return DAG.getConstant(0, SDLoc(N), VT);
4652
4653   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4654   if (N1C && N0.getOpcode() == ISD::SRL) {
4655     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4656       uint64_t c1 = N01C->getZExtValue();
4657       uint64_t c2 = N1C->getZExtValue();
4658       SDLoc DL(N);
4659       if (c1 + c2 >= OpSizeInBits)
4660         return DAG.getConstant(0, DL, VT);
4661       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4662                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4663     }
4664   }
4665
4666   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4667   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4668       N0.getOperand(0).getOpcode() == ISD::SRL &&
4669       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4670     uint64_t c1 =
4671       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4672     uint64_t c2 = N1C->getZExtValue();
4673     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4674     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4675     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4676     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4677     if (c1 + OpSizeInBits == InnerShiftSize) {
4678       SDLoc DL(N0);
4679       if (c1 + c2 >= InnerShiftSize)
4680         return DAG.getConstant(0, DL, VT);
4681       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4682                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4683                                      N0.getOperand(0)->getOperand(0),
4684                                      DAG.getConstant(c1 + c2, DL,
4685                                                      ShiftCountVT)));
4686     }
4687   }
4688
4689   // fold (srl (shl x, c), c) -> (and x, cst2)
4690   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4691     unsigned BitSize = N0.getScalarValueSizeInBits();
4692     if (BitSize <= 64) {
4693       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4694       SDLoc DL(N);
4695       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4696                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4697     }
4698   }
4699
4700   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4701   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4702     // Shifting in all undef bits?
4703     EVT SmallVT = N0.getOperand(0).getValueType();
4704     unsigned BitSize = SmallVT.getScalarSizeInBits();
4705     if (N1C->getZExtValue() >= BitSize)
4706       return DAG.getUNDEF(VT);
4707
4708     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4709       uint64_t ShiftAmt = N1C->getZExtValue();
4710       SDLoc DL0(N0);
4711       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4712                                        N0.getOperand(0),
4713                           DAG.getConstant(ShiftAmt, DL0,
4714                                           getShiftAmountTy(SmallVT)));
4715       AddToWorklist(SmallShift.getNode());
4716       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4717       SDLoc DL(N);
4718       return DAG.getNode(ISD::AND, DL, VT,
4719                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4720                          DAG.getConstant(Mask, DL, VT));
4721     }
4722   }
4723
4724   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4725   // bit, which is unmodified by sra.
4726   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4727     if (N0.getOpcode() == ISD::SRA)
4728       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4729   }
4730
4731   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4732   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4733       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4734     APInt KnownZero, KnownOne;
4735     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4736
4737     // If any of the input bits are KnownOne, then the input couldn't be all
4738     // zeros, thus the result of the srl will always be zero.
4739     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4740
4741     // If all of the bits input the to ctlz node are known to be zero, then
4742     // the result of the ctlz is "32" and the result of the shift is one.
4743     APInt UnknownBits = ~KnownZero;
4744     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4745
4746     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4747     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4748       // Okay, we know that only that the single bit specified by UnknownBits
4749       // could be set on input to the CTLZ node. If this bit is set, the SRL
4750       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4751       // to an SRL/XOR pair, which is likely to simplify more.
4752       unsigned ShAmt = UnknownBits.countTrailingZeros();
4753       SDValue Op = N0.getOperand(0);
4754
4755       if (ShAmt) {
4756         SDLoc DL(N0);
4757         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4758                   DAG.getConstant(ShAmt, DL,
4759                                   getShiftAmountTy(Op.getValueType())));
4760         AddToWorklist(Op.getNode());
4761       }
4762
4763       SDLoc DL(N);
4764       return DAG.getNode(ISD::XOR, DL, VT,
4765                          Op, DAG.getConstant(1, DL, VT));
4766     }
4767   }
4768
4769   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4770   if (N1.getOpcode() == ISD::TRUNCATE &&
4771       N1.getOperand(0).getOpcode() == ISD::AND) {
4772     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4773       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4774   }
4775
4776   // fold operands of srl based on knowledge that the low bits are not
4777   // demanded.
4778   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4779     return SDValue(N, 0);
4780
4781   if (N1C && !N1C->isOpaque())
4782     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4783       return NewSRL;
4784
4785   // Attempt to convert a srl of a load into a narrower zero-extending load.
4786   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4787     return NarrowLoad;
4788
4789   // Here is a common situation. We want to optimize:
4790   //
4791   //   %a = ...
4792   //   %b = and i32 %a, 2
4793   //   %c = srl i32 %b, 1
4794   //   brcond i32 %c ...
4795   //
4796   // into
4797   //
4798   //   %a = ...
4799   //   %b = and %a, 2
4800   //   %c = setcc eq %b, 0
4801   //   brcond %c ...
4802   //
4803   // However when after the source operand of SRL is optimized into AND, the SRL
4804   // itself may not be optimized further. Look for it and add the BRCOND into
4805   // the worklist.
4806   if (N->hasOneUse()) {
4807     SDNode *Use = *N->use_begin();
4808     if (Use->getOpcode() == ISD::BRCOND)
4809       AddToWorklist(Use);
4810     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4811       // Also look pass the truncate.
4812       Use = *Use->use_begin();
4813       if (Use->getOpcode() == ISD::BRCOND)
4814         AddToWorklist(Use);
4815     }
4816   }
4817
4818   return SDValue();
4819 }
4820
4821 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4822   SDValue N0 = N->getOperand(0);
4823   EVT VT = N->getValueType(0);
4824
4825   // fold (bswap c1) -> c2
4826   if (isConstantIntBuildVectorOrConstantInt(N0))
4827     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4828   // fold (bswap (bswap x)) -> x
4829   if (N0.getOpcode() == ISD::BSWAP)
4830     return N0->getOperand(0);
4831   return SDValue();
4832 }
4833
4834 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4835   SDValue N0 = N->getOperand(0);
4836   EVT VT = N->getValueType(0);
4837
4838   // fold (ctlz c1) -> c2
4839   if (isConstantIntBuildVectorOrConstantInt(N0))
4840     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4841   return SDValue();
4842 }
4843
4844 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4845   SDValue N0 = N->getOperand(0);
4846   EVT VT = N->getValueType(0);
4847
4848   // fold (ctlz_zero_undef c1) -> c2
4849   if (isConstantIntBuildVectorOrConstantInt(N0))
4850     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4851   return SDValue();
4852 }
4853
4854 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4855   SDValue N0 = N->getOperand(0);
4856   EVT VT = N->getValueType(0);
4857
4858   // fold (cttz c1) -> c2
4859   if (isConstantIntBuildVectorOrConstantInt(N0))
4860     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4861   return SDValue();
4862 }
4863
4864 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4865   SDValue N0 = N->getOperand(0);
4866   EVT VT = N->getValueType(0);
4867
4868   // fold (cttz_zero_undef c1) -> c2
4869   if (isConstantIntBuildVectorOrConstantInt(N0))
4870     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4871   return SDValue();
4872 }
4873
4874 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4875   SDValue N0 = N->getOperand(0);
4876   EVT VT = N->getValueType(0);
4877
4878   // fold (ctpop c1) -> c2
4879   if (isConstantIntBuildVectorOrConstantInt(N0))
4880     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4881   return SDValue();
4882 }
4883
4884
4885 /// \brief Generate Min/Max node
4886 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4887                                    SDValue True, SDValue False,
4888                                    ISD::CondCode CC, const TargetLowering &TLI,
4889                                    SelectionDAG &DAG) {
4890   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4891     return SDValue();
4892
4893   switch (CC) {
4894   case ISD::SETOLT:
4895   case ISD::SETOLE:
4896   case ISD::SETLT:
4897   case ISD::SETLE:
4898   case ISD::SETULT:
4899   case ISD::SETULE: {
4900     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4901     if (TLI.isOperationLegal(Opcode, VT))
4902       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4903     return SDValue();
4904   }
4905   case ISD::SETOGT:
4906   case ISD::SETOGE:
4907   case ISD::SETGT:
4908   case ISD::SETGE:
4909   case ISD::SETUGT:
4910   case ISD::SETUGE: {
4911     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4912     if (TLI.isOperationLegal(Opcode, VT))
4913       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4914     return SDValue();
4915   }
4916   default:
4917     return SDValue();
4918   }
4919 }
4920
4921 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4922   SDValue N0 = N->getOperand(0);
4923   SDValue N1 = N->getOperand(1);
4924   SDValue N2 = N->getOperand(2);
4925   EVT VT = N->getValueType(0);
4926   EVT VT0 = N0.getValueType();
4927
4928   // fold (select C, X, X) -> X
4929   if (N1 == N2)
4930     return N1;
4931   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4932     // fold (select true, X, Y) -> X
4933     // fold (select false, X, Y) -> Y
4934     return !N0C->isNullValue() ? N1 : N2;
4935   }
4936   // fold (select C, 1, X) -> (or C, X)
4937   if (VT == MVT::i1 && isOneConstant(N1))
4938     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4939   // fold (select C, 0, 1) -> (xor C, 1)
4940   // We can't do this reliably if integer based booleans have different contents
4941   // to floating point based booleans. This is because we can't tell whether we
4942   // have an integer-based boolean or a floating-point-based boolean unless we
4943   // can find the SETCC that produced it and inspect its operands. This is
4944   // fairly easy if C is the SETCC node, but it can potentially be
4945   // undiscoverable (or not reasonably discoverable). For example, it could be
4946   // in another basic block or it could require searching a complicated
4947   // expression.
4948   if (VT.isInteger() &&
4949       (VT0 == MVT::i1 || (VT0.isInteger() &&
4950                           TLI.getBooleanContents(false, false) ==
4951                               TLI.getBooleanContents(false, true) &&
4952                           TLI.getBooleanContents(false, false) ==
4953                               TargetLowering::ZeroOrOneBooleanContent)) &&
4954       isNullConstant(N1) && isOneConstant(N2)) {
4955     SDValue XORNode;
4956     if (VT == VT0) {
4957       SDLoc DL(N);
4958       return DAG.getNode(ISD::XOR, DL, VT0,
4959                          N0, DAG.getConstant(1, DL, VT0));
4960     }
4961     SDLoc DL0(N0);
4962     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4963                           N0, DAG.getConstant(1, DL0, VT0));
4964     AddToWorklist(XORNode.getNode());
4965     if (VT.bitsGT(VT0))
4966       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4967     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4968   }
4969   // fold (select C, 0, X) -> (and (not C), X)
4970   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4971     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4972     AddToWorklist(NOTNode.getNode());
4973     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4974   }
4975   // fold (select C, X, 1) -> (or (not C), X)
4976   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4977     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4978     AddToWorklist(NOTNode.getNode());
4979     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4980   }
4981   // fold (select C, X, 0) -> (and C, X)
4982   if (VT == MVT::i1 && isNullConstant(N2))
4983     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4984   // fold (select X, X, Y) -> (or X, Y)
4985   // fold (select X, 1, Y) -> (or X, Y)
4986   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4987     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4988   // fold (select X, Y, X) -> (and X, Y)
4989   // fold (select X, Y, 0) -> (and X, Y)
4990   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4991     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4992
4993   // If we can fold this based on the true/false value, do so.
4994   if (SimplifySelectOps(N, N1, N2))
4995     return SDValue(N, 0);  // Don't revisit N.
4996
4997   if (VT0 == MVT::i1) {
4998     // The code in this block deals with the following 2 equivalences:
4999     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5000     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5001     // The target can specify its prefered form with the
5002     // shouldNormalizeToSelectSequence() callback. However we always transform
5003     // to the right anyway if we find the inner select exists in the DAG anyway
5004     // and we always transform to the left side if we know that we can further
5005     // optimize the combination of the conditions.
5006     bool normalizeToSequence
5007       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5008     // select (and Cond0, Cond1), X, Y
5009     //   -> select Cond0, (select Cond1, X, Y), Y
5010     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5011       SDValue Cond0 = N0->getOperand(0);
5012       SDValue Cond1 = N0->getOperand(1);
5013       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5014                                         N1.getValueType(), Cond1, N1, N2);
5015       if (normalizeToSequence || !InnerSelect.use_empty())
5016         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5017                            InnerSelect, N2);
5018     }
5019     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5020     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5021       SDValue Cond0 = N0->getOperand(0);
5022       SDValue Cond1 = N0->getOperand(1);
5023       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5024                                         N1.getValueType(), Cond1, N1, N2);
5025       if (normalizeToSequence || !InnerSelect.use_empty())
5026         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5027                            InnerSelect);
5028     }
5029
5030     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5031     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5032       SDValue N1_0 = N1->getOperand(0);
5033       SDValue N1_1 = N1->getOperand(1);
5034       SDValue N1_2 = N1->getOperand(2);
5035       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5036         // Create the actual and node if we can generate good code for it.
5037         if (!normalizeToSequence) {
5038           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5039                                     N0, N1_0);
5040           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5041                              N1_1, N2);
5042         }
5043         // Otherwise see if we can optimize the "and" to a better pattern.
5044         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5045           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5046                              N1_1, N2);
5047       }
5048     }
5049     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5050     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5051       SDValue N2_0 = N2->getOperand(0);
5052       SDValue N2_1 = N2->getOperand(1);
5053       SDValue N2_2 = N2->getOperand(2);
5054       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5055         // Create the actual or node if we can generate good code for it.
5056         if (!normalizeToSequence) {
5057           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5058                                    N0, N2_0);
5059           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5060                              N1, N2_2);
5061         }
5062         // Otherwise see if we can optimize to a better pattern.
5063         if (SDValue Combined = visitORLike(N0, N2_0, N))
5064           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5065                              N1, N2_2);
5066       }
5067     }
5068   }
5069
5070   // fold selects based on a setcc into other things, such as min/max/abs
5071   if (N0.getOpcode() == ISD::SETCC) {
5072     // select x, y (fcmp lt x, y) -> fminnum x, y
5073     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5074     //
5075     // This is OK if we don't care about what happens if either operand is a
5076     // NaN.
5077     //
5078
5079     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5080     // no signed zeros as well as no nans.
5081     const TargetOptions &Options = DAG.getTarget().Options;
5082     if (Options.UnsafeFPMath &&
5083         VT.isFloatingPoint() && N0.hasOneUse() &&
5084         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5085       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5086
5087       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5088                                                 N0.getOperand(1), N1, N2, CC,
5089                                                 TLI, DAG))
5090         return FMinMax;
5091     }
5092
5093     if ((!LegalOperations &&
5094          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5095         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5096       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5097                          N0.getOperand(0), N0.getOperand(1),
5098                          N1, N2, N0.getOperand(2));
5099     return SimplifySelect(SDLoc(N), N0, N1, N2);
5100   }
5101
5102   return SDValue();
5103 }
5104
5105 static
5106 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5107   SDLoc DL(N);
5108   EVT LoVT, HiVT;
5109   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5110
5111   // Split the inputs.
5112   SDValue Lo, Hi, LL, LH, RL, RH;
5113   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5114   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5115
5116   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5117   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5118
5119   return std::make_pair(Lo, Hi);
5120 }
5121
5122 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5123 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5124 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5125   SDLoc dl(N);
5126   SDValue Cond = N->getOperand(0);
5127   SDValue LHS = N->getOperand(1);
5128   SDValue RHS = N->getOperand(2);
5129   EVT VT = N->getValueType(0);
5130   int NumElems = VT.getVectorNumElements();
5131   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5132          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5133          Cond.getOpcode() == ISD::BUILD_VECTOR);
5134
5135   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5136   // binary ones here.
5137   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5138     return SDValue();
5139
5140   // We're sure we have an even number of elements due to the
5141   // concat_vectors we have as arguments to vselect.
5142   // Skip BV elements until we find one that's not an UNDEF
5143   // After we find an UNDEF element, keep looping until we get to half the
5144   // length of the BV and see if all the non-undef nodes are the same.
5145   ConstantSDNode *BottomHalf = nullptr;
5146   for (int i = 0; i < NumElems / 2; ++i) {
5147     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5148       continue;
5149
5150     if (BottomHalf == nullptr)
5151       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5152     else if (Cond->getOperand(i).getNode() != BottomHalf)
5153       return SDValue();
5154   }
5155
5156   // Do the same for the second half of the BuildVector
5157   ConstantSDNode *TopHalf = nullptr;
5158   for (int i = NumElems / 2; i < NumElems; ++i) {
5159     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5160       continue;
5161
5162     if (TopHalf == nullptr)
5163       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5164     else if (Cond->getOperand(i).getNode() != TopHalf)
5165       return SDValue();
5166   }
5167
5168   assert(TopHalf && BottomHalf &&
5169          "One half of the selector was all UNDEFs and the other was all the "
5170          "same value. This should have been addressed before this function.");
5171   return DAG.getNode(
5172       ISD::CONCAT_VECTORS, dl, VT,
5173       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5174       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5175 }
5176
5177 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5178
5179   if (Level >= AfterLegalizeTypes)
5180     return SDValue();
5181
5182   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5183   SDValue Mask = MSC->getMask();
5184   SDValue Data  = MSC->getValue();
5185   SDLoc DL(N);
5186
5187   // If the MSCATTER data type requires splitting and the mask is provided by a
5188   // SETCC, then split both nodes and its operands before legalization. This
5189   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5190   // and enables future optimizations (e.g. min/max pattern matching on X86).
5191   if (Mask.getOpcode() != ISD::SETCC)
5192     return SDValue();
5193
5194   // Check if any splitting is required.
5195   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5196       TargetLowering::TypeSplitVector)
5197     return SDValue();
5198   SDValue MaskLo, MaskHi, Lo, Hi;
5199   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5200
5201   EVT LoVT, HiVT;
5202   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5203
5204   SDValue Chain = MSC->getChain();
5205
5206   EVT MemoryVT = MSC->getMemoryVT();
5207   unsigned Alignment = MSC->getOriginalAlignment();
5208
5209   EVT LoMemVT, HiMemVT;
5210   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5211
5212   SDValue DataLo, DataHi;
5213   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5214
5215   SDValue BasePtr = MSC->getBasePtr();
5216   SDValue IndexLo, IndexHi;
5217   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5218
5219   MachineMemOperand *MMO = DAG.getMachineFunction().
5220     getMachineMemOperand(MSC->getPointerInfo(),
5221                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5222                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5223
5224   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5225   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5226                             DL, OpsLo, MMO);
5227
5228   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5229   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5230                             DL, OpsHi, MMO);
5231
5232   AddToWorklist(Lo.getNode());
5233   AddToWorklist(Hi.getNode());
5234
5235   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5236 }
5237
5238 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5239
5240   if (Level >= AfterLegalizeTypes)
5241     return SDValue();
5242
5243   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5244   SDValue Mask = MST->getMask();
5245   SDValue Data  = MST->getValue();
5246   SDLoc DL(N);
5247
5248   // If the MSTORE data type requires splitting and the mask is provided by a
5249   // SETCC, then split both nodes and its operands before legalization. This
5250   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5251   // and enables future optimizations (e.g. min/max pattern matching on X86).
5252   if (Mask.getOpcode() == ISD::SETCC) {
5253
5254     // Check if any splitting is required.
5255     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5256         TargetLowering::TypeSplitVector)
5257       return SDValue();
5258
5259     SDValue MaskLo, MaskHi, Lo, Hi;
5260     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5261
5262     EVT LoVT, HiVT;
5263     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5264
5265     SDValue Chain = MST->getChain();
5266     SDValue Ptr   = MST->getBasePtr();
5267
5268     EVT MemoryVT = MST->getMemoryVT();
5269     unsigned Alignment = MST->getOriginalAlignment();
5270
5271     // if Alignment is equal to the vector size,
5272     // take the half of it for the second part
5273     unsigned SecondHalfAlignment =
5274       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5275          Alignment/2 : Alignment;
5276
5277     EVT LoMemVT, HiMemVT;
5278     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5279
5280     SDValue DataLo, DataHi;
5281     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5282
5283     MachineMemOperand *MMO = DAG.getMachineFunction().
5284       getMachineMemOperand(MST->getPointerInfo(),
5285                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5286                            Alignment, MST->getAAInfo(), MST->getRanges());
5287
5288     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5289                             MST->isTruncatingStore());
5290
5291     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5292     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5293                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5294
5295     MMO = DAG.getMachineFunction().
5296       getMachineMemOperand(MST->getPointerInfo(),
5297                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5298                            SecondHalfAlignment, MST->getAAInfo(),
5299                            MST->getRanges());
5300
5301     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5302                             MST->isTruncatingStore());
5303
5304     AddToWorklist(Lo.getNode());
5305     AddToWorklist(Hi.getNode());
5306
5307     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5308   }
5309   return SDValue();
5310 }
5311
5312 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5313
5314   if (Level >= AfterLegalizeTypes)
5315     return SDValue();
5316
5317   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5318   SDValue Mask = MGT->getMask();
5319   SDLoc DL(N);
5320
5321   // If the MGATHER result requires splitting and the mask is provided by a
5322   // SETCC, then split both nodes and its operands before legalization. This
5323   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5324   // and enables future optimizations (e.g. min/max pattern matching on X86).
5325
5326   if (Mask.getOpcode() != ISD::SETCC)
5327     return SDValue();
5328
5329   EVT VT = N->getValueType(0);
5330
5331   // Check if any splitting is required.
5332   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5333       TargetLowering::TypeSplitVector)
5334     return SDValue();
5335
5336   SDValue MaskLo, MaskHi, Lo, Hi;
5337   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5338
5339   SDValue Src0 = MGT->getValue();
5340   SDValue Src0Lo, Src0Hi;
5341   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5342
5343   EVT LoVT, HiVT;
5344   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5345
5346   SDValue Chain = MGT->getChain();
5347   EVT MemoryVT = MGT->getMemoryVT();
5348   unsigned Alignment = MGT->getOriginalAlignment();
5349
5350   EVT LoMemVT, HiMemVT;
5351   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5352
5353   SDValue BasePtr = MGT->getBasePtr();
5354   SDValue Index = MGT->getIndex();
5355   SDValue IndexLo, IndexHi;
5356   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5357
5358   MachineMemOperand *MMO = DAG.getMachineFunction().
5359     getMachineMemOperand(MGT->getPointerInfo(),
5360                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5361                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5362
5363   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5364   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5365                             MMO);
5366
5367   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5368   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5369                             MMO);
5370
5371   AddToWorklist(Lo.getNode());
5372   AddToWorklist(Hi.getNode());
5373
5374   // Build a factor node to remember that this load is independent of the
5375   // other one.
5376   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5377                       Hi.getValue(1));
5378
5379   // Legalized the chain result - switch anything that used the old chain to
5380   // use the new one.
5381   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5382
5383   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5384
5385   SDValue RetOps[] = { GatherRes, Chain };
5386   return DAG.getMergeValues(RetOps, DL);
5387 }
5388
5389 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5390
5391   if (Level >= AfterLegalizeTypes)
5392     return SDValue();
5393
5394   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5395   SDValue Mask = MLD->getMask();
5396   SDLoc DL(N);
5397
5398   // If the MLOAD result requires splitting and the mask is provided by a
5399   // SETCC, then split both nodes and its operands before legalization. This
5400   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5401   // and enables future optimizations (e.g. min/max pattern matching on X86).
5402
5403   if (Mask.getOpcode() == ISD::SETCC) {
5404     EVT VT = N->getValueType(0);
5405
5406     // Check if any splitting is required.
5407     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5408         TargetLowering::TypeSplitVector)
5409       return SDValue();
5410
5411     SDValue MaskLo, MaskHi, Lo, Hi;
5412     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5413
5414     SDValue Src0 = MLD->getSrc0();
5415     SDValue Src0Lo, Src0Hi;
5416     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5417
5418     EVT LoVT, HiVT;
5419     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5420
5421     SDValue Chain = MLD->getChain();
5422     SDValue Ptr   = MLD->getBasePtr();
5423     EVT MemoryVT = MLD->getMemoryVT();
5424     unsigned Alignment = MLD->getOriginalAlignment();
5425
5426     // if Alignment is equal to the vector size,
5427     // take the half of it for the second part
5428     unsigned SecondHalfAlignment =
5429       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5430          Alignment/2 : Alignment;
5431
5432     EVT LoMemVT, HiMemVT;
5433     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5434
5435     MachineMemOperand *MMO = DAG.getMachineFunction().
5436     getMachineMemOperand(MLD->getPointerInfo(),
5437                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5438                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5439
5440     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5441                            ISD::NON_EXTLOAD);
5442
5443     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5444     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5445                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5446
5447     MMO = DAG.getMachineFunction().
5448     getMachineMemOperand(MLD->getPointerInfo(),
5449                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5450                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5451
5452     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5453                            ISD::NON_EXTLOAD);
5454
5455     AddToWorklist(Lo.getNode());
5456     AddToWorklist(Hi.getNode());
5457
5458     // Build a factor node to remember that this load is independent of the
5459     // other one.
5460     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5461                         Hi.getValue(1));
5462
5463     // Legalized the chain result - switch anything that used the old chain to
5464     // use the new one.
5465     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5466
5467     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5468
5469     SDValue RetOps[] = { LoadRes, Chain };
5470     return DAG.getMergeValues(RetOps, DL);
5471   }
5472   return SDValue();
5473 }
5474
5475 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5476   SDValue N0 = N->getOperand(0);
5477   SDValue N1 = N->getOperand(1);
5478   SDValue N2 = N->getOperand(2);
5479   SDLoc DL(N);
5480
5481   // Canonicalize integer abs.
5482   // vselect (setg[te] X,  0),  X, -X ->
5483   // vselect (setgt    X, -1),  X, -X ->
5484   // vselect (setl[te] X,  0), -X,  X ->
5485   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5486   if (N0.getOpcode() == ISD::SETCC) {
5487     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5488     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5489     bool isAbs = false;
5490     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5491
5492     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5493          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5494         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5495       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5496     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5497              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5498       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5499
5500     if (isAbs) {
5501       EVT VT = LHS.getValueType();
5502       SDValue Shift = DAG.getNode(
5503           ISD::SRA, DL, VT, LHS,
5504           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5505       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5506       AddToWorklist(Shift.getNode());
5507       AddToWorklist(Add.getNode());
5508       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5509     }
5510   }
5511
5512   if (SimplifySelectOps(N, N1, N2))
5513     return SDValue(N, 0);  // Don't revisit N.
5514
5515   // If the VSELECT result requires splitting and the mask is provided by a
5516   // SETCC, then split both nodes and its operands before legalization. This
5517   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5518   // and enables future optimizations (e.g. min/max pattern matching on X86).
5519   if (N0.getOpcode() == ISD::SETCC) {
5520     EVT VT = N->getValueType(0);
5521
5522     // Check if any splitting is required.
5523     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5524         TargetLowering::TypeSplitVector)
5525       return SDValue();
5526
5527     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5528     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5529     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5530     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5531
5532     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5533     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5534
5535     // Add the new VSELECT nodes to the work list in case they need to be split
5536     // again.
5537     AddToWorklist(Lo.getNode());
5538     AddToWorklist(Hi.getNode());
5539
5540     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5541   }
5542
5543   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5544   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5545     return N1;
5546   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5547   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5548     return N2;
5549
5550   // The ConvertSelectToConcatVector function is assuming both the above
5551   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5552   // and addressed.
5553   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5554       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5555       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5556     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5557       return CV;
5558   }
5559
5560   return SDValue();
5561 }
5562
5563 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5564   SDValue N0 = N->getOperand(0);
5565   SDValue N1 = N->getOperand(1);
5566   SDValue N2 = N->getOperand(2);
5567   SDValue N3 = N->getOperand(3);
5568   SDValue N4 = N->getOperand(4);
5569   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5570
5571   // fold select_cc lhs, rhs, x, x, cc -> x
5572   if (N2 == N3)
5573     return N2;
5574
5575   // Determine if the condition we're dealing with is constant
5576   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5577                               N0, N1, CC, SDLoc(N), false);
5578   if (SCC.getNode()) {
5579     AddToWorklist(SCC.getNode());
5580
5581     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5582       if (!SCCC->isNullValue())
5583         return N2;    // cond always true -> true val
5584       else
5585         return N3;    // cond always false -> false val
5586     } else if (SCC->getOpcode() == ISD::UNDEF) {
5587       // When the condition is UNDEF, just return the first operand. This is
5588       // coherent the DAG creation, no setcc node is created in this case
5589       return N2;
5590     } else if (SCC.getOpcode() == ISD::SETCC) {
5591       // Fold to a simpler select_cc
5592       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5593                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5594                          SCC.getOperand(2));
5595     }
5596   }
5597
5598   // If we can fold this based on the true/false value, do so.
5599   if (SimplifySelectOps(N, N2, N3))
5600     return SDValue(N, 0);  // Don't revisit N.
5601
5602   // fold select_cc into other things, such as min/max/abs
5603   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5604 }
5605
5606 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5607   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5608                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5609                        SDLoc(N));
5610 }
5611
5612 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5613 /// a build_vector of constants.
5614 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5615 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5616 /// Vector extends are not folded if operations are legal; this is to
5617 /// avoid introducing illegal build_vector dag nodes.
5618 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5619                                          SelectionDAG &DAG, bool LegalTypes,
5620                                          bool LegalOperations) {
5621   unsigned Opcode = N->getOpcode();
5622   SDValue N0 = N->getOperand(0);
5623   EVT VT = N->getValueType(0);
5624
5625   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5626          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5627          && "Expected EXTEND dag node in input!");
5628
5629   // fold (sext c1) -> c1
5630   // fold (zext c1) -> c1
5631   // fold (aext c1) -> c1
5632   if (isa<ConstantSDNode>(N0))
5633     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5634
5635   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5636   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5637   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5638   EVT SVT = VT.getScalarType();
5639   if (!(VT.isVector() &&
5640       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5641       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5642     return nullptr;
5643
5644   // We can fold this node into a build_vector.
5645   unsigned VTBits = SVT.getSizeInBits();
5646   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5647   SmallVector<SDValue, 8> Elts;
5648   unsigned NumElts = VT.getVectorNumElements();
5649   SDLoc DL(N);
5650
5651   for (unsigned i=0; i != NumElts; ++i) {
5652     SDValue Op = N0->getOperand(i);
5653     if (Op->getOpcode() == ISD::UNDEF) {
5654       Elts.push_back(DAG.getUNDEF(SVT));
5655       continue;
5656     }
5657
5658     SDLoc DL(Op);
5659     // Get the constant value and if needed trunc it to the size of the type.
5660     // Nodes like build_vector might have constants wider than the scalar type.
5661     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5662     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5663       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5664     else
5665       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5666   }
5667
5668   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5669 }
5670
5671 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5672 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5673 // transformation. Returns true if extension are possible and the above
5674 // mentioned transformation is profitable.
5675 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5676                                     unsigned ExtOpc,
5677                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5678                                     const TargetLowering &TLI) {
5679   bool HasCopyToRegUses = false;
5680   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5681   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5682                             UE = N0.getNode()->use_end();
5683        UI != UE; ++UI) {
5684     SDNode *User = *UI;
5685     if (User == N)
5686       continue;
5687     if (UI.getUse().getResNo() != N0.getResNo())
5688       continue;
5689     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5690     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5691       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5692       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5693         // Sign bits will be lost after a zext.
5694         return false;
5695       bool Add = false;
5696       for (unsigned i = 0; i != 2; ++i) {
5697         SDValue UseOp = User->getOperand(i);
5698         if (UseOp == N0)
5699           continue;
5700         if (!isa<ConstantSDNode>(UseOp))
5701           return false;
5702         Add = true;
5703       }
5704       if (Add)
5705         ExtendNodes.push_back(User);
5706       continue;
5707     }
5708     // If truncates aren't free and there are users we can't
5709     // extend, it isn't worthwhile.
5710     if (!isTruncFree)
5711       return false;
5712     // Remember if this value is live-out.
5713     if (User->getOpcode() == ISD::CopyToReg)
5714       HasCopyToRegUses = true;
5715   }
5716
5717   if (HasCopyToRegUses) {
5718     bool BothLiveOut = false;
5719     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5720          UI != UE; ++UI) {
5721       SDUse &Use = UI.getUse();
5722       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5723         BothLiveOut = true;
5724         break;
5725       }
5726     }
5727     if (BothLiveOut)
5728       // Both unextended and extended values are live out. There had better be
5729       // a good reason for the transformation.
5730       return ExtendNodes.size();
5731   }
5732   return true;
5733 }
5734
5735 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5736                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5737                                   ISD::NodeType ExtType) {
5738   // Extend SetCC uses if necessary.
5739   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5740     SDNode *SetCC = SetCCs[i];
5741     SmallVector<SDValue, 4> Ops;
5742
5743     for (unsigned j = 0; j != 2; ++j) {
5744       SDValue SOp = SetCC->getOperand(j);
5745       if (SOp == Trunc)
5746         Ops.push_back(ExtLoad);
5747       else
5748         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5749     }
5750
5751     Ops.push_back(SetCC->getOperand(2));
5752     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5753   }
5754 }
5755
5756 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5757 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5758   SDValue N0 = N->getOperand(0);
5759   EVT DstVT = N->getValueType(0);
5760   EVT SrcVT = N0.getValueType();
5761
5762   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5763           N->getOpcode() == ISD::ZERO_EXTEND) &&
5764          "Unexpected node type (not an extend)!");
5765
5766   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5767   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5768   //   (v8i32 (sext (v8i16 (load x))))
5769   // into:
5770   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5771   //                          (v4i32 (sextload (x + 16)))))
5772   // Where uses of the original load, i.e.:
5773   //   (v8i16 (load x))
5774   // are replaced with:
5775   //   (v8i16 (truncate
5776   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5777   //                            (v4i32 (sextload (x + 16)))))))
5778   //
5779   // This combine is only applicable to illegal, but splittable, vectors.
5780   // All legal types, and illegal non-vector types, are handled elsewhere.
5781   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5782   //
5783   if (N0->getOpcode() != ISD::LOAD)
5784     return SDValue();
5785
5786   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5787
5788   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5789       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5790       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5791     return SDValue();
5792
5793   SmallVector<SDNode *, 4> SetCCs;
5794   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5795     return SDValue();
5796
5797   ISD::LoadExtType ExtType =
5798       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5799
5800   // Try to split the vector types to get down to legal types.
5801   EVT SplitSrcVT = SrcVT;
5802   EVT SplitDstVT = DstVT;
5803   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5804          SplitSrcVT.getVectorNumElements() > 1) {
5805     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5806     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5807   }
5808
5809   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5810     return SDValue();
5811
5812   SDLoc DL(N);
5813   const unsigned NumSplits =
5814       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5815   const unsigned Stride = SplitSrcVT.getStoreSize();
5816   SmallVector<SDValue, 4> Loads;
5817   SmallVector<SDValue, 4> Chains;
5818
5819   SDValue BasePtr = LN0->getBasePtr();
5820   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5821     const unsigned Offset = Idx * Stride;
5822     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5823
5824     SDValue SplitLoad = DAG.getExtLoad(
5825         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5826         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5827         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5828         Align, LN0->getAAInfo());
5829
5830     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5831                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5832
5833     Loads.push_back(SplitLoad.getValue(0));
5834     Chains.push_back(SplitLoad.getValue(1));
5835   }
5836
5837   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5838   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5839
5840   CombineTo(N, NewValue);
5841
5842   // Replace uses of the original load (before extension)
5843   // with a truncate of the concatenated sextloaded vectors.
5844   SDValue Trunc =
5845       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5846   CombineTo(N0.getNode(), Trunc, NewChain);
5847   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5848                   (ISD::NodeType)N->getOpcode());
5849   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5850 }
5851
5852 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5853   SDValue N0 = N->getOperand(0);
5854   EVT VT = N->getValueType(0);
5855
5856   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5857                                               LegalOperations))
5858     return SDValue(Res, 0);
5859
5860   // fold (sext (sext x)) -> (sext x)
5861   // fold (sext (aext x)) -> (sext x)
5862   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5863     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5864                        N0.getOperand(0));
5865
5866   if (N0.getOpcode() == ISD::TRUNCATE) {
5867     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5868     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5869     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5870       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5871       if (NarrowLoad.getNode() != N0.getNode()) {
5872         CombineTo(N0.getNode(), NarrowLoad);
5873         // CombineTo deleted the truncate, if needed, but not what's under it.
5874         AddToWorklist(oye);
5875       }
5876       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5877     }
5878
5879     // See if the value being truncated is already sign extended.  If so, just
5880     // eliminate the trunc/sext pair.
5881     SDValue Op = N0.getOperand(0);
5882     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5883     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5884     unsigned DestBits = VT.getScalarType().getSizeInBits();
5885     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5886
5887     if (OpBits == DestBits) {
5888       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5889       // bits, it is already ready.
5890       if (NumSignBits > DestBits-MidBits)
5891         return Op;
5892     } else if (OpBits < DestBits) {
5893       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5894       // bits, just sext from i32.
5895       if (NumSignBits > OpBits-MidBits)
5896         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5897     } else {
5898       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5899       // bits, just truncate to i32.
5900       if (NumSignBits > OpBits-MidBits)
5901         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5902     }
5903
5904     // fold (sext (truncate x)) -> (sextinreg x).
5905     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5906                                                  N0.getValueType())) {
5907       if (OpBits < DestBits)
5908         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5909       else if (OpBits > DestBits)
5910         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5911       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5912                          DAG.getValueType(N0.getValueType()));
5913     }
5914   }
5915
5916   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5917   // Only generate vector extloads when 1) they're legal, and 2) they are
5918   // deemed desirable by the target.
5919   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5920       ((!LegalOperations && !VT.isVector() &&
5921         !cast<LoadSDNode>(N0)->isVolatile()) ||
5922        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5923     bool DoXform = true;
5924     SmallVector<SDNode*, 4> SetCCs;
5925     if (!N0.hasOneUse())
5926       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5927     if (VT.isVector())
5928       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5929     if (DoXform) {
5930       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5931       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5932                                        LN0->getChain(),
5933                                        LN0->getBasePtr(), N0.getValueType(),
5934                                        LN0->getMemOperand());
5935       CombineTo(N, ExtLoad);
5936       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5937                                   N0.getValueType(), ExtLoad);
5938       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5939       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5940                       ISD::SIGN_EXTEND);
5941       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5942     }
5943   }
5944
5945   // fold (sext (load x)) to multiple smaller sextloads.
5946   // Only on illegal but splittable vectors.
5947   if (SDValue ExtLoad = CombineExtLoad(N))
5948     return ExtLoad;
5949
5950   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5951   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5952   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5953       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5954     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5955     EVT MemVT = LN0->getMemoryVT();
5956     if ((!LegalOperations && !LN0->isVolatile()) ||
5957         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5958       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5959                                        LN0->getChain(),
5960                                        LN0->getBasePtr(), MemVT,
5961                                        LN0->getMemOperand());
5962       CombineTo(N, ExtLoad);
5963       CombineTo(N0.getNode(),
5964                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5965                             N0.getValueType(), ExtLoad),
5966                 ExtLoad.getValue(1));
5967       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5968     }
5969   }
5970
5971   // fold (sext (and/or/xor (load x), cst)) ->
5972   //      (and/or/xor (sextload x), (sext cst))
5973   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5974        N0.getOpcode() == ISD::XOR) &&
5975       isa<LoadSDNode>(N0.getOperand(0)) &&
5976       N0.getOperand(1).getOpcode() == ISD::Constant &&
5977       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5978       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5979     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5980     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5981       bool DoXform = true;
5982       SmallVector<SDNode*, 4> SetCCs;
5983       if (!N0.hasOneUse())
5984         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5985                                           SetCCs, TLI);
5986       if (DoXform) {
5987         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5988                                          LN0->getChain(), LN0->getBasePtr(),
5989                                          LN0->getMemoryVT(),
5990                                          LN0->getMemOperand());
5991         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5992         Mask = Mask.sext(VT.getSizeInBits());
5993         SDLoc DL(N);
5994         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5995                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5996         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5997                                     SDLoc(N0.getOperand(0)),
5998                                     N0.getOperand(0).getValueType(), ExtLoad);
5999         CombineTo(N, And);
6000         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6001         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6002                         ISD::SIGN_EXTEND);
6003         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6004       }
6005     }
6006   }
6007
6008   if (N0.getOpcode() == ISD::SETCC) {
6009     EVT N0VT = N0.getOperand(0).getValueType();
6010     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6011     // Only do this before legalize for now.
6012     if (VT.isVector() && !LegalOperations &&
6013         TLI.getBooleanContents(N0VT) ==
6014             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6015       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6016       // of the same size as the compared operands. Only optimize sext(setcc())
6017       // if this is the case.
6018       EVT SVT = getSetCCResultType(N0VT);
6019
6020       // We know that the # elements of the results is the same as the
6021       // # elements of the compare (and the # elements of the compare result
6022       // for that matter).  Check to see that they are the same size.  If so,
6023       // we know that the element size of the sext'd result matches the
6024       // element size of the compare operands.
6025       if (VT.getSizeInBits() == SVT.getSizeInBits())
6026         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6027                              N0.getOperand(1),
6028                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6029
6030       // If the desired elements are smaller or larger than the source
6031       // elements we can use a matching integer vector type and then
6032       // truncate/sign extend
6033       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6034       if (SVT == MatchingVectorType) {
6035         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6036                                N0.getOperand(0), N0.getOperand(1),
6037                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6038         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6039       }
6040     }
6041
6042     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6043     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6044     SDLoc DL(N);
6045     SDValue NegOne =
6046       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6047     SDValue SCC =
6048       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6049                        NegOne, DAG.getConstant(0, DL, VT),
6050                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6051     if (SCC.getNode()) return SCC;
6052
6053     if (!VT.isVector()) {
6054       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6055       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6056         SDLoc DL(N);
6057         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6058         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6059                                      N0.getOperand(0), N0.getOperand(1), CC);
6060         return DAG.getSelect(DL, VT, SetCC,
6061                              NegOne, DAG.getConstant(0, DL, VT));
6062       }
6063     }
6064   }
6065
6066   // fold (sext x) -> (zext x) if the sign bit is known zero.
6067   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6068       DAG.SignBitIsZero(N0))
6069     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6070
6071   return SDValue();
6072 }
6073
6074 // isTruncateOf - If N is a truncate of some other value, return true, record
6075 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6076 // This function computes KnownZero to avoid a duplicated call to
6077 // computeKnownBits in the caller.
6078 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6079                          APInt &KnownZero) {
6080   APInt KnownOne;
6081   if (N->getOpcode() == ISD::TRUNCATE) {
6082     Op = N->getOperand(0);
6083     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6084     return true;
6085   }
6086
6087   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6088       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6089     return false;
6090
6091   SDValue Op0 = N->getOperand(0);
6092   SDValue Op1 = N->getOperand(1);
6093   assert(Op0.getValueType() == Op1.getValueType());
6094
6095   if (isNullConstant(Op0))
6096     Op = Op1;
6097   else if (isNullConstant(Op1))
6098     Op = Op0;
6099   else
6100     return false;
6101
6102   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6103
6104   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6105     return false;
6106
6107   return true;
6108 }
6109
6110 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6111   SDValue N0 = N->getOperand(0);
6112   EVT VT = N->getValueType(0);
6113
6114   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6115                                               LegalOperations))
6116     return SDValue(Res, 0);
6117
6118   // fold (zext (zext x)) -> (zext x)
6119   // fold (zext (aext x)) -> (zext x)
6120   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6121     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6122                        N0.getOperand(0));
6123
6124   // fold (zext (truncate x)) -> (zext x) or
6125   //      (zext (truncate x)) -> (truncate x)
6126   // This is valid when the truncated bits of x are already zero.
6127   // FIXME: We should extend this to work for vectors too.
6128   SDValue Op;
6129   APInt KnownZero;
6130   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6131     APInt TruncatedBits =
6132       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6133       APInt(Op.getValueSizeInBits(), 0) :
6134       APInt::getBitsSet(Op.getValueSizeInBits(),
6135                         N0.getValueSizeInBits(),
6136                         std::min(Op.getValueSizeInBits(),
6137                                  VT.getSizeInBits()));
6138     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6139       if (VT.bitsGT(Op.getValueType()))
6140         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6141       if (VT.bitsLT(Op.getValueType()))
6142         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6143
6144       return Op;
6145     }
6146   }
6147
6148   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6149   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6150   if (N0.getOpcode() == ISD::TRUNCATE) {
6151     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6152       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6153       if (NarrowLoad.getNode() != N0.getNode()) {
6154         CombineTo(N0.getNode(), NarrowLoad);
6155         // CombineTo deleted the truncate, if needed, but not what's under it.
6156         AddToWorklist(oye);
6157       }
6158       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6159     }
6160   }
6161
6162   // fold (zext (truncate x)) -> (and x, mask)
6163   if (N0.getOpcode() == ISD::TRUNCATE) {
6164     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6165     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6166     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6167       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6168       if (NarrowLoad.getNode() != N0.getNode()) {
6169         CombineTo(N0.getNode(), NarrowLoad);
6170         // CombineTo deleted the truncate, if needed, but not what's under it.
6171         AddToWorklist(oye);
6172       }
6173       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6174     }
6175
6176     EVT SrcVT = N0.getOperand(0).getValueType();
6177     EVT MinVT = N0.getValueType();
6178
6179     // Try to mask before the extension to avoid having to generate a larger mask,
6180     // possibly over several sub-vectors.
6181     if (SrcVT.bitsLT(VT)) {
6182       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6183                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6184         SDValue Op = N0.getOperand(0);
6185         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6186         AddToWorklist(Op.getNode());
6187         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6188       }
6189     }
6190
6191     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6192       SDValue Op = N0.getOperand(0);
6193       if (SrcVT.bitsLT(VT)) {
6194         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6195         AddToWorklist(Op.getNode());
6196       } else if (SrcVT.bitsGT(VT)) {
6197         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6198         AddToWorklist(Op.getNode());
6199       }
6200       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6201     }
6202   }
6203
6204   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6205   // if either of the casts is not free.
6206   if (N0.getOpcode() == ISD::AND &&
6207       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6208       N0.getOperand(1).getOpcode() == ISD::Constant &&
6209       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6210                            N0.getValueType()) ||
6211        !TLI.isZExtFree(N0.getValueType(), VT))) {
6212     SDValue X = N0.getOperand(0).getOperand(0);
6213     if (X.getValueType().bitsLT(VT)) {
6214       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6215     } else if (X.getValueType().bitsGT(VT)) {
6216       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6217     }
6218     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6219     Mask = Mask.zext(VT.getSizeInBits());
6220     SDLoc DL(N);
6221     return DAG.getNode(ISD::AND, DL, VT,
6222                        X, DAG.getConstant(Mask, DL, VT));
6223   }
6224
6225   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6226   // Only generate vector extloads when 1) they're legal, and 2) they are
6227   // deemed desirable by the target.
6228   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6229       ((!LegalOperations && !VT.isVector() &&
6230         !cast<LoadSDNode>(N0)->isVolatile()) ||
6231        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6232     bool DoXform = true;
6233     SmallVector<SDNode*, 4> SetCCs;
6234     if (!N0.hasOneUse())
6235       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6236     if (VT.isVector())
6237       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6238     if (DoXform) {
6239       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6240       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6241                                        LN0->getChain(),
6242                                        LN0->getBasePtr(), N0.getValueType(),
6243                                        LN0->getMemOperand());
6244       CombineTo(N, ExtLoad);
6245       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6246                                   N0.getValueType(), ExtLoad);
6247       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6248
6249       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6250                       ISD::ZERO_EXTEND);
6251       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6252     }
6253   }
6254
6255   // fold (zext (load x)) to multiple smaller zextloads.
6256   // Only on illegal but splittable vectors.
6257   if (SDValue ExtLoad = CombineExtLoad(N))
6258     return ExtLoad;
6259
6260   // fold (zext (and/or/xor (load x), cst)) ->
6261   //      (and/or/xor (zextload x), (zext cst))
6262   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6263        N0.getOpcode() == ISD::XOR) &&
6264       isa<LoadSDNode>(N0.getOperand(0)) &&
6265       N0.getOperand(1).getOpcode() == ISD::Constant &&
6266       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6267       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6268     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6269     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6270       bool DoXform = true;
6271       SmallVector<SDNode*, 4> SetCCs;
6272       if (!N0.hasOneUse())
6273         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6274                                           SetCCs, TLI);
6275       if (DoXform) {
6276         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6277                                          LN0->getChain(), LN0->getBasePtr(),
6278                                          LN0->getMemoryVT(),
6279                                          LN0->getMemOperand());
6280         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6281         Mask = Mask.zext(VT.getSizeInBits());
6282         SDLoc DL(N);
6283         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6284                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6285         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6286                                     SDLoc(N0.getOperand(0)),
6287                                     N0.getOperand(0).getValueType(), ExtLoad);
6288         CombineTo(N, And);
6289         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6290         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6291                         ISD::ZERO_EXTEND);
6292         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6293       }
6294     }
6295   }
6296
6297   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6298   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6299   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6300       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6301     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6302     EVT MemVT = LN0->getMemoryVT();
6303     if ((!LegalOperations && !LN0->isVolatile()) ||
6304         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6305       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6306                                        LN0->getChain(),
6307                                        LN0->getBasePtr(), MemVT,
6308                                        LN0->getMemOperand());
6309       CombineTo(N, ExtLoad);
6310       CombineTo(N0.getNode(),
6311                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6312                             ExtLoad),
6313                 ExtLoad.getValue(1));
6314       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6315     }
6316   }
6317
6318   if (N0.getOpcode() == ISD::SETCC) {
6319     if (!LegalOperations && VT.isVector() &&
6320         N0.getValueType().getVectorElementType() == MVT::i1) {
6321       EVT N0VT = N0.getOperand(0).getValueType();
6322       if (getSetCCResultType(N0VT) == N0.getValueType())
6323         return SDValue();
6324
6325       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6326       // Only do this before legalize for now.
6327       EVT EltVT = VT.getVectorElementType();
6328       SDLoc DL(N);
6329       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6330                                     DAG.getConstant(1, DL, EltVT));
6331       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6332         // We know that the # elements of the results is the same as the
6333         // # elements of the compare (and the # elements of the compare result
6334         // for that matter).  Check to see that they are the same size.  If so,
6335         // we know that the element size of the sext'd result matches the
6336         // element size of the compare operands.
6337         return DAG.getNode(ISD::AND, DL, VT,
6338                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6339                                          N0.getOperand(1),
6340                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6341                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6342                                        OneOps));
6343
6344       // If the desired elements are smaller or larger than the source
6345       // elements we can use a matching integer vector type and then
6346       // truncate/sign extend
6347       EVT MatchingElementType =
6348         EVT::getIntegerVT(*DAG.getContext(),
6349                           N0VT.getScalarType().getSizeInBits());
6350       EVT MatchingVectorType =
6351         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6352                          N0VT.getVectorNumElements());
6353       SDValue VsetCC =
6354         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6355                       N0.getOperand(1),
6356                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6357       return DAG.getNode(ISD::AND, DL, VT,
6358                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6359                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6360     }
6361
6362     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6363     SDLoc DL(N);
6364     SDValue SCC =
6365       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6366                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6367                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6368     if (SCC.getNode()) return SCC;
6369   }
6370
6371   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6372   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6373       isa<ConstantSDNode>(N0.getOperand(1)) &&
6374       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6375       N0.hasOneUse()) {
6376     SDValue ShAmt = N0.getOperand(1);
6377     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6378     if (N0.getOpcode() == ISD::SHL) {
6379       SDValue InnerZExt = N0.getOperand(0);
6380       // If the original shl may be shifting out bits, do not perform this
6381       // transformation.
6382       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6383         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6384       if (ShAmtVal > KnownZeroBits)
6385         return SDValue();
6386     }
6387
6388     SDLoc DL(N);
6389
6390     // Ensure that the shift amount is wide enough for the shifted value.
6391     if (VT.getSizeInBits() >= 256)
6392       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6393
6394     return DAG.getNode(N0.getOpcode(), DL, VT,
6395                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6396                        ShAmt);
6397   }
6398
6399   return SDValue();
6400 }
6401
6402 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6403   SDValue N0 = N->getOperand(0);
6404   EVT VT = N->getValueType(0);
6405
6406   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6407                                               LegalOperations))
6408     return SDValue(Res, 0);
6409
6410   // fold (aext (aext x)) -> (aext x)
6411   // fold (aext (zext x)) -> (zext x)
6412   // fold (aext (sext x)) -> (sext x)
6413   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6414       N0.getOpcode() == ISD::ZERO_EXTEND ||
6415       N0.getOpcode() == ISD::SIGN_EXTEND)
6416     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6417
6418   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6419   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6420   if (N0.getOpcode() == ISD::TRUNCATE) {
6421     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6422       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6423       if (NarrowLoad.getNode() != N0.getNode()) {
6424         CombineTo(N0.getNode(), NarrowLoad);
6425         // CombineTo deleted the truncate, if needed, but not what's under it.
6426         AddToWorklist(oye);
6427       }
6428       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6429     }
6430   }
6431
6432   // fold (aext (truncate x))
6433   if (N0.getOpcode() == ISD::TRUNCATE) {
6434     SDValue TruncOp = N0.getOperand(0);
6435     if (TruncOp.getValueType() == VT)
6436       return TruncOp; // x iff x size == zext size.
6437     if (TruncOp.getValueType().bitsGT(VT))
6438       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6439     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6440   }
6441
6442   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6443   // if the trunc is not free.
6444   if (N0.getOpcode() == ISD::AND &&
6445       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6446       N0.getOperand(1).getOpcode() == ISD::Constant &&
6447       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6448                           N0.getValueType())) {
6449     SDValue X = N0.getOperand(0).getOperand(0);
6450     if (X.getValueType().bitsLT(VT)) {
6451       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6452     } else if (X.getValueType().bitsGT(VT)) {
6453       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6454     }
6455     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6456     Mask = Mask.zext(VT.getSizeInBits());
6457     SDLoc DL(N);
6458     return DAG.getNode(ISD::AND, DL, VT,
6459                        X, DAG.getConstant(Mask, DL, VT));
6460   }
6461
6462   // fold (aext (load x)) -> (aext (truncate (extload x)))
6463   // None of the supported targets knows how to perform load and any_ext
6464   // on vectors in one instruction.  We only perform this transformation on
6465   // scalars.
6466   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6467       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6468       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6469     bool DoXform = true;
6470     SmallVector<SDNode*, 4> SetCCs;
6471     if (!N0.hasOneUse())
6472       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6473     if (DoXform) {
6474       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6475       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6476                                        LN0->getChain(),
6477                                        LN0->getBasePtr(), N0.getValueType(),
6478                                        LN0->getMemOperand());
6479       CombineTo(N, ExtLoad);
6480       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6481                                   N0.getValueType(), ExtLoad);
6482       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6483       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6484                       ISD::ANY_EXTEND);
6485       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6486     }
6487   }
6488
6489   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6490   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6491   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6492   if (N0.getOpcode() == ISD::LOAD &&
6493       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6494       N0.hasOneUse()) {
6495     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6496     ISD::LoadExtType ExtType = LN0->getExtensionType();
6497     EVT MemVT = LN0->getMemoryVT();
6498     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6499       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6500                                        VT, LN0->getChain(), LN0->getBasePtr(),
6501                                        MemVT, LN0->getMemOperand());
6502       CombineTo(N, ExtLoad);
6503       CombineTo(N0.getNode(),
6504                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6505                             N0.getValueType(), ExtLoad),
6506                 ExtLoad.getValue(1));
6507       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6508     }
6509   }
6510
6511   if (N0.getOpcode() == ISD::SETCC) {
6512     // For vectors:
6513     // aext(setcc) -> vsetcc
6514     // aext(setcc) -> truncate(vsetcc)
6515     // aext(setcc) -> aext(vsetcc)
6516     // Only do this before legalize for now.
6517     if (VT.isVector() && !LegalOperations) {
6518       EVT N0VT = N0.getOperand(0).getValueType();
6519         // We know that the # elements of the results is the same as the
6520         // # elements of the compare (and the # elements of the compare result
6521         // for that matter).  Check to see that they are the same size.  If so,
6522         // we know that the element size of the sext'd result matches the
6523         // element size of the compare operands.
6524       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6525         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6526                              N0.getOperand(1),
6527                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6528       // If the desired elements are smaller or larger than the source
6529       // elements we can use a matching integer vector type and then
6530       // truncate/any extend
6531       else {
6532         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6533         SDValue VsetCC =
6534           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6535                         N0.getOperand(1),
6536                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6537         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6538       }
6539     }
6540
6541     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6542     SDLoc DL(N);
6543     SDValue SCC =
6544       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6545                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6546                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6547     if (SCC.getNode())
6548       return SCC;
6549   }
6550
6551   return SDValue();
6552 }
6553
6554 /// See if the specified operand can be simplified with the knowledge that only
6555 /// the bits specified by Mask are used.  If so, return the simpler operand,
6556 /// otherwise return a null SDValue.
6557 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6558   switch (V.getOpcode()) {
6559   default: break;
6560   case ISD::Constant: {
6561     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6562     assert(CV && "Const value should be ConstSDNode.");
6563     const APInt &CVal = CV->getAPIntValue();
6564     APInt NewVal = CVal & Mask;
6565     if (NewVal != CVal)
6566       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6567     break;
6568   }
6569   case ISD::OR:
6570   case ISD::XOR:
6571     // If the LHS or RHS don't contribute bits to the or, drop them.
6572     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6573       return V.getOperand(1);
6574     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6575       return V.getOperand(0);
6576     break;
6577   case ISD::SRL:
6578     // Only look at single-use SRLs.
6579     if (!V.getNode()->hasOneUse())
6580       break;
6581     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6582       // See if we can recursively simplify the LHS.
6583       unsigned Amt = RHSC->getZExtValue();
6584
6585       // Watch out for shift count overflow though.
6586       if (Amt >= Mask.getBitWidth()) break;
6587       APInt NewMask = Mask << Amt;
6588       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6589         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6590                            SimplifyLHS, V.getOperand(1));
6591     }
6592   }
6593   return SDValue();
6594 }
6595
6596 /// If the result of a wider load is shifted to right of N  bits and then
6597 /// truncated to a narrower type and where N is a multiple of number of bits of
6598 /// the narrower type, transform it to a narrower load from address + N / num of
6599 /// bits of new type. If the result is to be extended, also fold the extension
6600 /// to form a extending load.
6601 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6602   unsigned Opc = N->getOpcode();
6603
6604   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6605   SDValue N0 = N->getOperand(0);
6606   EVT VT = N->getValueType(0);
6607   EVT ExtVT = VT;
6608
6609   // This transformation isn't valid for vector loads.
6610   if (VT.isVector())
6611     return SDValue();
6612
6613   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6614   // extended to VT.
6615   if (Opc == ISD::SIGN_EXTEND_INREG) {
6616     ExtType = ISD::SEXTLOAD;
6617     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6618   } else if (Opc == ISD::SRL) {
6619     // Another special-case: SRL is basically zero-extending a narrower value.
6620     ExtType = ISD::ZEXTLOAD;
6621     N0 = SDValue(N, 0);
6622     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6623     if (!N01) return SDValue();
6624     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6625                               VT.getSizeInBits() - N01->getZExtValue());
6626   }
6627   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6628     return SDValue();
6629
6630   unsigned EVTBits = ExtVT.getSizeInBits();
6631
6632   // Do not generate loads of non-round integer types since these can
6633   // be expensive (and would be wrong if the type is not byte sized).
6634   if (!ExtVT.isRound())
6635     return SDValue();
6636
6637   unsigned ShAmt = 0;
6638   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6639     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6640       ShAmt = N01->getZExtValue();
6641       // Is the shift amount a multiple of size of VT?
6642       if ((ShAmt & (EVTBits-1)) == 0) {
6643         N0 = N0.getOperand(0);
6644         // Is the load width a multiple of size of VT?
6645         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6646           return SDValue();
6647       }
6648
6649       // At this point, we must have a load or else we can't do the transform.
6650       if (!isa<LoadSDNode>(N0)) return SDValue();
6651
6652       // Because a SRL must be assumed to *need* to zero-extend the high bits
6653       // (as opposed to anyext the high bits), we can't combine the zextload
6654       // lowering of SRL and an sextload.
6655       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6656         return SDValue();
6657
6658       // If the shift amount is larger than the input type then we're not
6659       // accessing any of the loaded bytes.  If the load was a zextload/extload
6660       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6661       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6662         return SDValue();
6663     }
6664   }
6665
6666   // If the load is shifted left (and the result isn't shifted back right),
6667   // we can fold the truncate through the shift.
6668   unsigned ShLeftAmt = 0;
6669   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6670       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6671     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6672       ShLeftAmt = N01->getZExtValue();
6673       N0 = N0.getOperand(0);
6674     }
6675   }
6676
6677   // If we haven't found a load, we can't narrow it.  Don't transform one with
6678   // multiple uses, this would require adding a new load.
6679   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6680     return SDValue();
6681
6682   // Don't change the width of a volatile load.
6683   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6684   if (LN0->isVolatile())
6685     return SDValue();
6686
6687   // Verify that we are actually reducing a load width here.
6688   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6689     return SDValue();
6690
6691   // For the transform to be legal, the load must produce only two values
6692   // (the value loaded and the chain).  Don't transform a pre-increment
6693   // load, for example, which produces an extra value.  Otherwise the
6694   // transformation is not equivalent, and the downstream logic to replace
6695   // uses gets things wrong.
6696   if (LN0->getNumValues() > 2)
6697     return SDValue();
6698
6699   // If the load that we're shrinking is an extload and we're not just
6700   // discarding the extension we can't simply shrink the load. Bail.
6701   // TODO: It would be possible to merge the extensions in some cases.
6702   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6703       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6704     return SDValue();
6705
6706   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6707     return SDValue();
6708
6709   EVT PtrType = N0.getOperand(1).getValueType();
6710
6711   if (PtrType == MVT::Untyped || PtrType.isExtended())
6712     // It's not possible to generate a constant of extended or untyped type.
6713     return SDValue();
6714
6715   // For big endian targets, we need to adjust the offset to the pointer to
6716   // load the correct bytes.
6717   if (DAG.getDataLayout().isBigEndian()) {
6718     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6719     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6720     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6721   }
6722
6723   uint64_t PtrOff = ShAmt / 8;
6724   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6725   SDLoc DL(LN0);
6726   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6727                                PtrType, LN0->getBasePtr(),
6728                                DAG.getConstant(PtrOff, DL, PtrType));
6729   AddToWorklist(NewPtr.getNode());
6730
6731   SDValue Load;
6732   if (ExtType == ISD::NON_EXTLOAD)
6733     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6734                         LN0->getPointerInfo().getWithOffset(PtrOff),
6735                         LN0->isVolatile(), LN0->isNonTemporal(),
6736                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6737   else
6738     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6739                           LN0->getPointerInfo().getWithOffset(PtrOff),
6740                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6741                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6742
6743   // Replace the old load's chain with the new load's chain.
6744   WorklistRemover DeadNodes(*this);
6745   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6746
6747   // Shift the result left, if we've swallowed a left shift.
6748   SDValue Result = Load;
6749   if (ShLeftAmt != 0) {
6750     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6751     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6752       ShImmTy = VT;
6753     // If the shift amount is as large as the result size (but, presumably,
6754     // no larger than the source) then the useful bits of the result are
6755     // zero; we can't simply return the shortened shift, because the result
6756     // of that operation is undefined.
6757     SDLoc DL(N0);
6758     if (ShLeftAmt >= VT.getSizeInBits())
6759       Result = DAG.getConstant(0, DL, VT);
6760     else
6761       Result = DAG.getNode(ISD::SHL, DL, VT,
6762                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6763   }
6764
6765   // Return the new loaded value.
6766   return Result;
6767 }
6768
6769 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6770   SDValue N0 = N->getOperand(0);
6771   SDValue N1 = N->getOperand(1);
6772   EVT VT = N->getValueType(0);
6773   EVT EVT = cast<VTSDNode>(N1)->getVT();
6774   unsigned VTBits = VT.getScalarType().getSizeInBits();
6775   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6776
6777   // fold (sext_in_reg c1) -> c1
6778   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6779     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6780
6781   // If the input is already sign extended, just drop the extension.
6782   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6783     return N0;
6784
6785   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6786   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6787       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6788     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6789                        N0.getOperand(0), N1);
6790
6791   // fold (sext_in_reg (sext x)) -> (sext x)
6792   // fold (sext_in_reg (aext x)) -> (sext x)
6793   // if x is small enough.
6794   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6795     SDValue N00 = N0.getOperand(0);
6796     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6797         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6798       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6799   }
6800
6801   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6802   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6803     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6804
6805   // fold operands of sext_in_reg based on knowledge that the top bits are not
6806   // demanded.
6807   if (SimplifyDemandedBits(SDValue(N, 0)))
6808     return SDValue(N, 0);
6809
6810   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6811   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6812   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6813     return NarrowLoad;
6814
6815   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6816   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6817   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6818   if (N0.getOpcode() == ISD::SRL) {
6819     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6820       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6821         // We can turn this into an SRA iff the input to the SRL is already sign
6822         // extended enough.
6823         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6824         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6825           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6826                              N0.getOperand(0), N0.getOperand(1));
6827       }
6828   }
6829
6830   // fold (sext_inreg (extload x)) -> (sextload x)
6831   if (ISD::isEXTLoad(N0.getNode()) &&
6832       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6833       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6834       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6835        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6836     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6837     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6838                                      LN0->getChain(),
6839                                      LN0->getBasePtr(), EVT,
6840                                      LN0->getMemOperand());
6841     CombineTo(N, ExtLoad);
6842     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6843     AddToWorklist(ExtLoad.getNode());
6844     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6845   }
6846   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6847   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6848       N0.hasOneUse() &&
6849       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6850       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6851        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6852     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6853     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6854                                      LN0->getChain(),
6855                                      LN0->getBasePtr(), EVT,
6856                                      LN0->getMemOperand());
6857     CombineTo(N, ExtLoad);
6858     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6859     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6860   }
6861
6862   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6863   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6864     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6865                                        N0.getOperand(1), false);
6866     if (BSwap.getNode())
6867       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6868                          BSwap, N1);
6869   }
6870
6871   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6872   // into a build_vector.
6873   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6874     SmallVector<SDValue, 8> Elts;
6875     unsigned NumElts = N0->getNumOperands();
6876     unsigned ShAmt = VTBits - EVTBits;
6877
6878     for (unsigned i = 0; i != NumElts; ++i) {
6879       SDValue Op = N0->getOperand(i);
6880       if (Op->getOpcode() == ISD::UNDEF) {
6881         Elts.push_back(Op);
6882         continue;
6883       }
6884
6885       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6886       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6887       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6888                                      SDLoc(Op), Op.getValueType()));
6889     }
6890
6891     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6892   }
6893
6894   return SDValue();
6895 }
6896
6897 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6898   SDValue N0 = N->getOperand(0);
6899   EVT VT = N->getValueType(0);
6900
6901   if (N0.getOpcode() == ISD::UNDEF)
6902     return DAG.getUNDEF(VT);
6903
6904   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6905                                               LegalOperations))
6906     return SDValue(Res, 0);
6907
6908   return SDValue();
6909 }
6910
6911 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6912   SDValue N0 = N->getOperand(0);
6913   EVT VT = N->getValueType(0);
6914   bool isLE = DAG.getDataLayout().isLittleEndian();
6915
6916   // noop truncate
6917   if (N0.getValueType() == N->getValueType(0))
6918     return N0;
6919   // fold (truncate c1) -> c1
6920   if (isConstantIntBuildVectorOrConstantInt(N0))
6921     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6922   // fold (truncate (truncate x)) -> (truncate x)
6923   if (N0.getOpcode() == ISD::TRUNCATE)
6924     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6925   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6926   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6927       N0.getOpcode() == ISD::SIGN_EXTEND ||
6928       N0.getOpcode() == ISD::ANY_EXTEND) {
6929     if (N0.getOperand(0).getValueType().bitsLT(VT))
6930       // if the source is smaller than the dest, we still need an extend
6931       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6932                          N0.getOperand(0));
6933     if (N0.getOperand(0).getValueType().bitsGT(VT))
6934       // if the source is larger than the dest, than we just need the truncate
6935       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6936     // if the source and dest are the same type, we can drop both the extend
6937     // and the truncate.
6938     return N0.getOperand(0);
6939   }
6940
6941   // Fold extract-and-trunc into a narrow extract. For example:
6942   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6943   //   i32 y = TRUNCATE(i64 x)
6944   //        -- becomes --
6945   //   v16i8 b = BITCAST (v2i64 val)
6946   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6947   //
6948   // Note: We only run this optimization after type legalization (which often
6949   // creates this pattern) and before operation legalization after which
6950   // we need to be more careful about the vector instructions that we generate.
6951   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6952       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6953
6954     EVT VecTy = N0.getOperand(0).getValueType();
6955     EVT ExTy = N0.getValueType();
6956     EVT TrTy = N->getValueType(0);
6957
6958     unsigned NumElem = VecTy.getVectorNumElements();
6959     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6960
6961     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6962     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6963
6964     SDValue EltNo = N0->getOperand(1);
6965     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6966       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6967       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6968       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6969
6970       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6971                               NVT, N0.getOperand(0));
6972
6973       SDLoc DL(N);
6974       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6975                          DL, TrTy, V,
6976                          DAG.getConstant(Index, DL, IndexTy));
6977     }
6978   }
6979
6980   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6981   if (N0.getOpcode() == ISD::SELECT) {
6982     EVT SrcVT = N0.getValueType();
6983     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6984         TLI.isTruncateFree(SrcVT, VT)) {
6985       SDLoc SL(N0);
6986       SDValue Cond = N0.getOperand(0);
6987       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6988       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6989       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6990     }
6991   }
6992
6993   // Fold a series of buildvector, bitcast, and truncate if possible.
6994   // For example fold
6995   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6996   //   (2xi32 (buildvector x, y)).
6997   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6998       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6999       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7000       N0.getOperand(0).hasOneUse()) {
7001
7002     SDValue BuildVect = N0.getOperand(0);
7003     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7004     EVT TruncVecEltTy = VT.getVectorElementType();
7005
7006     // Check that the element types match.
7007     if (BuildVectEltTy == TruncVecEltTy) {
7008       // Now we only need to compute the offset of the truncated elements.
7009       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7010       unsigned TruncVecNumElts = VT.getVectorNumElements();
7011       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7012
7013       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7014              "Invalid number of elements");
7015
7016       SmallVector<SDValue, 8> Opnds;
7017       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7018         Opnds.push_back(BuildVect.getOperand(i));
7019
7020       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7021     }
7022   }
7023
7024   // See if we can simplify the input to this truncate through knowledge that
7025   // only the low bits are being used.
7026   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7027   // Currently we only perform this optimization on scalars because vectors
7028   // may have different active low bits.
7029   if (!VT.isVector()) {
7030     SDValue Shorter =
7031       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7032                                                VT.getSizeInBits()));
7033     if (Shorter.getNode())
7034       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7035   }
7036   // fold (truncate (load x)) -> (smaller load x)
7037   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7038   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7039     if (SDValue Reduced = ReduceLoadWidth(N))
7040       return Reduced;
7041
7042     // Handle the case where the load remains an extending load even
7043     // after truncation.
7044     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7045       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7046       if (!LN0->isVolatile() &&
7047           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7048         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7049                                          VT, LN0->getChain(), LN0->getBasePtr(),
7050                                          LN0->getMemoryVT(),
7051                                          LN0->getMemOperand());
7052         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7053         return NewLoad;
7054       }
7055     }
7056   }
7057   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7058   // where ... are all 'undef'.
7059   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7060     SmallVector<EVT, 8> VTs;
7061     SDValue V;
7062     unsigned Idx = 0;
7063     unsigned NumDefs = 0;
7064
7065     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7066       SDValue X = N0.getOperand(i);
7067       if (X.getOpcode() != ISD::UNDEF) {
7068         V = X;
7069         Idx = i;
7070         NumDefs++;
7071       }
7072       // Stop if more than one members are non-undef.
7073       if (NumDefs > 1)
7074         break;
7075       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7076                                      VT.getVectorElementType(),
7077                                      X.getValueType().getVectorNumElements()));
7078     }
7079
7080     if (NumDefs == 0)
7081       return DAG.getUNDEF(VT);
7082
7083     if (NumDefs == 1) {
7084       assert(V.getNode() && "The single defined operand is empty!");
7085       SmallVector<SDValue, 8> Opnds;
7086       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7087         if (i != Idx) {
7088           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7089           continue;
7090         }
7091         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7092         AddToWorklist(NV.getNode());
7093         Opnds.push_back(NV);
7094       }
7095       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7096     }
7097   }
7098
7099   // Simplify the operands using demanded-bits information.
7100   if (!VT.isVector() &&
7101       SimplifyDemandedBits(SDValue(N, 0)))
7102     return SDValue(N, 0);
7103
7104   return SDValue();
7105 }
7106
7107 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7108   SDValue Elt = N->getOperand(i);
7109   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7110     return Elt.getNode();
7111   return Elt.getOperand(Elt.getResNo()).getNode();
7112 }
7113
7114 /// build_pair (load, load) -> load
7115 /// if load locations are consecutive.
7116 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7117   assert(N->getOpcode() == ISD::BUILD_PAIR);
7118
7119   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7120   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7121   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7122       LD1->getAddressSpace() != LD2->getAddressSpace())
7123     return SDValue();
7124   EVT LD1VT = LD1->getValueType(0);
7125
7126   if (ISD::isNON_EXTLoad(LD2) &&
7127       LD2->hasOneUse() &&
7128       // If both are volatile this would reduce the number of volatile loads.
7129       // If one is volatile it might be ok, but play conservative and bail out.
7130       !LD1->isVolatile() &&
7131       !LD2->isVolatile() &&
7132       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7133     unsigned Align = LD1->getAlignment();
7134     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7135         VT.getTypeForEVT(*DAG.getContext()));
7136
7137     if (NewAlign <= Align &&
7138         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7139       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7140                          LD1->getBasePtr(), LD1->getPointerInfo(),
7141                          false, false, false, Align);
7142   }
7143
7144   return SDValue();
7145 }
7146
7147 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7148   SDValue N0 = N->getOperand(0);
7149   EVT VT = N->getValueType(0);
7150
7151   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7152   // Only do this before legalize, since afterward the target may be depending
7153   // on the bitconvert.
7154   // First check to see if this is all constant.
7155   if (!LegalTypes &&
7156       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7157       VT.isVector()) {
7158     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7159
7160     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7161     assert(!DestEltVT.isVector() &&
7162            "Element type of vector ValueType must not be vector!");
7163     if (isSimple)
7164       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7165   }
7166
7167   // If the input is a constant, let getNode fold it.
7168   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7169     // If we can't allow illegal operations, we need to check that this is just
7170     // a fp -> int or int -> conversion and that the resulting operation will
7171     // be legal.
7172     if (!LegalOperations ||
7173         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7174          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7175         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7176          TLI.isOperationLegal(ISD::Constant, VT)))
7177       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7178   }
7179
7180   // (conv (conv x, t1), t2) -> (conv x, t2)
7181   if (N0.getOpcode() == ISD::BITCAST)
7182     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7183                        N0.getOperand(0));
7184
7185   // fold (conv (load x)) -> (load (conv*)x)
7186   // If the resultant load doesn't need a higher alignment than the original!
7187   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7188       // Do not change the width of a volatile load.
7189       !cast<LoadSDNode>(N0)->isVolatile() &&
7190       // Do not remove the cast if the types differ in endian layout.
7191       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7192           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7193       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7194       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7195     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7196     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7197         VT.getTypeForEVT(*DAG.getContext()));
7198     unsigned OrigAlign = LN0->getAlignment();
7199
7200     if (Align <= OrigAlign) {
7201       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7202                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7203                                  LN0->isVolatile(), LN0->isNonTemporal(),
7204                                  LN0->isInvariant(), OrigAlign,
7205                                  LN0->getAAInfo());
7206       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7207       return Load;
7208     }
7209   }
7210
7211   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7212   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7213   // This often reduces constant pool loads.
7214   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7215        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7216       N0.getNode()->hasOneUse() && VT.isInteger() &&
7217       !VT.isVector() && !N0.getValueType().isVector()) {
7218     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7219                                   N0.getOperand(0));
7220     AddToWorklist(NewConv.getNode());
7221
7222     SDLoc DL(N);
7223     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7224     if (N0.getOpcode() == ISD::FNEG)
7225       return DAG.getNode(ISD::XOR, DL, VT,
7226                          NewConv, DAG.getConstant(SignBit, DL, VT));
7227     assert(N0.getOpcode() == ISD::FABS);
7228     return DAG.getNode(ISD::AND, DL, VT,
7229                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7230   }
7231
7232   // fold (bitconvert (fcopysign cst, x)) ->
7233   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7234   // Note that we don't handle (copysign x, cst) because this can always be
7235   // folded to an fneg or fabs.
7236   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7237       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7238       VT.isInteger() && !VT.isVector()) {
7239     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7240     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7241     if (isTypeLegal(IntXVT)) {
7242       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7243                               IntXVT, N0.getOperand(1));
7244       AddToWorklist(X.getNode());
7245
7246       // If X has a different width than the result/lhs, sext it or truncate it.
7247       unsigned VTWidth = VT.getSizeInBits();
7248       if (OrigXWidth < VTWidth) {
7249         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7250         AddToWorklist(X.getNode());
7251       } else if (OrigXWidth > VTWidth) {
7252         // To get the sign bit in the right place, we have to shift it right
7253         // before truncating.
7254         SDLoc DL(X);
7255         X = DAG.getNode(ISD::SRL, DL,
7256                         X.getValueType(), X,
7257                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7258                                         X.getValueType()));
7259         AddToWorklist(X.getNode());
7260         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7261         AddToWorklist(X.getNode());
7262       }
7263
7264       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7265       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7266                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7267       AddToWorklist(X.getNode());
7268
7269       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7270                                 VT, N0.getOperand(0));
7271       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7272                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7273       AddToWorklist(Cst.getNode());
7274
7275       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7276     }
7277   }
7278
7279   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7280   if (N0.getOpcode() == ISD::BUILD_PAIR)
7281     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7282       return CombineLD;
7283
7284   // Remove double bitcasts from shuffles - this is often a legacy of
7285   // XformToShuffleWithZero being used to combine bitmaskings (of
7286   // float vectors bitcast to integer vectors) into shuffles.
7287   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7288   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7289       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7290       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7291       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7292     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7293
7294     // If operands are a bitcast, peek through if it casts the original VT.
7295     // If operands are a constant, just bitcast back to original VT.
7296     auto PeekThroughBitcast = [&](SDValue Op) {
7297       if (Op.getOpcode() == ISD::BITCAST &&
7298           Op.getOperand(0).getValueType() == VT)
7299         return SDValue(Op.getOperand(0));
7300       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7301           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7302         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7303       return SDValue();
7304     };
7305
7306     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7307     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7308     if (!(SV0 && SV1))
7309       return SDValue();
7310
7311     int MaskScale =
7312         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7313     SmallVector<int, 8> NewMask;
7314     for (int M : SVN->getMask())
7315       for (int i = 0; i != MaskScale; ++i)
7316         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7317
7318     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7319     if (!LegalMask) {
7320       std::swap(SV0, SV1);
7321       ShuffleVectorSDNode::commuteMask(NewMask);
7322       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7323     }
7324
7325     if (LegalMask)
7326       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7327   }
7328
7329   return SDValue();
7330 }
7331
7332 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7333   EVT VT = N->getValueType(0);
7334   return CombineConsecutiveLoads(N, VT);
7335 }
7336
7337 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7338 /// operands. DstEltVT indicates the destination element value type.
7339 SDValue DAGCombiner::
7340 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7341   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7342
7343   // If this is already the right type, we're done.
7344   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7345
7346   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7347   unsigned DstBitSize = DstEltVT.getSizeInBits();
7348
7349   // If this is a conversion of N elements of one type to N elements of another
7350   // type, convert each element.  This handles FP<->INT cases.
7351   if (SrcBitSize == DstBitSize) {
7352     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7353                               BV->getValueType(0).getVectorNumElements());
7354
7355     // Due to the FP element handling below calling this routine recursively,
7356     // we can end up with a scalar-to-vector node here.
7357     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7358       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7359                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7360                                      DstEltVT, BV->getOperand(0)));
7361
7362     SmallVector<SDValue, 8> Ops;
7363     for (SDValue Op : BV->op_values()) {
7364       // If the vector element type is not legal, the BUILD_VECTOR operands
7365       // are promoted and implicitly truncated.  Make that explicit here.
7366       if (Op.getValueType() != SrcEltVT)
7367         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7368       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7369                                 DstEltVT, Op));
7370       AddToWorklist(Ops.back().getNode());
7371     }
7372     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7373   }
7374
7375   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7376   // handle annoying details of growing/shrinking FP values, we convert them to
7377   // int first.
7378   if (SrcEltVT.isFloatingPoint()) {
7379     // Convert the input float vector to a int vector where the elements are the
7380     // same sizes.
7381     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7382     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7383     SrcEltVT = IntVT;
7384   }
7385
7386   // Now we know the input is an integer vector.  If the output is a FP type,
7387   // convert to integer first, then to FP of the right size.
7388   if (DstEltVT.isFloatingPoint()) {
7389     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7390     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7391
7392     // Next, convert to FP elements of the same size.
7393     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7394   }
7395
7396   SDLoc DL(BV);
7397
7398   // Okay, we know the src/dst types are both integers of differing types.
7399   // Handling growing first.
7400   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7401   if (SrcBitSize < DstBitSize) {
7402     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7403
7404     SmallVector<SDValue, 8> Ops;
7405     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7406          i += NumInputsPerOutput) {
7407       bool isLE = DAG.getDataLayout().isLittleEndian();
7408       APInt NewBits = APInt(DstBitSize, 0);
7409       bool EltIsUndef = true;
7410       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7411         // Shift the previously computed bits over.
7412         NewBits <<= SrcBitSize;
7413         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7414         if (Op.getOpcode() == ISD::UNDEF) continue;
7415         EltIsUndef = false;
7416
7417         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7418                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7419       }
7420
7421       if (EltIsUndef)
7422         Ops.push_back(DAG.getUNDEF(DstEltVT));
7423       else
7424         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7425     }
7426
7427     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7428     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7429   }
7430
7431   // Finally, this must be the case where we are shrinking elements: each input
7432   // turns into multiple outputs.
7433   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7434   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7435                             NumOutputsPerInput*BV->getNumOperands());
7436   SmallVector<SDValue, 8> Ops;
7437
7438   for (const SDValue &Op : BV->op_values()) {
7439     if (Op.getOpcode() == ISD::UNDEF) {
7440       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7441       continue;
7442     }
7443
7444     APInt OpVal = cast<ConstantSDNode>(Op)->
7445                   getAPIntValue().zextOrTrunc(SrcBitSize);
7446
7447     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7448       APInt ThisVal = OpVal.trunc(DstBitSize);
7449       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7450       OpVal = OpVal.lshr(DstBitSize);
7451     }
7452
7453     // For big endian targets, swap the order of the pieces of each element.
7454     if (DAG.getDataLayout().isBigEndian())
7455       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7456   }
7457
7458   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7459 }
7460
7461 /// Try to perform FMA combining on a given FADD node.
7462 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7463   SDValue N0 = N->getOperand(0);
7464   SDValue N1 = N->getOperand(1);
7465   EVT VT = N->getValueType(0);
7466   SDLoc SL(N);
7467
7468   const TargetOptions &Options = DAG.getTarget().Options;
7469   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7470                        Options.UnsafeFPMath);
7471
7472   // Floating-point multiply-add with intermediate rounding.
7473   bool HasFMAD = (LegalOperations &&
7474                   TLI.isOperationLegal(ISD::FMAD, VT));
7475
7476   // Floating-point multiply-add without intermediate rounding.
7477   bool HasFMA = ((!LegalOperations ||
7478                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7479                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7480                  UnsafeFPMath);
7481
7482   // No valid opcode, do not combine.
7483   if (!HasFMAD && !HasFMA)
7484     return SDValue();
7485
7486   // Always prefer FMAD to FMA for precision.
7487   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7488   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7489   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7490
7491   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7492   // prefer to fold the multiply with fewer uses.
7493   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7494       N1.getOpcode() == ISD::FMUL) {
7495     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7496       std::swap(N0, N1);
7497   }
7498
7499   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7500   if (N0.getOpcode() == ISD::FMUL &&
7501       (Aggressive || N0->hasOneUse())) {
7502     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7503                        N0.getOperand(0), N0.getOperand(1), N1);
7504   }
7505
7506   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7507   // Note: Commutes FADD operands.
7508   if (N1.getOpcode() == ISD::FMUL &&
7509       (Aggressive || N1->hasOneUse())) {
7510     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7511                        N1.getOperand(0), N1.getOperand(1), N0);
7512   }
7513
7514   // Look through FP_EXTEND nodes to do more combining.
7515   if (UnsafeFPMath && LookThroughFPExt) {
7516     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7517     if (N0.getOpcode() == ISD::FP_EXTEND) {
7518       SDValue N00 = N0.getOperand(0);
7519       if (N00.getOpcode() == ISD::FMUL)
7520         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7521                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7522                                        N00.getOperand(0)),
7523                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7524                                        N00.getOperand(1)), N1);
7525     }
7526
7527     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7528     // Note: Commutes FADD operands.
7529     if (N1.getOpcode() == ISD::FP_EXTEND) {
7530       SDValue N10 = N1.getOperand(0);
7531       if (N10.getOpcode() == ISD::FMUL)
7532         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7533                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7534                                        N10.getOperand(0)),
7535                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7536                                        N10.getOperand(1)), N0);
7537     }
7538   }
7539
7540   // More folding opportunities when target permits.
7541   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7542     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7543     if (N0.getOpcode() == PreferredFusedOpcode &&
7544         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7545       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7546                          N0.getOperand(0), N0.getOperand(1),
7547                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7548                                      N0.getOperand(2).getOperand(0),
7549                                      N0.getOperand(2).getOperand(1),
7550                                      N1));
7551     }
7552
7553     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7554     if (N1->getOpcode() == PreferredFusedOpcode &&
7555         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7556       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7557                          N1.getOperand(0), N1.getOperand(1),
7558                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7559                                      N1.getOperand(2).getOperand(0),
7560                                      N1.getOperand(2).getOperand(1),
7561                                      N0));
7562     }
7563
7564     if (UnsafeFPMath && LookThroughFPExt) {
7565       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7566       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7567       auto FoldFAddFMAFPExtFMul = [&] (
7568           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7569         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7570                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7571                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7572                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7573                                        Z));
7574       };
7575       if (N0.getOpcode() == PreferredFusedOpcode) {
7576         SDValue N02 = N0.getOperand(2);
7577         if (N02.getOpcode() == ISD::FP_EXTEND) {
7578           SDValue N020 = N02.getOperand(0);
7579           if (N020.getOpcode() == ISD::FMUL)
7580             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7581                                         N020.getOperand(0), N020.getOperand(1),
7582                                         N1);
7583         }
7584       }
7585
7586       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7587       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7588       // FIXME: This turns two single-precision and one double-precision
7589       // operation into two double-precision operations, which might not be
7590       // interesting for all targets, especially GPUs.
7591       auto FoldFAddFPExtFMAFMul = [&] (
7592           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7593         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7594                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7595                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7596                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7597                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7598                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7599                                        Z));
7600       };
7601       if (N0.getOpcode() == ISD::FP_EXTEND) {
7602         SDValue N00 = N0.getOperand(0);
7603         if (N00.getOpcode() == PreferredFusedOpcode) {
7604           SDValue N002 = N00.getOperand(2);
7605           if (N002.getOpcode() == ISD::FMUL)
7606             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7607                                         N002.getOperand(0), N002.getOperand(1),
7608                                         N1);
7609         }
7610       }
7611
7612       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7613       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7614       if (N1.getOpcode() == PreferredFusedOpcode) {
7615         SDValue N12 = N1.getOperand(2);
7616         if (N12.getOpcode() == ISD::FP_EXTEND) {
7617           SDValue N120 = N12.getOperand(0);
7618           if (N120.getOpcode() == ISD::FMUL)
7619             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7620                                         N120.getOperand(0), N120.getOperand(1),
7621                                         N0);
7622         }
7623       }
7624
7625       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7626       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7627       // FIXME: This turns two single-precision and one double-precision
7628       // operation into two double-precision operations, which might not be
7629       // interesting for all targets, especially GPUs.
7630       if (N1.getOpcode() == ISD::FP_EXTEND) {
7631         SDValue N10 = N1.getOperand(0);
7632         if (N10.getOpcode() == PreferredFusedOpcode) {
7633           SDValue N102 = N10.getOperand(2);
7634           if (N102.getOpcode() == ISD::FMUL)
7635             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7636                                         N102.getOperand(0), N102.getOperand(1),
7637                                         N0);
7638         }
7639       }
7640     }
7641   }
7642
7643   return SDValue();
7644 }
7645
7646 /// Try to perform FMA combining on a given FSUB node.
7647 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7648   SDValue N0 = N->getOperand(0);
7649   SDValue N1 = N->getOperand(1);
7650   EVT VT = N->getValueType(0);
7651   SDLoc SL(N);
7652
7653   const TargetOptions &Options = DAG.getTarget().Options;
7654   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7655                        Options.UnsafeFPMath);
7656
7657   // Floating-point multiply-add with intermediate rounding.
7658   bool HasFMAD = (LegalOperations &&
7659                   TLI.isOperationLegal(ISD::FMAD, VT));
7660
7661   // Floating-point multiply-add without intermediate rounding.
7662   bool HasFMA = ((!LegalOperations ||
7663                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7664                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7665                  UnsafeFPMath);
7666
7667   // No valid opcode, do not combine.
7668   if (!HasFMAD && !HasFMA)
7669     return SDValue();
7670
7671   // Always prefer FMAD to FMA for precision.
7672   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7673   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7674   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7675
7676   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7677   if (N0.getOpcode() == ISD::FMUL &&
7678       (Aggressive || N0->hasOneUse())) {
7679     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7680                        N0.getOperand(0), N0.getOperand(1),
7681                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7682   }
7683
7684   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7685   // Note: Commutes FSUB operands.
7686   if (N1.getOpcode() == ISD::FMUL &&
7687       (Aggressive || N1->hasOneUse()))
7688     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7689                        DAG.getNode(ISD::FNEG, SL, VT,
7690                                    N1.getOperand(0)),
7691                        N1.getOperand(1), N0);
7692
7693   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7694   if (N0.getOpcode() == ISD::FNEG &&
7695       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7696       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7697     SDValue N00 = N0.getOperand(0).getOperand(0);
7698     SDValue N01 = N0.getOperand(0).getOperand(1);
7699     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7700                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7701                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7702   }
7703
7704   // Look through FP_EXTEND nodes to do more combining.
7705   if (UnsafeFPMath && LookThroughFPExt) {
7706     // fold (fsub (fpext (fmul x, y)), z)
7707     //   -> (fma (fpext x), (fpext y), (fneg z))
7708     if (N0.getOpcode() == ISD::FP_EXTEND) {
7709       SDValue N00 = N0.getOperand(0);
7710       if (N00.getOpcode() == ISD::FMUL)
7711         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7712                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7713                                        N00.getOperand(0)),
7714                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7715                                        N00.getOperand(1)),
7716                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7717     }
7718
7719     // fold (fsub x, (fpext (fmul y, z)))
7720     //   -> (fma (fneg (fpext y)), (fpext z), x)
7721     // Note: Commutes FSUB operands.
7722     if (N1.getOpcode() == ISD::FP_EXTEND) {
7723       SDValue N10 = N1.getOperand(0);
7724       if (N10.getOpcode() == ISD::FMUL)
7725         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7726                            DAG.getNode(ISD::FNEG, SL, VT,
7727                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                                    N10.getOperand(0))),
7729                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7730                                        N10.getOperand(1)),
7731                            N0);
7732     }
7733
7734     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7735     //   -> (fneg (fma (fpext x), (fpext y), z))
7736     // Note: This could be removed with appropriate canonicalization of the
7737     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7738     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7739     // from implementing the canonicalization in visitFSUB.
7740     if (N0.getOpcode() == ISD::FP_EXTEND) {
7741       SDValue N00 = N0.getOperand(0);
7742       if (N00.getOpcode() == ISD::FNEG) {
7743         SDValue N000 = N00.getOperand(0);
7744         if (N000.getOpcode() == ISD::FMUL) {
7745           return DAG.getNode(ISD::FNEG, SL, VT,
7746                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7747                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7748                                                      N000.getOperand(0)),
7749                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7750                                                      N000.getOperand(1)),
7751                                          N1));
7752         }
7753       }
7754     }
7755
7756     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7757     //   -> (fneg (fma (fpext x)), (fpext y), z)
7758     // Note: This could be removed with appropriate canonicalization of the
7759     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7760     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7761     // from implementing the canonicalization in visitFSUB.
7762     if (N0.getOpcode() == ISD::FNEG) {
7763       SDValue N00 = N0.getOperand(0);
7764       if (N00.getOpcode() == ISD::FP_EXTEND) {
7765         SDValue N000 = N00.getOperand(0);
7766         if (N000.getOpcode() == ISD::FMUL) {
7767           return DAG.getNode(ISD::FNEG, SL, VT,
7768                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7769                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7770                                                      N000.getOperand(0)),
7771                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772                                                      N000.getOperand(1)),
7773                                          N1));
7774         }
7775       }
7776     }
7777
7778   }
7779
7780   // More folding opportunities when target permits.
7781   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7782     // fold (fsub (fma x, y, (fmul u, v)), z)
7783     //   -> (fma x, y (fma u, v, (fneg z)))
7784     if (N0.getOpcode() == PreferredFusedOpcode &&
7785         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7786       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7787                          N0.getOperand(0), N0.getOperand(1),
7788                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7789                                      N0.getOperand(2).getOperand(0),
7790                                      N0.getOperand(2).getOperand(1),
7791                                      DAG.getNode(ISD::FNEG, SL, VT,
7792                                                  N1)));
7793     }
7794
7795     // fold (fsub x, (fma y, z, (fmul u, v)))
7796     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7797     if (N1.getOpcode() == PreferredFusedOpcode &&
7798         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7799       SDValue N20 = N1.getOperand(2).getOperand(0);
7800       SDValue N21 = N1.getOperand(2).getOperand(1);
7801       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                          DAG.getNode(ISD::FNEG, SL, VT,
7803                                      N1.getOperand(0)),
7804                          N1.getOperand(1),
7805                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7806                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7807
7808                                      N21, N0));
7809     }
7810
7811     if (UnsafeFPMath && LookThroughFPExt) {
7812       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7813       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7814       if (N0.getOpcode() == PreferredFusedOpcode) {
7815         SDValue N02 = N0.getOperand(2);
7816         if (N02.getOpcode() == ISD::FP_EXTEND) {
7817           SDValue N020 = N02.getOperand(0);
7818           if (N020.getOpcode() == ISD::FMUL)
7819             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                                N0.getOperand(0), N0.getOperand(1),
7821                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7822                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7823                                                        N020.getOperand(0)),
7824                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7825                                                        N020.getOperand(1)),
7826                                            DAG.getNode(ISD::FNEG, SL, VT,
7827                                                        N1)));
7828         }
7829       }
7830
7831       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7832       //   -> (fma (fpext x), (fpext y),
7833       //           (fma (fpext u), (fpext v), (fneg z)))
7834       // FIXME: This turns two single-precision and one double-precision
7835       // operation into two double-precision operations, which might not be
7836       // interesting for all targets, especially GPUs.
7837       if (N0.getOpcode() == ISD::FP_EXTEND) {
7838         SDValue N00 = N0.getOperand(0);
7839         if (N00.getOpcode() == PreferredFusedOpcode) {
7840           SDValue N002 = N00.getOperand(2);
7841           if (N002.getOpcode() == ISD::FMUL)
7842             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7843                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7844                                            N00.getOperand(0)),
7845                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7846                                            N00.getOperand(1)),
7847                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7848                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7849                                                        N002.getOperand(0)),
7850                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7851                                                        N002.getOperand(1)),
7852                                            DAG.getNode(ISD::FNEG, SL, VT,
7853                                                        N1)));
7854         }
7855       }
7856
7857       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7858       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7859       if (N1.getOpcode() == PreferredFusedOpcode &&
7860         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7861         SDValue N120 = N1.getOperand(2).getOperand(0);
7862         if (N120.getOpcode() == ISD::FMUL) {
7863           SDValue N1200 = N120.getOperand(0);
7864           SDValue N1201 = N120.getOperand(1);
7865           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7866                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7867                              N1.getOperand(1),
7868                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7869                                          DAG.getNode(ISD::FNEG, SL, VT,
7870                                              DAG.getNode(ISD::FP_EXTEND, SL,
7871                                                          VT, N1200)),
7872                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7873                                                      N1201),
7874                                          N0));
7875         }
7876       }
7877
7878       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7879       //   -> (fma (fneg (fpext y)), (fpext z),
7880       //           (fma (fneg (fpext u)), (fpext v), x))
7881       // FIXME: This turns two single-precision and one double-precision
7882       // operation into two double-precision operations, which might not be
7883       // interesting for all targets, especially GPUs.
7884       if (N1.getOpcode() == ISD::FP_EXTEND &&
7885         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7886         SDValue N100 = N1.getOperand(0).getOperand(0);
7887         SDValue N101 = N1.getOperand(0).getOperand(1);
7888         SDValue N102 = N1.getOperand(0).getOperand(2);
7889         if (N102.getOpcode() == ISD::FMUL) {
7890           SDValue N1020 = N102.getOperand(0);
7891           SDValue N1021 = N102.getOperand(1);
7892           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7893                              DAG.getNode(ISD::FNEG, SL, VT,
7894                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7895                                                      N100)),
7896                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7897                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7898                                          DAG.getNode(ISD::FNEG, SL, VT,
7899                                              DAG.getNode(ISD::FP_EXTEND, SL,
7900                                                          VT, N1020)),
7901                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7902                                                      N1021),
7903                                          N0));
7904         }
7905       }
7906     }
7907   }
7908
7909   return SDValue();
7910 }
7911
7912 SDValue DAGCombiner::visitFADD(SDNode *N) {
7913   SDValue N0 = N->getOperand(0);
7914   SDValue N1 = N->getOperand(1);
7915   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7916   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7917   EVT VT = N->getValueType(0);
7918   SDLoc DL(N);
7919   const TargetOptions &Options = DAG.getTarget().Options;
7920
7921   // fold vector ops
7922   if (VT.isVector())
7923     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7924       return FoldedVOp;
7925
7926   // fold (fadd c1, c2) -> c1 + c2
7927   if (N0CFP && N1CFP)
7928     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7929
7930   // canonicalize constant to RHS
7931   if (N0CFP && !N1CFP)
7932     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7933
7934   // fold (fadd A, (fneg B)) -> (fsub A, B)
7935   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7936       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7937     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7938                        GetNegatedExpression(N1, DAG, LegalOperations));
7939
7940   // fold (fadd (fneg A), B) -> (fsub B, A)
7941   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7942       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7943     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7944                        GetNegatedExpression(N0, DAG, LegalOperations));
7945
7946   // If 'unsafe math' is enabled, fold lots of things.
7947   if (Options.UnsafeFPMath) {
7948     // No FP constant should be created after legalization as Instruction
7949     // Selection pass has a hard time dealing with FP constants.
7950     bool AllowNewConst = (Level < AfterLegalizeDAG);
7951
7952     // fold (fadd A, 0) -> A
7953     if (N1CFP && N1CFP->isZero())
7954       return N0;
7955
7956     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7957     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7958         isa<ConstantFPSDNode>(N0.getOperand(1)))
7959       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7960                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7961
7962     // If allowed, fold (fadd (fneg x), x) -> 0.0
7963     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7964       return DAG.getConstantFP(0.0, DL, VT);
7965
7966     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7967     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7968       return DAG.getConstantFP(0.0, DL, VT);
7969
7970     // We can fold chains of FADD's of the same value into multiplications.
7971     // This transform is not safe in general because we are reducing the number
7972     // of rounding steps.
7973     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7974       if (N0.getOpcode() == ISD::FMUL) {
7975         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7976         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7977
7978         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7979         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7980           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7981                                        DAG.getConstantFP(1.0, DL, VT));
7982           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7983         }
7984
7985         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7986         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7987             N1.getOperand(0) == N1.getOperand(1) &&
7988             N0.getOperand(0) == N1.getOperand(0)) {
7989           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7990                                        DAG.getConstantFP(2.0, DL, VT));
7991           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7992         }
7993       }
7994
7995       if (N1.getOpcode() == ISD::FMUL) {
7996         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7997         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7998
7999         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8000         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8001           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8002                                        DAG.getConstantFP(1.0, DL, VT));
8003           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
8004         }
8005
8006         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8007         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8008             N0.getOperand(0) == N0.getOperand(1) &&
8009             N1.getOperand(0) == N0.getOperand(0)) {
8010           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8011                                        DAG.getConstantFP(2.0, DL, VT));
8012           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8013         }
8014       }
8015
8016       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8017         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8018         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8019         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8020             (N0.getOperand(0) == N1)) {
8021           return DAG.getNode(ISD::FMUL, DL, VT,
8022                              N1, DAG.getConstantFP(3.0, DL, VT));
8023         }
8024       }
8025
8026       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8027         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8028         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8029         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8030             N1.getOperand(0) == N0) {
8031           return DAG.getNode(ISD::FMUL, DL, VT,
8032                              N0, DAG.getConstantFP(3.0, DL, VT));
8033         }
8034       }
8035
8036       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8037       if (AllowNewConst &&
8038           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8039           N0.getOperand(0) == N0.getOperand(1) &&
8040           N1.getOperand(0) == N1.getOperand(1) &&
8041           N0.getOperand(0) == N1.getOperand(0)) {
8042         return DAG.getNode(ISD::FMUL, DL, VT,
8043                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8044       }
8045     }
8046   } // enable-unsafe-fp-math
8047
8048   // FADD -> FMA combines:
8049   if (SDValue Fused = visitFADDForFMACombine(N)) {
8050     AddToWorklist(Fused.getNode());
8051     return Fused;
8052   }
8053
8054   return SDValue();
8055 }
8056
8057 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8058   SDValue N0 = N->getOperand(0);
8059   SDValue N1 = N->getOperand(1);
8060   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8061   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8062   EVT VT = N->getValueType(0);
8063   SDLoc dl(N);
8064   const TargetOptions &Options = DAG.getTarget().Options;
8065
8066   // fold vector ops
8067   if (VT.isVector())
8068     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8069       return FoldedVOp;
8070
8071   // fold (fsub c1, c2) -> c1-c2
8072   if (N0CFP && N1CFP)
8073     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8074
8075   // fold (fsub A, (fneg B)) -> (fadd A, B)
8076   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8077     return DAG.getNode(ISD::FADD, dl, VT, N0,
8078                        GetNegatedExpression(N1, DAG, LegalOperations));
8079
8080   // If 'unsafe math' is enabled, fold lots of things.
8081   if (Options.UnsafeFPMath) {
8082     // (fsub A, 0) -> A
8083     if (N1CFP && N1CFP->isZero())
8084       return N0;
8085
8086     // (fsub 0, B) -> -B
8087     if (N0CFP && N0CFP->isZero()) {
8088       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8089         return GetNegatedExpression(N1, DAG, LegalOperations);
8090       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8091         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8092     }
8093
8094     // (fsub x, x) -> 0.0
8095     if (N0 == N1)
8096       return DAG.getConstantFP(0.0f, dl, VT);
8097
8098     // (fsub x, (fadd x, y)) -> (fneg y)
8099     // (fsub x, (fadd y, x)) -> (fneg y)
8100     if (N1.getOpcode() == ISD::FADD) {
8101       SDValue N10 = N1->getOperand(0);
8102       SDValue N11 = N1->getOperand(1);
8103
8104       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8105         return GetNegatedExpression(N11, DAG, LegalOperations);
8106
8107       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8108         return GetNegatedExpression(N10, DAG, LegalOperations);
8109     }
8110   }
8111
8112   // FSUB -> FMA combines:
8113   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8114     AddToWorklist(Fused.getNode());
8115     return Fused;
8116   }
8117
8118   return SDValue();
8119 }
8120
8121 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8122   SDValue N0 = N->getOperand(0);
8123   SDValue N1 = N->getOperand(1);
8124   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8125   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8126   EVT VT = N->getValueType(0);
8127   SDLoc DL(N);
8128   const TargetOptions &Options = DAG.getTarget().Options;
8129
8130   // fold vector ops
8131   if (VT.isVector()) {
8132     // This just handles C1 * C2 for vectors. Other vector folds are below.
8133     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8134       return FoldedVOp;
8135   }
8136
8137   // fold (fmul c1, c2) -> c1*c2
8138   if (N0CFP && N1CFP)
8139     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8140
8141   // canonicalize constant to RHS
8142   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8143      !isConstantFPBuildVectorOrConstantFP(N1))
8144     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8145
8146   // fold (fmul A, 1.0) -> A
8147   if (N1CFP && N1CFP->isExactlyValue(1.0))
8148     return N0;
8149
8150   if (Options.UnsafeFPMath) {
8151     // fold (fmul A, 0) -> 0
8152     if (N1CFP && N1CFP->isZero())
8153       return N1;
8154
8155     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8156     if (N0.getOpcode() == ISD::FMUL) {
8157       // Fold scalars or any vector constants (not just splats).
8158       // This fold is done in general by InstCombine, but extra fmul insts
8159       // may have been generated during lowering.
8160       SDValue N00 = N0.getOperand(0);
8161       SDValue N01 = N0.getOperand(1);
8162       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8163       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8164       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8165
8166       // Check 1: Make sure that the first operand of the inner multiply is NOT
8167       // a constant. Otherwise, we may induce infinite looping.
8168       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8169         // Check 2: Make sure that the second operand of the inner multiply and
8170         // the second operand of the outer multiply are constants.
8171         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8172             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8173           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8174           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8175         }
8176       }
8177     }
8178
8179     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8180     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8181     // during an early run of DAGCombiner can prevent folding with fmuls
8182     // inserted during lowering.
8183     if (N0.getOpcode() == ISD::FADD &&
8184         (N0.getOperand(0) == N0.getOperand(1)) &&
8185         N0.hasOneUse()) {
8186       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8187       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8188       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8189     }
8190   }
8191
8192   // fold (fmul X, 2.0) -> (fadd X, X)
8193   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8194     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8195
8196   // fold (fmul X, -1.0) -> (fneg X)
8197   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8198     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8199       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8200
8201   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8202   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8203     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8204       // Both can be negated for free, check to see if at least one is cheaper
8205       // negated.
8206       if (LHSNeg == 2 || RHSNeg == 2)
8207         return DAG.getNode(ISD::FMUL, DL, VT,
8208                            GetNegatedExpression(N0, DAG, LegalOperations),
8209                            GetNegatedExpression(N1, DAG, LegalOperations));
8210     }
8211   }
8212
8213   return SDValue();
8214 }
8215
8216 SDValue DAGCombiner::visitFMA(SDNode *N) {
8217   SDValue N0 = N->getOperand(0);
8218   SDValue N1 = N->getOperand(1);
8219   SDValue N2 = N->getOperand(2);
8220   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8221   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8222   EVT VT = N->getValueType(0);
8223   SDLoc dl(N);
8224   const TargetOptions &Options = DAG.getTarget().Options;
8225
8226   // Constant fold FMA.
8227   if (isa<ConstantFPSDNode>(N0) &&
8228       isa<ConstantFPSDNode>(N1) &&
8229       isa<ConstantFPSDNode>(N2)) {
8230     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8231   }
8232
8233   if (Options.UnsafeFPMath) {
8234     if (N0CFP && N0CFP->isZero())
8235       return N2;
8236     if (N1CFP && N1CFP->isZero())
8237       return N2;
8238   }
8239   if (N0CFP && N0CFP->isExactlyValue(1.0))
8240     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8241   if (N1CFP && N1CFP->isExactlyValue(1.0))
8242     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8243
8244   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8245   if (N0CFP && !N1CFP)
8246     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8247
8248   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8249   if (Options.UnsafeFPMath && N1CFP &&
8250       N2.getOpcode() == ISD::FMUL &&
8251       N0 == N2.getOperand(0) &&
8252       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8253     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8254                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8255   }
8256
8257
8258   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8259   if (Options.UnsafeFPMath &&
8260       N0.getOpcode() == ISD::FMUL && N1CFP &&
8261       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8262     return DAG.getNode(ISD::FMA, dl, VT,
8263                        N0.getOperand(0),
8264                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8265                        N2);
8266   }
8267
8268   // (fma x, 1, y) -> (fadd x, y)
8269   // (fma x, -1, y) -> (fadd (fneg x), y)
8270   if (N1CFP) {
8271     if (N1CFP->isExactlyValue(1.0))
8272       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8273
8274     if (N1CFP->isExactlyValue(-1.0) &&
8275         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8276       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8277       AddToWorklist(RHSNeg.getNode());
8278       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8279     }
8280   }
8281
8282   // (fma x, c, x) -> (fmul x, (c+1))
8283   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8284     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8285                        DAG.getNode(ISD::FADD, dl, VT,
8286                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8287
8288   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8289   if (Options.UnsafeFPMath && N1CFP &&
8290       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8291     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8292                        DAG.getNode(ISD::FADD, dl, VT,
8293                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8294
8295
8296   return SDValue();
8297 }
8298
8299 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8300 // reciprocal.
8301 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8302 // Notice that this is not always beneficial. One reason is different target
8303 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8304 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8305 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8306 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8307   if (!DAG.getTarget().Options.UnsafeFPMath)
8308     return SDValue();
8309
8310   // Skip if current node is a reciprocal.
8311   SDValue N0 = N->getOperand(0);
8312   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8313   if (N0CFP && N0CFP->isExactlyValue(1.0))
8314     return SDValue();
8315
8316   // Exit early if the target does not want this transform or if there can't
8317   // possibly be enough uses of the divisor to make the transform worthwhile.
8318   SDValue N1 = N->getOperand(1);
8319   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8320   if (!MinUses || N1->use_size() < MinUses)
8321     return SDValue();
8322
8323   // Find all FDIV users of the same divisor.
8324   // Use a set because duplicates may be present in the user list.
8325   SetVector<SDNode *> Users;
8326   for (auto *U : N1->uses())
8327     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8328       Users.insert(U);
8329
8330   // Now that we have the actual number of divisor uses, make sure it meets
8331   // the minimum threshold specified by the target.
8332   if (Users.size() < MinUses)
8333     return SDValue();
8334
8335   EVT VT = N->getValueType(0);
8336   SDLoc DL(N);
8337   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8338   // FIXME: This optimization requires some level of fast-math, so the
8339   // created reciprocal node should at least have the 'allowReciprocal'
8340   // fast-math-flag set.
8341   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8342
8343   // Dividend / Divisor -> Dividend * Reciprocal
8344   for (auto *U : Users) {
8345     SDValue Dividend = U->getOperand(0);
8346     if (Dividend != FPOne) {
8347       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8348                                     Reciprocal);
8349       CombineTo(U, NewNode);
8350     } else if (U != Reciprocal.getNode()) {
8351       // In the absence of fast-math-flags, this user node is always the
8352       // same node as Reciprocal, but with FMF they may be different nodes.
8353       CombineTo(U, Reciprocal);
8354     }
8355   }
8356   return SDValue(N, 0);  // N was replaced.
8357 }
8358
8359 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8360   SDValue N0 = N->getOperand(0);
8361   SDValue N1 = N->getOperand(1);
8362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8363   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8364   EVT VT = N->getValueType(0);
8365   SDLoc DL(N);
8366   const TargetOptions &Options = DAG.getTarget().Options;
8367
8368   // fold vector ops
8369   if (VT.isVector())
8370     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8371       return FoldedVOp;
8372
8373   // fold (fdiv c1, c2) -> c1/c2
8374   if (N0CFP && N1CFP)
8375     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8376
8377   if (Options.UnsafeFPMath) {
8378     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8379     if (N1CFP) {
8380       // Compute the reciprocal 1.0 / c2.
8381       APFloat N1APF = N1CFP->getValueAPF();
8382       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8383       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8384       // Only do the transform if the reciprocal is a legal fp immediate that
8385       // isn't too nasty (eg NaN, denormal, ...).
8386       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8387           (!LegalOperations ||
8388            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8389            // backend)... we should handle this gracefully after Legalize.
8390            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8391            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8392            TLI.isFPImmLegal(Recip, VT)))
8393         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8394                            DAG.getConstantFP(Recip, DL, VT));
8395     }
8396
8397     // If this FDIV is part of a reciprocal square root, it may be folded
8398     // into a target-specific square root estimate instruction.
8399     if (N1.getOpcode() == ISD::FSQRT) {
8400       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8401         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8402       }
8403     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8404                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8405       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8406         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8407         AddToWorklist(RV.getNode());
8408         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8409       }
8410     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8411                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8412       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8413         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8414         AddToWorklist(RV.getNode());
8415         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8416       }
8417     } else if (N1.getOpcode() == ISD::FMUL) {
8418       // Look through an FMUL. Even though this won't remove the FDIV directly,
8419       // it's still worthwhile to get rid of the FSQRT if possible.
8420       SDValue SqrtOp;
8421       SDValue OtherOp;
8422       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8423         SqrtOp = N1.getOperand(0);
8424         OtherOp = N1.getOperand(1);
8425       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8426         SqrtOp = N1.getOperand(1);
8427         OtherOp = N1.getOperand(0);
8428       }
8429       if (SqrtOp.getNode()) {
8430         // We found a FSQRT, so try to make this fold:
8431         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8432         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8433           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8434           AddToWorklist(RV.getNode());
8435           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8436         }
8437       }
8438     }
8439
8440     // Fold into a reciprocal estimate and multiply instead of a real divide.
8441     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8442       AddToWorklist(RV.getNode());
8443       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8444     }
8445   }
8446
8447   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8448   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8449     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8450       // Both can be negated for free, check to see if at least one is cheaper
8451       // negated.
8452       if (LHSNeg == 2 || RHSNeg == 2)
8453         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8454                            GetNegatedExpression(N0, DAG, LegalOperations),
8455                            GetNegatedExpression(N1, DAG, LegalOperations));
8456     }
8457   }
8458
8459   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8460     return CombineRepeatedDivisors;
8461
8462   return SDValue();
8463 }
8464
8465 SDValue DAGCombiner::visitFREM(SDNode *N) {
8466   SDValue N0 = N->getOperand(0);
8467   SDValue N1 = N->getOperand(1);
8468   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8469   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8470   EVT VT = N->getValueType(0);
8471
8472   // fold (frem c1, c2) -> fmod(c1,c2)
8473   if (N0CFP && N1CFP)
8474     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8475
8476   return SDValue();
8477 }
8478
8479 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8480   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8481     return SDValue();
8482
8483   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8484   SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8485   if (!RV)
8486     return SDValue();
8487
8488   EVT VT = RV.getValueType();
8489   SDLoc DL(N);
8490   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8491   AddToWorklist(RV.getNode());
8492
8493   // Unfortunately, RV is now NaN if the input was exactly 0.
8494   // Select out this case and force the answer to 0.
8495   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8496   EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8497   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8498   AddToWorklist(ZeroCmp.getNode());
8499   AddToWorklist(RV.getNode());
8500
8501   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8502                      ZeroCmp, Zero, RV);
8503 }
8504
8505 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8506   SDValue N0 = N->getOperand(0);
8507   SDValue N1 = N->getOperand(1);
8508   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8509   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8510   EVT VT = N->getValueType(0);
8511
8512   if (N0CFP && N1CFP)  // Constant fold
8513     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8514
8515   if (N1CFP) {
8516     const APFloat& V = N1CFP->getValueAPF();
8517     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8518     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8519     if (!V.isNegative()) {
8520       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8521         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8522     } else {
8523       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8524         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8525                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8526     }
8527   }
8528
8529   // copysign(fabs(x), y) -> copysign(x, y)
8530   // copysign(fneg(x), y) -> copysign(x, y)
8531   // copysign(copysign(x,z), y) -> copysign(x, y)
8532   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8533       N0.getOpcode() == ISD::FCOPYSIGN)
8534     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8535                        N0.getOperand(0), N1);
8536
8537   // copysign(x, abs(y)) -> abs(x)
8538   if (N1.getOpcode() == ISD::FABS)
8539     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8540
8541   // copysign(x, copysign(y,z)) -> copysign(x, z)
8542   if (N1.getOpcode() == ISD::FCOPYSIGN)
8543     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8544                        N0, N1.getOperand(1));
8545
8546   // copysign(x, fp_extend(y)) -> copysign(x, y)
8547   // copysign(x, fp_round(y)) -> copysign(x, y)
8548   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8549     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8550                        N0, N1.getOperand(0));
8551
8552   return SDValue();
8553 }
8554
8555 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8556   SDValue N0 = N->getOperand(0);
8557   EVT VT = N->getValueType(0);
8558   EVT OpVT = N0.getValueType();
8559
8560   // fold (sint_to_fp c1) -> c1fp
8561   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8562       // ...but only if the target supports immediate floating-point values
8563       (!LegalOperations ||
8564        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8565     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8566
8567   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8568   // but UINT_TO_FP is legal on this target, try to convert.
8569   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8570       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8571     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8572     if (DAG.SignBitIsZero(N0))
8573       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8574   }
8575
8576   // The next optimizations are desirable only if SELECT_CC can be lowered.
8577   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8578     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8579     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8580         !VT.isVector() &&
8581         (!LegalOperations ||
8582          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8583       SDLoc DL(N);
8584       SDValue Ops[] =
8585         { N0.getOperand(0), N0.getOperand(1),
8586           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8587           N0.getOperand(2) };
8588       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8589     }
8590
8591     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8592     //      (select_cc x, y, 1.0, 0.0,, cc)
8593     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8594         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8595         (!LegalOperations ||
8596          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8597       SDLoc DL(N);
8598       SDValue Ops[] =
8599         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8600           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8601           N0.getOperand(0).getOperand(2) };
8602       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8603     }
8604   }
8605
8606   return SDValue();
8607 }
8608
8609 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8610   SDValue N0 = N->getOperand(0);
8611   EVT VT = N->getValueType(0);
8612   EVT OpVT = N0.getValueType();
8613
8614   // fold (uint_to_fp c1) -> c1fp
8615   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8616       // ...but only if the target supports immediate floating-point values
8617       (!LegalOperations ||
8618        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8619     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8620
8621   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8622   // but SINT_TO_FP is legal on this target, try to convert.
8623   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8624       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8625     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8626     if (DAG.SignBitIsZero(N0))
8627       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8628   }
8629
8630   // The next optimizations are desirable only if SELECT_CC can be lowered.
8631   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8632     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8633
8634     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8635         (!LegalOperations ||
8636          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8637       SDLoc DL(N);
8638       SDValue Ops[] =
8639         { N0.getOperand(0), N0.getOperand(1),
8640           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8641           N0.getOperand(2) };
8642       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8643     }
8644   }
8645
8646   return SDValue();
8647 }
8648
8649 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8650 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8651   SDValue N0 = N->getOperand(0);
8652   EVT VT = N->getValueType(0);
8653
8654   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8655     return SDValue();
8656
8657   SDValue Src = N0.getOperand(0);
8658   EVT SrcVT = Src.getValueType();
8659   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8660   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8661
8662   // We can safely assume the conversion won't overflow the output range,
8663   // because (for example) (uint8_t)18293.f is undefined behavior.
8664
8665   // Since we can assume the conversion won't overflow, our decision as to
8666   // whether the input will fit in the float should depend on the minimum
8667   // of the input range and output range.
8668
8669   // This means this is also safe for a signed input and unsigned output, since
8670   // a negative input would lead to undefined behavior.
8671   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8672   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8673   unsigned ActualSize = std::min(InputSize, OutputSize);
8674   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8675
8676   // We can only fold away the float conversion if the input range can be
8677   // represented exactly in the float range.
8678   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8679     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8680       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8681                                                        : ISD::ZERO_EXTEND;
8682       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8683     }
8684     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8685       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8686     if (SrcVT == VT)
8687       return Src;
8688     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8689   }
8690   return SDValue();
8691 }
8692
8693 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8694   SDValue N0 = N->getOperand(0);
8695   EVT VT = N->getValueType(0);
8696
8697   // fold (fp_to_sint c1fp) -> c1
8698   if (isConstantFPBuildVectorOrConstantFP(N0))
8699     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8700
8701   return FoldIntToFPToInt(N, DAG);
8702 }
8703
8704 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8705   SDValue N0 = N->getOperand(0);
8706   EVT VT = N->getValueType(0);
8707
8708   // fold (fp_to_uint c1fp) -> c1
8709   if (isConstantFPBuildVectorOrConstantFP(N0))
8710     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8711
8712   return FoldIntToFPToInt(N, DAG);
8713 }
8714
8715 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8716   SDValue N0 = N->getOperand(0);
8717   SDValue N1 = N->getOperand(1);
8718   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8719   EVT VT = N->getValueType(0);
8720
8721   // fold (fp_round c1fp) -> c1fp
8722   if (N0CFP)
8723     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8724
8725   // fold (fp_round (fp_extend x)) -> x
8726   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8727     return N0.getOperand(0);
8728
8729   // fold (fp_round (fp_round x)) -> (fp_round x)
8730   if (N0.getOpcode() == ISD::FP_ROUND) {
8731     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8732     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8733     // If the first fp_round isn't a value preserving truncation, it might
8734     // introduce a tie in the second fp_round, that wouldn't occur in the
8735     // single-step fp_round we want to fold to.
8736     // In other words, double rounding isn't the same as rounding.
8737     // Also, this is a value preserving truncation iff both fp_round's are.
8738     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8739       SDLoc DL(N);
8740       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8741                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8742     }
8743   }
8744
8745   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8746   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8747     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8748                               N0.getOperand(0), N1);
8749     AddToWorklist(Tmp.getNode());
8750     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8751                        Tmp, N0.getOperand(1));
8752   }
8753
8754   return SDValue();
8755 }
8756
8757 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8758   SDValue N0 = N->getOperand(0);
8759   EVT VT = N->getValueType(0);
8760   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8761   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8762
8763   // fold (fp_round_inreg c1fp) -> c1fp
8764   if (N0CFP && isTypeLegal(EVT)) {
8765     SDLoc DL(N);
8766     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8767     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8768   }
8769
8770   return SDValue();
8771 }
8772
8773 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8774   SDValue N0 = N->getOperand(0);
8775   EVT VT = N->getValueType(0);
8776
8777   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8778   if (N->hasOneUse() &&
8779       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8780     return SDValue();
8781
8782   // fold (fp_extend c1fp) -> c1fp
8783   if (isConstantFPBuildVectorOrConstantFP(N0))
8784     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8785
8786   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8787   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8788       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8789     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8790
8791   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8792   // value of X.
8793   if (N0.getOpcode() == ISD::FP_ROUND
8794       && N0.getNode()->getConstantOperandVal(1) == 1) {
8795     SDValue In = N0.getOperand(0);
8796     if (In.getValueType() == VT) return In;
8797     if (VT.bitsLT(In.getValueType()))
8798       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8799                          In, N0.getOperand(1));
8800     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8801   }
8802
8803   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8804   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8805        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8806     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8807     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8808                                      LN0->getChain(),
8809                                      LN0->getBasePtr(), N0.getValueType(),
8810                                      LN0->getMemOperand());
8811     CombineTo(N, ExtLoad);
8812     CombineTo(N0.getNode(),
8813               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8814                           N0.getValueType(), ExtLoad,
8815                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8816               ExtLoad.getValue(1));
8817     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8818   }
8819
8820   return SDValue();
8821 }
8822
8823 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8824   SDValue N0 = N->getOperand(0);
8825   EVT VT = N->getValueType(0);
8826
8827   // fold (fceil c1) -> fceil(c1)
8828   if (isConstantFPBuildVectorOrConstantFP(N0))
8829     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8830
8831   return SDValue();
8832 }
8833
8834 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8835   SDValue N0 = N->getOperand(0);
8836   EVT VT = N->getValueType(0);
8837
8838   // fold (ftrunc c1) -> ftrunc(c1)
8839   if (isConstantFPBuildVectorOrConstantFP(N0))
8840     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8841
8842   return SDValue();
8843 }
8844
8845 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8846   SDValue N0 = N->getOperand(0);
8847   EVT VT = N->getValueType(0);
8848
8849   // fold (ffloor c1) -> ffloor(c1)
8850   if (isConstantFPBuildVectorOrConstantFP(N0))
8851     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8852
8853   return SDValue();
8854 }
8855
8856 // FIXME: FNEG and FABS have a lot in common; refactor.
8857 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8858   SDValue N0 = N->getOperand(0);
8859   EVT VT = N->getValueType(0);
8860
8861   // Constant fold FNEG.
8862   if (isConstantFPBuildVectorOrConstantFP(N0))
8863     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8864
8865   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8866                          &DAG.getTarget().Options))
8867     return GetNegatedExpression(N0, DAG, LegalOperations);
8868
8869   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8870   // constant pool values.
8871   if (!TLI.isFNegFree(VT) &&
8872       N0.getOpcode() == ISD::BITCAST &&
8873       N0.getNode()->hasOneUse()) {
8874     SDValue Int = N0.getOperand(0);
8875     EVT IntVT = Int.getValueType();
8876     if (IntVT.isInteger() && !IntVT.isVector()) {
8877       APInt SignMask;
8878       if (N0.getValueType().isVector()) {
8879         // For a vector, get a mask such as 0x80... per scalar element
8880         // and splat it.
8881         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8882         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8883       } else {
8884         // For a scalar, just generate 0x80...
8885         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8886       }
8887       SDLoc DL0(N0);
8888       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8889                         DAG.getConstant(SignMask, DL0, IntVT));
8890       AddToWorklist(Int.getNode());
8891       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8892     }
8893   }
8894
8895   // (fneg (fmul c, x)) -> (fmul -c, x)
8896   if (N0.getOpcode() == ISD::FMUL &&
8897       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8898     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8899     if (CFP1) {
8900       APFloat CVal = CFP1->getValueAPF();
8901       CVal.changeSign();
8902       if (Level >= AfterLegalizeDAG &&
8903           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8904            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8905         return DAG.getNode(
8906             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8907             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8908     }
8909   }
8910
8911   return SDValue();
8912 }
8913
8914 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8915   SDValue N0 = N->getOperand(0);
8916   SDValue N1 = N->getOperand(1);
8917   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8918   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8919
8920   if (N0CFP && N1CFP) {
8921     const APFloat &C0 = N0CFP->getValueAPF();
8922     const APFloat &C1 = N1CFP->getValueAPF();
8923     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8924   }
8925
8926   if (N0CFP) {
8927     EVT VT = N->getValueType(0);
8928     // Canonicalize to constant on RHS.
8929     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8930   }
8931
8932   return SDValue();
8933 }
8934
8935 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8936   SDValue N0 = N->getOperand(0);
8937   SDValue N1 = N->getOperand(1);
8938   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8939   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8940
8941   if (N0CFP && N1CFP) {
8942     const APFloat &C0 = N0CFP->getValueAPF();
8943     const APFloat &C1 = N1CFP->getValueAPF();
8944     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8945   }
8946
8947   if (N0CFP) {
8948     EVT VT = N->getValueType(0);
8949     // Canonicalize to constant on RHS.
8950     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8951   }
8952
8953   return SDValue();
8954 }
8955
8956 SDValue DAGCombiner::visitFABS(SDNode *N) {
8957   SDValue N0 = N->getOperand(0);
8958   EVT VT = N->getValueType(0);
8959
8960   // fold (fabs c1) -> fabs(c1)
8961   if (isConstantFPBuildVectorOrConstantFP(N0))
8962     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8963
8964   // fold (fabs (fabs x)) -> (fabs x)
8965   if (N0.getOpcode() == ISD::FABS)
8966     return N->getOperand(0);
8967
8968   // fold (fabs (fneg x)) -> (fabs x)
8969   // fold (fabs (fcopysign x, y)) -> (fabs x)
8970   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8971     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8972
8973   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8974   // constant pool values.
8975   if (!TLI.isFAbsFree(VT) &&
8976       N0.getOpcode() == ISD::BITCAST &&
8977       N0.getNode()->hasOneUse()) {
8978     SDValue Int = N0.getOperand(0);
8979     EVT IntVT = Int.getValueType();
8980     if (IntVT.isInteger() && !IntVT.isVector()) {
8981       APInt SignMask;
8982       if (N0.getValueType().isVector()) {
8983         // For a vector, get a mask such as 0x7f... per scalar element
8984         // and splat it.
8985         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8986         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8987       } else {
8988         // For a scalar, just generate 0x7f...
8989         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8990       }
8991       SDLoc DL(N0);
8992       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8993                         DAG.getConstant(SignMask, DL, IntVT));
8994       AddToWorklist(Int.getNode());
8995       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8996     }
8997   }
8998
8999   return SDValue();
9000 }
9001
9002 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9003   SDValue Chain = N->getOperand(0);
9004   SDValue N1 = N->getOperand(1);
9005   SDValue N2 = N->getOperand(2);
9006
9007   // If N is a constant we could fold this into a fallthrough or unconditional
9008   // branch. However that doesn't happen very often in normal code, because
9009   // Instcombine/SimplifyCFG should have handled the available opportunities.
9010   // If we did this folding here, it would be necessary to update the
9011   // MachineBasicBlock CFG, which is awkward.
9012
9013   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9014   // on the target.
9015   if (N1.getOpcode() == ISD::SETCC &&
9016       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9017                                    N1.getOperand(0).getValueType())) {
9018     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9019                        Chain, N1.getOperand(2),
9020                        N1.getOperand(0), N1.getOperand(1), N2);
9021   }
9022
9023   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9024       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9025        (N1.getOperand(0).hasOneUse() &&
9026         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9027     SDNode *Trunc = nullptr;
9028     if (N1.getOpcode() == ISD::TRUNCATE) {
9029       // Look pass the truncate.
9030       Trunc = N1.getNode();
9031       N1 = N1.getOperand(0);
9032     }
9033
9034     // Match this pattern so that we can generate simpler code:
9035     //
9036     //   %a = ...
9037     //   %b = and i32 %a, 2
9038     //   %c = srl i32 %b, 1
9039     //   brcond i32 %c ...
9040     //
9041     // into
9042     //
9043     //   %a = ...
9044     //   %b = and i32 %a, 2
9045     //   %c = setcc eq %b, 0
9046     //   brcond %c ...
9047     //
9048     // This applies only when the AND constant value has one bit set and the
9049     // SRL constant is equal to the log2 of the AND constant. The back-end is
9050     // smart enough to convert the result into a TEST/JMP sequence.
9051     SDValue Op0 = N1.getOperand(0);
9052     SDValue Op1 = N1.getOperand(1);
9053
9054     if (Op0.getOpcode() == ISD::AND &&
9055         Op1.getOpcode() == ISD::Constant) {
9056       SDValue AndOp1 = Op0.getOperand(1);
9057
9058       if (AndOp1.getOpcode() == ISD::Constant) {
9059         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9060
9061         if (AndConst.isPowerOf2() &&
9062             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9063           SDLoc DL(N);
9064           SDValue SetCC =
9065             DAG.getSetCC(DL,
9066                          getSetCCResultType(Op0.getValueType()),
9067                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9068                          ISD::SETNE);
9069
9070           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9071                                           MVT::Other, Chain, SetCC, N2);
9072           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9073           // will convert it back to (X & C1) >> C2.
9074           CombineTo(N, NewBRCond, false);
9075           // Truncate is dead.
9076           if (Trunc)
9077             deleteAndRecombine(Trunc);
9078           // Replace the uses of SRL with SETCC
9079           WorklistRemover DeadNodes(*this);
9080           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9081           deleteAndRecombine(N1.getNode());
9082           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9083         }
9084       }
9085     }
9086
9087     if (Trunc)
9088       // Restore N1 if the above transformation doesn't match.
9089       N1 = N->getOperand(1);
9090   }
9091
9092   // Transform br(xor(x, y)) -> br(x != y)
9093   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9094   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9095     SDNode *TheXor = N1.getNode();
9096     SDValue Op0 = TheXor->getOperand(0);
9097     SDValue Op1 = TheXor->getOperand(1);
9098     if (Op0.getOpcode() == Op1.getOpcode()) {
9099       // Avoid missing important xor optimizations.
9100       if (SDValue Tmp = visitXOR(TheXor)) {
9101         if (Tmp.getNode() != TheXor) {
9102           DEBUG(dbgs() << "\nReplacing.8 ";
9103                 TheXor->dump(&DAG);
9104                 dbgs() << "\nWith: ";
9105                 Tmp.getNode()->dump(&DAG);
9106                 dbgs() << '\n');
9107           WorklistRemover DeadNodes(*this);
9108           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9109           deleteAndRecombine(TheXor);
9110           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9111                              MVT::Other, Chain, Tmp, N2);
9112         }
9113
9114         // visitXOR has changed XOR's operands or replaced the XOR completely,
9115         // bail out.
9116         return SDValue(N, 0);
9117       }
9118     }
9119
9120     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9121       bool Equal = false;
9122       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9123           Op0.getOpcode() == ISD::XOR) {
9124         TheXor = Op0.getNode();
9125         Equal = true;
9126       }
9127
9128       EVT SetCCVT = N1.getValueType();
9129       if (LegalTypes)
9130         SetCCVT = getSetCCResultType(SetCCVT);
9131       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9132                                    SetCCVT,
9133                                    Op0, Op1,
9134                                    Equal ? ISD::SETEQ : ISD::SETNE);
9135       // Replace the uses of XOR with SETCC
9136       WorklistRemover DeadNodes(*this);
9137       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9138       deleteAndRecombine(N1.getNode());
9139       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9140                          MVT::Other, Chain, SetCC, N2);
9141     }
9142   }
9143
9144   return SDValue();
9145 }
9146
9147 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9148 //
9149 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9150   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9151   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9152
9153   // If N is a constant we could fold this into a fallthrough or unconditional
9154   // branch. However that doesn't happen very often in normal code, because
9155   // Instcombine/SimplifyCFG should have handled the available opportunities.
9156   // If we did this folding here, it would be necessary to update the
9157   // MachineBasicBlock CFG, which is awkward.
9158
9159   // Use SimplifySetCC to simplify SETCC's.
9160   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9161                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9162                                false);
9163   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9164
9165   // fold to a simpler setcc
9166   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9167     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9168                        N->getOperand(0), Simp.getOperand(2),
9169                        Simp.getOperand(0), Simp.getOperand(1),
9170                        N->getOperand(4));
9171
9172   return SDValue();
9173 }
9174
9175 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9176 /// and that N may be folded in the load / store addressing mode.
9177 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9178                                     SelectionDAG &DAG,
9179                                     const TargetLowering &TLI) {
9180   EVT VT;
9181   unsigned AS;
9182
9183   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9184     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9185       return false;
9186     VT = LD->getMemoryVT();
9187     AS = LD->getAddressSpace();
9188   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9189     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9190       return false;
9191     VT = ST->getMemoryVT();
9192     AS = ST->getAddressSpace();
9193   } else
9194     return false;
9195
9196   TargetLowering::AddrMode AM;
9197   if (N->getOpcode() == ISD::ADD) {
9198     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9199     if (Offset)
9200       // [reg +/- imm]
9201       AM.BaseOffs = Offset->getSExtValue();
9202     else
9203       // [reg +/- reg]
9204       AM.Scale = 1;
9205   } else if (N->getOpcode() == ISD::SUB) {
9206     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9207     if (Offset)
9208       // [reg +/- imm]
9209       AM.BaseOffs = -Offset->getSExtValue();
9210     else
9211       // [reg +/- reg]
9212       AM.Scale = 1;
9213   } else
9214     return false;
9215
9216   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9217                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9218 }
9219
9220 /// Try turning a load/store into a pre-indexed load/store when the base
9221 /// pointer is an add or subtract and it has other uses besides the load/store.
9222 /// After the transformation, the new indexed load/store has effectively folded
9223 /// the add/subtract in and all of its other uses are redirected to the
9224 /// new load/store.
9225 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9226   if (Level < AfterLegalizeDAG)
9227     return false;
9228
9229   bool isLoad = true;
9230   SDValue Ptr;
9231   EVT VT;
9232   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9233     if (LD->isIndexed())
9234       return false;
9235     VT = LD->getMemoryVT();
9236     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9237         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9238       return false;
9239     Ptr = LD->getBasePtr();
9240   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9241     if (ST->isIndexed())
9242       return false;
9243     VT = ST->getMemoryVT();
9244     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9245         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9246       return false;
9247     Ptr = ST->getBasePtr();
9248     isLoad = false;
9249   } else {
9250     return false;
9251   }
9252
9253   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9254   // out.  There is no reason to make this a preinc/predec.
9255   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9256       Ptr.getNode()->hasOneUse())
9257     return false;
9258
9259   // Ask the target to do addressing mode selection.
9260   SDValue BasePtr;
9261   SDValue Offset;
9262   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9263   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9264     return false;
9265
9266   // Backends without true r+i pre-indexed forms may need to pass a
9267   // constant base with a variable offset so that constant coercion
9268   // will work with the patterns in canonical form.
9269   bool Swapped = false;
9270   if (isa<ConstantSDNode>(BasePtr)) {
9271     std::swap(BasePtr, Offset);
9272     Swapped = true;
9273   }
9274
9275   // Don't create a indexed load / store with zero offset.
9276   if (isNullConstant(Offset))
9277     return false;
9278
9279   // Try turning it into a pre-indexed load / store except when:
9280   // 1) The new base ptr is a frame index.
9281   // 2) If N is a store and the new base ptr is either the same as or is a
9282   //    predecessor of the value being stored.
9283   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9284   //    that would create a cycle.
9285   // 4) All uses are load / store ops that use it as old base ptr.
9286
9287   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9288   // (plus the implicit offset) to a register to preinc anyway.
9289   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9290     return false;
9291
9292   // Check #2.
9293   if (!isLoad) {
9294     SDValue Val = cast<StoreSDNode>(N)->getValue();
9295     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9296       return false;
9297   }
9298
9299   // If the offset is a constant, there may be other adds of constants that
9300   // can be folded with this one. We should do this to avoid having to keep
9301   // a copy of the original base pointer.
9302   SmallVector<SDNode *, 16> OtherUses;
9303   if (isa<ConstantSDNode>(Offset))
9304     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9305                               UE = BasePtr.getNode()->use_end();
9306          UI != UE; ++UI) {
9307       SDUse &Use = UI.getUse();
9308       // Skip the use that is Ptr and uses of other results from BasePtr's
9309       // node (important for nodes that return multiple results).
9310       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9311         continue;
9312
9313       if (Use.getUser()->isPredecessorOf(N))
9314         continue;
9315
9316       if (Use.getUser()->getOpcode() != ISD::ADD &&
9317           Use.getUser()->getOpcode() != ISD::SUB) {
9318         OtherUses.clear();
9319         break;
9320       }
9321
9322       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9323       if (!isa<ConstantSDNode>(Op1)) {
9324         OtherUses.clear();
9325         break;
9326       }
9327
9328       // FIXME: In some cases, we can be smarter about this.
9329       if (Op1.getValueType() != Offset.getValueType()) {
9330         OtherUses.clear();
9331         break;
9332       }
9333
9334       OtherUses.push_back(Use.getUser());
9335     }
9336
9337   if (Swapped)
9338     std::swap(BasePtr, Offset);
9339
9340   // Now check for #3 and #4.
9341   bool RealUse = false;
9342
9343   // Caches for hasPredecessorHelper
9344   SmallPtrSet<const SDNode *, 32> Visited;
9345   SmallVector<const SDNode *, 16> Worklist;
9346
9347   for (SDNode *Use : Ptr.getNode()->uses()) {
9348     if (Use == N)
9349       continue;
9350     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9351       return false;
9352
9353     // If Ptr may be folded in addressing mode of other use, then it's
9354     // not profitable to do this transformation.
9355     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9356       RealUse = true;
9357   }
9358
9359   if (!RealUse)
9360     return false;
9361
9362   SDValue Result;
9363   if (isLoad)
9364     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9365                                 BasePtr, Offset, AM);
9366   else
9367     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9368                                  BasePtr, Offset, AM);
9369   ++PreIndexedNodes;
9370   ++NodesCombined;
9371   DEBUG(dbgs() << "\nReplacing.4 ";
9372         N->dump(&DAG);
9373         dbgs() << "\nWith: ";
9374         Result.getNode()->dump(&DAG);
9375         dbgs() << '\n');
9376   WorklistRemover DeadNodes(*this);
9377   if (isLoad) {
9378     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9379     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9380   } else {
9381     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9382   }
9383
9384   // Finally, since the node is now dead, remove it from the graph.
9385   deleteAndRecombine(N);
9386
9387   if (Swapped)
9388     std::swap(BasePtr, Offset);
9389
9390   // Replace other uses of BasePtr that can be updated to use Ptr
9391   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9392     unsigned OffsetIdx = 1;
9393     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9394       OffsetIdx = 0;
9395     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9396            BasePtr.getNode() && "Expected BasePtr operand");
9397
9398     // We need to replace ptr0 in the following expression:
9399     //   x0 * offset0 + y0 * ptr0 = t0
9400     // knowing that
9401     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9402     //
9403     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9404     // indexed load/store and the expresion that needs to be re-written.
9405     //
9406     // Therefore, we have:
9407     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9408
9409     ConstantSDNode *CN =
9410       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9411     int X0, X1, Y0, Y1;
9412     APInt Offset0 = CN->getAPIntValue();
9413     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9414
9415     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9416     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9417     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9418     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9419
9420     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9421
9422     APInt CNV = Offset0;
9423     if (X0 < 0) CNV = -CNV;
9424     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9425     else CNV = CNV - Offset1;
9426
9427     SDLoc DL(OtherUses[i]);
9428
9429     // We can now generate the new expression.
9430     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9431     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9432
9433     SDValue NewUse = DAG.getNode(Opcode,
9434                                  DL,
9435                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9436     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9437     deleteAndRecombine(OtherUses[i]);
9438   }
9439
9440   // Replace the uses of Ptr with uses of the updated base value.
9441   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9442   deleteAndRecombine(Ptr.getNode());
9443
9444   return true;
9445 }
9446
9447 /// Try to combine a load/store with a add/sub of the base pointer node into a
9448 /// post-indexed load/store. The transformation folded the add/subtract into the
9449 /// new indexed load/store effectively and all of its uses are redirected to the
9450 /// new load/store.
9451 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9452   if (Level < AfterLegalizeDAG)
9453     return false;
9454
9455   bool isLoad = true;
9456   SDValue Ptr;
9457   EVT VT;
9458   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9459     if (LD->isIndexed())
9460       return false;
9461     VT = LD->getMemoryVT();
9462     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9463         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9464       return false;
9465     Ptr = LD->getBasePtr();
9466   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9467     if (ST->isIndexed())
9468       return false;
9469     VT = ST->getMemoryVT();
9470     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9471         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9472       return false;
9473     Ptr = ST->getBasePtr();
9474     isLoad = false;
9475   } else {
9476     return false;
9477   }
9478
9479   if (Ptr.getNode()->hasOneUse())
9480     return false;
9481
9482   for (SDNode *Op : Ptr.getNode()->uses()) {
9483     if (Op == N ||
9484         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9485       continue;
9486
9487     SDValue BasePtr;
9488     SDValue Offset;
9489     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9490     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9491       // Don't create a indexed load / store with zero offset.
9492       if (isNullConstant(Offset))
9493         continue;
9494
9495       // Try turning it into a post-indexed load / store except when
9496       // 1) All uses are load / store ops that use it as base ptr (and
9497       //    it may be folded as addressing mmode).
9498       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9499       //    nor a successor of N. Otherwise, if Op is folded that would
9500       //    create a cycle.
9501
9502       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9503         continue;
9504
9505       // Check for #1.
9506       bool TryNext = false;
9507       for (SDNode *Use : BasePtr.getNode()->uses()) {
9508         if (Use == Ptr.getNode())
9509           continue;
9510
9511         // If all the uses are load / store addresses, then don't do the
9512         // transformation.
9513         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9514           bool RealUse = false;
9515           for (SDNode *UseUse : Use->uses()) {
9516             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9517               RealUse = true;
9518           }
9519
9520           if (!RealUse) {
9521             TryNext = true;
9522             break;
9523           }
9524         }
9525       }
9526
9527       if (TryNext)
9528         continue;
9529
9530       // Check for #2
9531       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9532         SDValue Result = isLoad
9533           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9534                                BasePtr, Offset, AM)
9535           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9536                                 BasePtr, Offset, AM);
9537         ++PostIndexedNodes;
9538         ++NodesCombined;
9539         DEBUG(dbgs() << "\nReplacing.5 ";
9540               N->dump(&DAG);
9541               dbgs() << "\nWith: ";
9542               Result.getNode()->dump(&DAG);
9543               dbgs() << '\n');
9544         WorklistRemover DeadNodes(*this);
9545         if (isLoad) {
9546           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9547           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9548         } else {
9549           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9550         }
9551
9552         // Finally, since the node is now dead, remove it from the graph.
9553         deleteAndRecombine(N);
9554
9555         // Replace the uses of Use with uses of the updated base value.
9556         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9557                                       Result.getValue(isLoad ? 1 : 0));
9558         deleteAndRecombine(Op);
9559         return true;
9560       }
9561     }
9562   }
9563
9564   return false;
9565 }
9566
9567 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9568 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9569   ISD::MemIndexedMode AM = LD->getAddressingMode();
9570   assert(AM != ISD::UNINDEXED);
9571   SDValue BP = LD->getOperand(1);
9572   SDValue Inc = LD->getOperand(2);
9573
9574   // Some backends use TargetConstants for load offsets, but don't expect
9575   // TargetConstants in general ADD nodes. We can convert these constants into
9576   // regular Constants (if the constant is not opaque).
9577   assert((Inc.getOpcode() != ISD::TargetConstant ||
9578           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9579          "Cannot split out indexing using opaque target constants");
9580   if (Inc.getOpcode() == ISD::TargetConstant) {
9581     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9582     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9583                           ConstInc->getValueType(0));
9584   }
9585
9586   unsigned Opc =
9587       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9588   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9589 }
9590
9591 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9592   LoadSDNode *LD  = cast<LoadSDNode>(N);
9593   SDValue Chain = LD->getChain();
9594   SDValue Ptr   = LD->getBasePtr();
9595
9596   // If load is not volatile and there are no uses of the loaded value (and
9597   // the updated indexed value in case of indexed loads), change uses of the
9598   // chain value into uses of the chain input (i.e. delete the dead load).
9599   if (!LD->isVolatile()) {
9600     if (N->getValueType(1) == MVT::Other) {
9601       // Unindexed loads.
9602       if (!N->hasAnyUseOfValue(0)) {
9603         // It's not safe to use the two value CombineTo variant here. e.g.
9604         // v1, chain2 = load chain1, loc
9605         // v2, chain3 = load chain2, loc
9606         // v3         = add v2, c
9607         // Now we replace use of chain2 with chain1.  This makes the second load
9608         // isomorphic to the one we are deleting, and thus makes this load live.
9609         DEBUG(dbgs() << "\nReplacing.6 ";
9610               N->dump(&DAG);
9611               dbgs() << "\nWith chain: ";
9612               Chain.getNode()->dump(&DAG);
9613               dbgs() << "\n");
9614         WorklistRemover DeadNodes(*this);
9615         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9616
9617         if (N->use_empty())
9618           deleteAndRecombine(N);
9619
9620         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9621       }
9622     } else {
9623       // Indexed loads.
9624       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9625
9626       // If this load has an opaque TargetConstant offset, then we cannot split
9627       // the indexing into an add/sub directly (that TargetConstant may not be
9628       // valid for a different type of node, and we cannot convert an opaque
9629       // target constant into a regular constant).
9630       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9631                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9632
9633       if (!N->hasAnyUseOfValue(0) &&
9634           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9635         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9636         SDValue Index;
9637         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9638           Index = SplitIndexingFromLoad(LD);
9639           // Try to fold the base pointer arithmetic into subsequent loads and
9640           // stores.
9641           AddUsersToWorklist(N);
9642         } else
9643           Index = DAG.getUNDEF(N->getValueType(1));
9644         DEBUG(dbgs() << "\nReplacing.7 ";
9645               N->dump(&DAG);
9646               dbgs() << "\nWith: ";
9647               Undef.getNode()->dump(&DAG);
9648               dbgs() << " and 2 other values\n");
9649         WorklistRemover DeadNodes(*this);
9650         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9651         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9652         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9653         deleteAndRecombine(N);
9654         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9655       }
9656     }
9657   }
9658
9659   // If this load is directly stored, replace the load value with the stored
9660   // value.
9661   // TODO: Handle store large -> read small portion.
9662   // TODO: Handle TRUNCSTORE/LOADEXT
9663   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9664     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9665       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9666       if (PrevST->getBasePtr() == Ptr &&
9667           PrevST->getValue().getValueType() == N->getValueType(0))
9668       return CombineTo(N, Chain.getOperand(1), Chain);
9669     }
9670   }
9671
9672   // Try to infer better alignment information than the load already has.
9673   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9674     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9675       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9676         SDValue NewLoad =
9677                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9678                               LD->getValueType(0),
9679                               Chain, Ptr, LD->getPointerInfo(),
9680                               LD->getMemoryVT(),
9681                               LD->isVolatile(), LD->isNonTemporal(),
9682                               LD->isInvariant(), Align, LD->getAAInfo());
9683         if (NewLoad.getNode() != N)
9684           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9685       }
9686     }
9687   }
9688
9689   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9690                                                   : DAG.getSubtarget().useAA();
9691 #ifndef NDEBUG
9692   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9693       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9694     UseAA = false;
9695 #endif
9696   if (UseAA && LD->isUnindexed()) {
9697     // Walk up chain skipping non-aliasing memory nodes.
9698     SDValue BetterChain = FindBetterChain(N, Chain);
9699
9700     // If there is a better chain.
9701     if (Chain != BetterChain) {
9702       SDValue ReplLoad;
9703
9704       // Replace the chain to void dependency.
9705       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9706         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9707                                BetterChain, Ptr, LD->getMemOperand());
9708       } else {
9709         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9710                                   LD->getValueType(0),
9711                                   BetterChain, Ptr, LD->getMemoryVT(),
9712                                   LD->getMemOperand());
9713       }
9714
9715       // Create token factor to keep old chain connected.
9716       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9717                                   MVT::Other, Chain, ReplLoad.getValue(1));
9718
9719       // Make sure the new and old chains are cleaned up.
9720       AddToWorklist(Token.getNode());
9721
9722       // Replace uses with load result and token factor. Don't add users
9723       // to work list.
9724       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9725     }
9726   }
9727
9728   // Try transforming N to an indexed load.
9729   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9730     return SDValue(N, 0);
9731
9732   // Try to slice up N to more direct loads if the slices are mapped to
9733   // different register banks or pairing can take place.
9734   if (SliceUpLoad(N))
9735     return SDValue(N, 0);
9736
9737   return SDValue();
9738 }
9739
9740 namespace {
9741 /// \brief Helper structure used to slice a load in smaller loads.
9742 /// Basically a slice is obtained from the following sequence:
9743 /// Origin = load Ty1, Base
9744 /// Shift = srl Ty1 Origin, CstTy Amount
9745 /// Inst = trunc Shift to Ty2
9746 ///
9747 /// Then, it will be rewriten into:
9748 /// Slice = load SliceTy, Base + SliceOffset
9749 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9750 ///
9751 /// SliceTy is deduced from the number of bits that are actually used to
9752 /// build Inst.
9753 struct LoadedSlice {
9754   /// \brief Helper structure used to compute the cost of a slice.
9755   struct Cost {
9756     /// Are we optimizing for code size.
9757     bool ForCodeSize;
9758     /// Various cost.
9759     unsigned Loads;
9760     unsigned Truncates;
9761     unsigned CrossRegisterBanksCopies;
9762     unsigned ZExts;
9763     unsigned Shift;
9764
9765     Cost(bool ForCodeSize = false)
9766         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9767           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9768
9769     /// \brief Get the cost of one isolated slice.
9770     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9771         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9772           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9773       EVT TruncType = LS.Inst->getValueType(0);
9774       EVT LoadedType = LS.getLoadedType();
9775       if (TruncType != LoadedType &&
9776           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9777         ZExts = 1;
9778     }
9779
9780     /// \brief Account for slicing gain in the current cost.
9781     /// Slicing provide a few gains like removing a shift or a
9782     /// truncate. This method allows to grow the cost of the original
9783     /// load with the gain from this slice.
9784     void addSliceGain(const LoadedSlice &LS) {
9785       // Each slice saves a truncate.
9786       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9787       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9788                               LS.Inst->getValueType(0)))
9789         ++Truncates;
9790       // If there is a shift amount, this slice gets rid of it.
9791       if (LS.Shift)
9792         ++Shift;
9793       // If this slice can merge a cross register bank copy, account for it.
9794       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9795         ++CrossRegisterBanksCopies;
9796     }
9797
9798     Cost &operator+=(const Cost &RHS) {
9799       Loads += RHS.Loads;
9800       Truncates += RHS.Truncates;
9801       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9802       ZExts += RHS.ZExts;
9803       Shift += RHS.Shift;
9804       return *this;
9805     }
9806
9807     bool operator==(const Cost &RHS) const {
9808       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9809              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9810              ZExts == RHS.ZExts && Shift == RHS.Shift;
9811     }
9812
9813     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9814
9815     bool operator<(const Cost &RHS) const {
9816       // Assume cross register banks copies are as expensive as loads.
9817       // FIXME: Do we want some more target hooks?
9818       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9819       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9820       // Unless we are optimizing for code size, consider the
9821       // expensive operation first.
9822       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9823         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9824       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9825              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9826     }
9827
9828     bool operator>(const Cost &RHS) const { return RHS < *this; }
9829
9830     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9831
9832     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9833   };
9834   // The last instruction that represent the slice. This should be a
9835   // truncate instruction.
9836   SDNode *Inst;
9837   // The original load instruction.
9838   LoadSDNode *Origin;
9839   // The right shift amount in bits from the original load.
9840   unsigned Shift;
9841   // The DAG from which Origin came from.
9842   // This is used to get some contextual information about legal types, etc.
9843   SelectionDAG *DAG;
9844
9845   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9846               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9847       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9848
9849   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9850   /// \return Result is \p BitWidth and has used bits set to 1 and
9851   ///         not used bits set to 0.
9852   APInt getUsedBits() const {
9853     // Reproduce the trunc(lshr) sequence:
9854     // - Start from the truncated value.
9855     // - Zero extend to the desired bit width.
9856     // - Shift left.
9857     assert(Origin && "No original load to compare against.");
9858     unsigned BitWidth = Origin->getValueSizeInBits(0);
9859     assert(Inst && "This slice is not bound to an instruction");
9860     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9861            "Extracted slice is bigger than the whole type!");
9862     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9863     UsedBits.setAllBits();
9864     UsedBits = UsedBits.zext(BitWidth);
9865     UsedBits <<= Shift;
9866     return UsedBits;
9867   }
9868
9869   /// \brief Get the size of the slice to be loaded in bytes.
9870   unsigned getLoadedSize() const {
9871     unsigned SliceSize = getUsedBits().countPopulation();
9872     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9873     return SliceSize / 8;
9874   }
9875
9876   /// \brief Get the type that will be loaded for this slice.
9877   /// Note: This may not be the final type for the slice.
9878   EVT getLoadedType() const {
9879     assert(DAG && "Missing context");
9880     LLVMContext &Ctxt = *DAG->getContext();
9881     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9882   }
9883
9884   /// \brief Get the alignment of the load used for this slice.
9885   unsigned getAlignment() const {
9886     unsigned Alignment = Origin->getAlignment();
9887     unsigned Offset = getOffsetFromBase();
9888     if (Offset != 0)
9889       Alignment = MinAlign(Alignment, Alignment + Offset);
9890     return Alignment;
9891   }
9892
9893   /// \brief Check if this slice can be rewritten with legal operations.
9894   bool isLegal() const {
9895     // An invalid slice is not legal.
9896     if (!Origin || !Inst || !DAG)
9897       return false;
9898
9899     // Offsets are for indexed load only, we do not handle that.
9900     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9901       return false;
9902
9903     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9904
9905     // Check that the type is legal.
9906     EVT SliceType = getLoadedType();
9907     if (!TLI.isTypeLegal(SliceType))
9908       return false;
9909
9910     // Check that the load is legal for this type.
9911     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9912       return false;
9913
9914     // Check that the offset can be computed.
9915     // 1. Check its type.
9916     EVT PtrType = Origin->getBasePtr().getValueType();
9917     if (PtrType == MVT::Untyped || PtrType.isExtended())
9918       return false;
9919
9920     // 2. Check that it fits in the immediate.
9921     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9922       return false;
9923
9924     // 3. Check that the computation is legal.
9925     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9926       return false;
9927
9928     // Check that the zext is legal if it needs one.
9929     EVT TruncateType = Inst->getValueType(0);
9930     if (TruncateType != SliceType &&
9931         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9932       return false;
9933
9934     return true;
9935   }
9936
9937   /// \brief Get the offset in bytes of this slice in the original chunk of
9938   /// bits.
9939   /// \pre DAG != nullptr.
9940   uint64_t getOffsetFromBase() const {
9941     assert(DAG && "Missing context.");
9942     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9943     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9944     uint64_t Offset = Shift / 8;
9945     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9946     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9947            "The size of the original loaded type is not a multiple of a"
9948            " byte.");
9949     // If Offset is bigger than TySizeInBytes, it means we are loading all
9950     // zeros. This should have been optimized before in the process.
9951     assert(TySizeInBytes > Offset &&
9952            "Invalid shift amount for given loaded size");
9953     if (IsBigEndian)
9954       Offset = TySizeInBytes - Offset - getLoadedSize();
9955     return Offset;
9956   }
9957
9958   /// \brief Generate the sequence of instructions to load the slice
9959   /// represented by this object and redirect the uses of this slice to
9960   /// this new sequence of instructions.
9961   /// \pre this->Inst && this->Origin are valid Instructions and this
9962   /// object passed the legal check: LoadedSlice::isLegal returned true.
9963   /// \return The last instruction of the sequence used to load the slice.
9964   SDValue loadSlice() const {
9965     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9966     const SDValue &OldBaseAddr = Origin->getBasePtr();
9967     SDValue BaseAddr = OldBaseAddr;
9968     // Get the offset in that chunk of bytes w.r.t. the endianess.
9969     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9970     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9971     if (Offset) {
9972       // BaseAddr = BaseAddr + Offset.
9973       EVT ArithType = BaseAddr.getValueType();
9974       SDLoc DL(Origin);
9975       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9976                               DAG->getConstant(Offset, DL, ArithType));
9977     }
9978
9979     // Create the type of the loaded slice according to its size.
9980     EVT SliceType = getLoadedType();
9981
9982     // Create the load for the slice.
9983     SDValue LastInst = DAG->getLoad(
9984         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9985         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9986         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9987     // If the final type is not the same as the loaded type, this means that
9988     // we have to pad with zero. Create a zero extend for that.
9989     EVT FinalType = Inst->getValueType(0);
9990     if (SliceType != FinalType)
9991       LastInst =
9992           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9993     return LastInst;
9994   }
9995
9996   /// \brief Check if this slice can be merged with an expensive cross register
9997   /// bank copy. E.g.,
9998   /// i = load i32
9999   /// f = bitcast i32 i to float
10000   bool canMergeExpensiveCrossRegisterBankCopy() const {
10001     if (!Inst || !Inst->hasOneUse())
10002       return false;
10003     SDNode *Use = *Inst->use_begin();
10004     if (Use->getOpcode() != ISD::BITCAST)
10005       return false;
10006     assert(DAG && "Missing context");
10007     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10008     EVT ResVT = Use->getValueType(0);
10009     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10010     const TargetRegisterClass *ArgRC =
10011         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10012     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10013       return false;
10014
10015     // At this point, we know that we perform a cross-register-bank copy.
10016     // Check if it is expensive.
10017     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10018     // Assume bitcasts are cheap, unless both register classes do not
10019     // explicitly share a common sub class.
10020     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10021       return false;
10022
10023     // Check if it will be merged with the load.
10024     // 1. Check the alignment constraint.
10025     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10026         ResVT.getTypeForEVT(*DAG->getContext()));
10027
10028     if (RequiredAlignment > getAlignment())
10029       return false;
10030
10031     // 2. Check that the load is a legal operation for that type.
10032     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10033       return false;
10034
10035     // 3. Check that we do not have a zext in the way.
10036     if (Inst->getValueType(0) != getLoadedType())
10037       return false;
10038
10039     return true;
10040   }
10041 };
10042 }
10043
10044 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10045 /// \p UsedBits looks like 0..0 1..1 0..0.
10046 static bool areUsedBitsDense(const APInt &UsedBits) {
10047   // If all the bits are one, this is dense!
10048   if (UsedBits.isAllOnesValue())
10049     return true;
10050
10051   // Get rid of the unused bits on the right.
10052   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10053   // Get rid of the unused bits on the left.
10054   if (NarrowedUsedBits.countLeadingZeros())
10055     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10056   // Check that the chunk of bits is completely used.
10057   return NarrowedUsedBits.isAllOnesValue();
10058 }
10059
10060 /// \brief Check whether or not \p First and \p Second are next to each other
10061 /// in memory. This means that there is no hole between the bits loaded
10062 /// by \p First and the bits loaded by \p Second.
10063 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10064                                      const LoadedSlice &Second) {
10065   assert(First.Origin == Second.Origin && First.Origin &&
10066          "Unable to match different memory origins.");
10067   APInt UsedBits = First.getUsedBits();
10068   assert((UsedBits & Second.getUsedBits()) == 0 &&
10069          "Slices are not supposed to overlap.");
10070   UsedBits |= Second.getUsedBits();
10071   return areUsedBitsDense(UsedBits);
10072 }
10073
10074 /// \brief Adjust the \p GlobalLSCost according to the target
10075 /// paring capabilities and the layout of the slices.
10076 /// \pre \p GlobalLSCost should account for at least as many loads as
10077 /// there is in the slices in \p LoadedSlices.
10078 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10079                                  LoadedSlice::Cost &GlobalLSCost) {
10080   unsigned NumberOfSlices = LoadedSlices.size();
10081   // If there is less than 2 elements, no pairing is possible.
10082   if (NumberOfSlices < 2)
10083     return;
10084
10085   // Sort the slices so that elements that are likely to be next to each
10086   // other in memory are next to each other in the list.
10087   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10088             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10089     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10090     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10091   });
10092   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10093   // First (resp. Second) is the first (resp. Second) potentially candidate
10094   // to be placed in a paired load.
10095   const LoadedSlice *First = nullptr;
10096   const LoadedSlice *Second = nullptr;
10097   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10098                 // Set the beginning of the pair.
10099                                                            First = Second) {
10100
10101     Second = &LoadedSlices[CurrSlice];
10102
10103     // If First is NULL, it means we start a new pair.
10104     // Get to the next slice.
10105     if (!First)
10106       continue;
10107
10108     EVT LoadedType = First->getLoadedType();
10109
10110     // If the types of the slices are different, we cannot pair them.
10111     if (LoadedType != Second->getLoadedType())
10112       continue;
10113
10114     // Check if the target supplies paired loads for this type.
10115     unsigned RequiredAlignment = 0;
10116     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10117       // move to the next pair, this type is hopeless.
10118       Second = nullptr;
10119       continue;
10120     }
10121     // Check if we meet the alignment requirement.
10122     if (RequiredAlignment > First->getAlignment())
10123       continue;
10124
10125     // Check that both loads are next to each other in memory.
10126     if (!areSlicesNextToEachOther(*First, *Second))
10127       continue;
10128
10129     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10130     --GlobalLSCost.Loads;
10131     // Move to the next pair.
10132     Second = nullptr;
10133   }
10134 }
10135
10136 /// \brief Check the profitability of all involved LoadedSlice.
10137 /// Currently, it is considered profitable if there is exactly two
10138 /// involved slices (1) which are (2) next to each other in memory, and
10139 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10140 ///
10141 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10142 /// the elements themselves.
10143 ///
10144 /// FIXME: When the cost model will be mature enough, we can relax
10145 /// constraints (1) and (2).
10146 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10147                                 const APInt &UsedBits, bool ForCodeSize) {
10148   unsigned NumberOfSlices = LoadedSlices.size();
10149   if (StressLoadSlicing)
10150     return NumberOfSlices > 1;
10151
10152   // Check (1).
10153   if (NumberOfSlices != 2)
10154     return false;
10155
10156   // Check (2).
10157   if (!areUsedBitsDense(UsedBits))
10158     return false;
10159
10160   // Check (3).
10161   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10162   // The original code has one big load.
10163   OrigCost.Loads = 1;
10164   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10165     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10166     // Accumulate the cost of all the slices.
10167     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10168     GlobalSlicingCost += SliceCost;
10169
10170     // Account as cost in the original configuration the gain obtained
10171     // with the current slices.
10172     OrigCost.addSliceGain(LS);
10173   }
10174
10175   // If the target supports paired load, adjust the cost accordingly.
10176   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10177   return OrigCost > GlobalSlicingCost;
10178 }
10179
10180 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10181 /// operations, split it in the various pieces being extracted.
10182 ///
10183 /// This sort of thing is introduced by SROA.
10184 /// This slicing takes care not to insert overlapping loads.
10185 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10186 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10187   if (Level < AfterLegalizeDAG)
10188     return false;
10189
10190   LoadSDNode *LD = cast<LoadSDNode>(N);
10191   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10192       !LD->getValueType(0).isInteger())
10193     return false;
10194
10195   // Keep track of already used bits to detect overlapping values.
10196   // In that case, we will just abort the transformation.
10197   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10198
10199   SmallVector<LoadedSlice, 4> LoadedSlices;
10200
10201   // Check if this load is used as several smaller chunks of bits.
10202   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10203   // of computation for each trunc.
10204   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10205        UI != UIEnd; ++UI) {
10206     // Skip the uses of the chain.
10207     if (UI.getUse().getResNo() != 0)
10208       continue;
10209
10210     SDNode *User = *UI;
10211     unsigned Shift = 0;
10212
10213     // Check if this is a trunc(lshr).
10214     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10215         isa<ConstantSDNode>(User->getOperand(1))) {
10216       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10217       User = *User->use_begin();
10218     }
10219
10220     // At this point, User is a Truncate, iff we encountered, trunc or
10221     // trunc(lshr).
10222     if (User->getOpcode() != ISD::TRUNCATE)
10223       return false;
10224
10225     // The width of the type must be a power of 2 and greater than 8-bits.
10226     // Otherwise the load cannot be represented in LLVM IR.
10227     // Moreover, if we shifted with a non-8-bits multiple, the slice
10228     // will be across several bytes. We do not support that.
10229     unsigned Width = User->getValueSizeInBits(0);
10230     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10231       return 0;
10232
10233     // Build the slice for this chain of computations.
10234     LoadedSlice LS(User, LD, Shift, &DAG);
10235     APInt CurrentUsedBits = LS.getUsedBits();
10236
10237     // Check if this slice overlaps with another.
10238     if ((CurrentUsedBits & UsedBits) != 0)
10239       return false;
10240     // Update the bits used globally.
10241     UsedBits |= CurrentUsedBits;
10242
10243     // Check if the new slice would be legal.
10244     if (!LS.isLegal())
10245       return false;
10246
10247     // Record the slice.
10248     LoadedSlices.push_back(LS);
10249   }
10250
10251   // Abort slicing if it does not seem to be profitable.
10252   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10253     return false;
10254
10255   ++SlicedLoads;
10256
10257   // Rewrite each chain to use an independent load.
10258   // By construction, each chain can be represented by a unique load.
10259
10260   // Prepare the argument for the new token factor for all the slices.
10261   SmallVector<SDValue, 8> ArgChains;
10262   for (SmallVectorImpl<LoadedSlice>::const_iterator
10263            LSIt = LoadedSlices.begin(),
10264            LSItEnd = LoadedSlices.end();
10265        LSIt != LSItEnd; ++LSIt) {
10266     SDValue SliceInst = LSIt->loadSlice();
10267     CombineTo(LSIt->Inst, SliceInst, true);
10268     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10269       SliceInst = SliceInst.getOperand(0);
10270     assert(SliceInst->getOpcode() == ISD::LOAD &&
10271            "It takes more than a zext to get to the loaded slice!!");
10272     ArgChains.push_back(SliceInst.getValue(1));
10273   }
10274
10275   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10276                               ArgChains);
10277   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10278   return true;
10279 }
10280
10281 /// Check to see if V is (and load (ptr), imm), where the load is having
10282 /// specific bytes cleared out.  If so, return the byte size being masked out
10283 /// and the shift amount.
10284 static std::pair<unsigned, unsigned>
10285 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10286   std::pair<unsigned, unsigned> Result(0, 0);
10287
10288   // Check for the structure we're looking for.
10289   if (V->getOpcode() != ISD::AND ||
10290       !isa<ConstantSDNode>(V->getOperand(1)) ||
10291       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10292     return Result;
10293
10294   // Check the chain and pointer.
10295   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10296   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10297
10298   // The store should be chained directly to the load or be an operand of a
10299   // tokenfactor.
10300   if (LD == Chain.getNode())
10301     ; // ok.
10302   else if (Chain->getOpcode() != ISD::TokenFactor)
10303     return Result; // Fail.
10304   else {
10305     bool isOk = false;
10306     for (const SDValue &ChainOp : Chain->op_values())
10307       if (ChainOp.getNode() == LD) {
10308         isOk = true;
10309         break;
10310       }
10311     if (!isOk) return Result;
10312   }
10313
10314   // This only handles simple types.
10315   if (V.getValueType() != MVT::i16 &&
10316       V.getValueType() != MVT::i32 &&
10317       V.getValueType() != MVT::i64)
10318     return Result;
10319
10320   // Check the constant mask.  Invert it so that the bits being masked out are
10321   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10322   // follow the sign bit for uniformity.
10323   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10324   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10325   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10326   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10327   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10328   if (NotMaskLZ == 64) return Result;  // All zero mask.
10329
10330   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10331   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10332     return Result;
10333
10334   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10335   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10336     NotMaskLZ -= 64-V.getValueSizeInBits();
10337
10338   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10339   switch (MaskedBytes) {
10340   case 1:
10341   case 2:
10342   case 4: break;
10343   default: return Result; // All one mask, or 5-byte mask.
10344   }
10345
10346   // Verify that the first bit starts at a multiple of mask so that the access
10347   // is aligned the same as the access width.
10348   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10349
10350   Result.first = MaskedBytes;
10351   Result.second = NotMaskTZ/8;
10352   return Result;
10353 }
10354
10355
10356 /// Check to see if IVal is something that provides a value as specified by
10357 /// MaskInfo. If so, replace the specified store with a narrower store of
10358 /// truncated IVal.
10359 static SDNode *
10360 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10361                                 SDValue IVal, StoreSDNode *St,
10362                                 DAGCombiner *DC) {
10363   unsigned NumBytes = MaskInfo.first;
10364   unsigned ByteShift = MaskInfo.second;
10365   SelectionDAG &DAG = DC->getDAG();
10366
10367   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10368   // that uses this.  If not, this is not a replacement.
10369   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10370                                   ByteShift*8, (ByteShift+NumBytes)*8);
10371   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10372
10373   // Check that it is legal on the target to do this.  It is legal if the new
10374   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10375   // legalization.
10376   MVT VT = MVT::getIntegerVT(NumBytes*8);
10377   if (!DC->isTypeLegal(VT))
10378     return nullptr;
10379
10380   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10381   // shifted by ByteShift and truncated down to NumBytes.
10382   if (ByteShift) {
10383     SDLoc DL(IVal);
10384     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10385                        DAG.getConstant(ByteShift*8, DL,
10386                                     DC->getShiftAmountTy(IVal.getValueType())));
10387   }
10388
10389   // Figure out the offset for the store and the alignment of the access.
10390   unsigned StOffset;
10391   unsigned NewAlign = St->getAlignment();
10392
10393   if (DAG.getDataLayout().isLittleEndian())
10394     StOffset = ByteShift;
10395   else
10396     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10397
10398   SDValue Ptr = St->getBasePtr();
10399   if (StOffset) {
10400     SDLoc DL(IVal);
10401     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10402                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10403     NewAlign = MinAlign(NewAlign, StOffset);
10404   }
10405
10406   // Truncate down to the new size.
10407   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10408
10409   ++OpsNarrowed;
10410   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10411                       St->getPointerInfo().getWithOffset(StOffset),
10412                       false, false, NewAlign).getNode();
10413 }
10414
10415
10416 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10417 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10418 /// narrowing the load and store if it would end up being a win for performance
10419 /// or code size.
10420 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10421   StoreSDNode *ST  = cast<StoreSDNode>(N);
10422   if (ST->isVolatile())
10423     return SDValue();
10424
10425   SDValue Chain = ST->getChain();
10426   SDValue Value = ST->getValue();
10427   SDValue Ptr   = ST->getBasePtr();
10428   EVT VT = Value.getValueType();
10429
10430   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10431     return SDValue();
10432
10433   unsigned Opc = Value.getOpcode();
10434
10435   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10436   // is a byte mask indicating a consecutive number of bytes, check to see if
10437   // Y is known to provide just those bytes.  If so, we try to replace the
10438   // load + replace + store sequence with a single (narrower) store, which makes
10439   // the load dead.
10440   if (Opc == ISD::OR) {
10441     std::pair<unsigned, unsigned> MaskedLoad;
10442     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10443     if (MaskedLoad.first)
10444       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10445                                                   Value.getOperand(1), ST,this))
10446         return SDValue(NewST, 0);
10447
10448     // Or is commutative, so try swapping X and Y.
10449     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10450     if (MaskedLoad.first)
10451       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10452                                                   Value.getOperand(0), ST,this))
10453         return SDValue(NewST, 0);
10454   }
10455
10456   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10457       Value.getOperand(1).getOpcode() != ISD::Constant)
10458     return SDValue();
10459
10460   SDValue N0 = Value.getOperand(0);
10461   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10462       Chain == SDValue(N0.getNode(), 1)) {
10463     LoadSDNode *LD = cast<LoadSDNode>(N0);
10464     if (LD->getBasePtr() != Ptr ||
10465         LD->getPointerInfo().getAddrSpace() !=
10466         ST->getPointerInfo().getAddrSpace())
10467       return SDValue();
10468
10469     // Find the type to narrow it the load / op / store to.
10470     SDValue N1 = Value.getOperand(1);
10471     unsigned BitWidth = N1.getValueSizeInBits();
10472     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10473     if (Opc == ISD::AND)
10474       Imm ^= APInt::getAllOnesValue(BitWidth);
10475     if (Imm == 0 || Imm.isAllOnesValue())
10476       return SDValue();
10477     unsigned ShAmt = Imm.countTrailingZeros();
10478     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10479     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10480     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10481     // The narrowing should be profitable, the load/store operation should be
10482     // legal (or custom) and the store size should be equal to the NewVT width.
10483     while (NewBW < BitWidth &&
10484            (NewVT.getStoreSizeInBits() != NewBW ||
10485             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10486             !TLI.isNarrowingProfitable(VT, NewVT))) {
10487       NewBW = NextPowerOf2(NewBW);
10488       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10489     }
10490     if (NewBW >= BitWidth)
10491       return SDValue();
10492
10493     // If the lsb changed does not start at the type bitwidth boundary,
10494     // start at the previous one.
10495     if (ShAmt % NewBW)
10496       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10497     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10498                                    std::min(BitWidth, ShAmt + NewBW));
10499     if ((Imm & Mask) == Imm) {
10500       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10501       if (Opc == ISD::AND)
10502         NewImm ^= APInt::getAllOnesValue(NewBW);
10503       uint64_t PtrOff = ShAmt / 8;
10504       // For big endian targets, we need to adjust the offset to the pointer to
10505       // load the correct bytes.
10506       if (DAG.getDataLayout().isBigEndian())
10507         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10508
10509       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10510       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10511       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10512         return SDValue();
10513
10514       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10515                                    Ptr.getValueType(), Ptr,
10516                                    DAG.getConstant(PtrOff, SDLoc(LD),
10517                                                    Ptr.getValueType()));
10518       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10519                                   LD->getChain(), NewPtr,
10520                                   LD->getPointerInfo().getWithOffset(PtrOff),
10521                                   LD->isVolatile(), LD->isNonTemporal(),
10522                                   LD->isInvariant(), NewAlign,
10523                                   LD->getAAInfo());
10524       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10525                                    DAG.getConstant(NewImm, SDLoc(Value),
10526                                                    NewVT));
10527       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10528                                    NewVal, NewPtr,
10529                                    ST->getPointerInfo().getWithOffset(PtrOff),
10530                                    false, false, NewAlign);
10531
10532       AddToWorklist(NewPtr.getNode());
10533       AddToWorklist(NewLD.getNode());
10534       AddToWorklist(NewVal.getNode());
10535       WorklistRemover DeadNodes(*this);
10536       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10537       ++OpsNarrowed;
10538       return NewST;
10539     }
10540   }
10541
10542   return SDValue();
10543 }
10544
10545 /// For a given floating point load / store pair, if the load value isn't used
10546 /// by any other operations, then consider transforming the pair to integer
10547 /// load / store operations if the target deems the transformation profitable.
10548 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10549   StoreSDNode *ST  = cast<StoreSDNode>(N);
10550   SDValue Chain = ST->getChain();
10551   SDValue Value = ST->getValue();
10552   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10553       Value.hasOneUse() &&
10554       Chain == SDValue(Value.getNode(), 1)) {
10555     LoadSDNode *LD = cast<LoadSDNode>(Value);
10556     EVT VT = LD->getMemoryVT();
10557     if (!VT.isFloatingPoint() ||
10558         VT != ST->getMemoryVT() ||
10559         LD->isNonTemporal() ||
10560         ST->isNonTemporal() ||
10561         LD->getPointerInfo().getAddrSpace() != 0 ||
10562         ST->getPointerInfo().getAddrSpace() != 0)
10563       return SDValue();
10564
10565     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10566     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10567         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10568         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10569         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10570       return SDValue();
10571
10572     unsigned LDAlign = LD->getAlignment();
10573     unsigned STAlign = ST->getAlignment();
10574     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10575     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10576     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10577       return SDValue();
10578
10579     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10580                                 LD->getChain(), LD->getBasePtr(),
10581                                 LD->getPointerInfo(),
10582                                 false, false, false, LDAlign);
10583
10584     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10585                                  NewLD, ST->getBasePtr(),
10586                                  ST->getPointerInfo(),
10587                                  false, false, STAlign);
10588
10589     AddToWorklist(NewLD.getNode());
10590     AddToWorklist(NewST.getNode());
10591     WorklistRemover DeadNodes(*this);
10592     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10593     ++LdStFP2Int;
10594     return NewST;
10595   }
10596
10597   return SDValue();
10598 }
10599
10600 namespace {
10601 /// Helper struct to parse and store a memory address as base + index + offset.
10602 /// We ignore sign extensions when it is safe to do so.
10603 /// The following two expressions are not equivalent. To differentiate we need
10604 /// to store whether there was a sign extension involved in the index
10605 /// computation.
10606 ///  (load (i64 add (i64 copyfromreg %c)
10607 ///                 (i64 signextend (add (i8 load %index)
10608 ///                                      (i8 1))))
10609 /// vs
10610 ///
10611 /// (load (i64 add (i64 copyfromreg %c)
10612 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10613 ///                                         (i32 1)))))
10614 struct BaseIndexOffset {
10615   SDValue Base;
10616   SDValue Index;
10617   int64_t Offset;
10618   bool IsIndexSignExt;
10619
10620   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10621
10622   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10623                   bool IsIndexSignExt) :
10624     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10625
10626   bool equalBaseIndex(const BaseIndexOffset &Other) {
10627     return Other.Base == Base && Other.Index == Index &&
10628       Other.IsIndexSignExt == IsIndexSignExt;
10629   }
10630
10631   /// Parses tree in Ptr for base, index, offset addresses.
10632   static BaseIndexOffset match(SDValue Ptr) {
10633     bool IsIndexSignExt = false;
10634
10635     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10636     // instruction, then it could be just the BASE or everything else we don't
10637     // know how to handle. Just use Ptr as BASE and give up.
10638     if (Ptr->getOpcode() != ISD::ADD)
10639       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10640
10641     // We know that we have at least an ADD instruction. Try to pattern match
10642     // the simple case of BASE + OFFSET.
10643     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10644       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10645       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10646                               IsIndexSignExt);
10647     }
10648
10649     // Inside a loop the current BASE pointer is calculated using an ADD and a
10650     // MUL instruction. In this case Ptr is the actual BASE pointer.
10651     // (i64 add (i64 %array_ptr)
10652     //          (i64 mul (i64 %induction_var)
10653     //                   (i64 %element_size)))
10654     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10655       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10656
10657     // Look at Base + Index + Offset cases.
10658     SDValue Base = Ptr->getOperand(0);
10659     SDValue IndexOffset = Ptr->getOperand(1);
10660
10661     // Skip signextends.
10662     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10663       IndexOffset = IndexOffset->getOperand(0);
10664       IsIndexSignExt = true;
10665     }
10666
10667     // Either the case of Base + Index (no offset) or something else.
10668     if (IndexOffset->getOpcode() != ISD::ADD)
10669       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10670
10671     // Now we have the case of Base + Index + offset.
10672     SDValue Index = IndexOffset->getOperand(0);
10673     SDValue Offset = IndexOffset->getOperand(1);
10674
10675     if (!isa<ConstantSDNode>(Offset))
10676       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10677
10678     // Ignore signextends.
10679     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10680       Index = Index->getOperand(0);
10681       IsIndexSignExt = true;
10682     } else IsIndexSignExt = false;
10683
10684     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10685     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10686   }
10687 };
10688 } // namespace
10689
10690 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10691                                                   SDLoc SL,
10692                                                   ArrayRef<MemOpLink> Stores,
10693                                                   EVT Ty) const {
10694   SmallVector<SDValue, 8> BuildVector;
10695
10696   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10697     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10698
10699   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10700 }
10701
10702 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10703                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10704                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10705   // Make sure we have something to merge.
10706   if (NumElem < 2)
10707     return false;
10708
10709   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10710   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10711   unsigned LatestNodeUsed = 0;
10712
10713   for (unsigned i=0; i < NumElem; ++i) {
10714     // Find a chain for the new wide-store operand. Notice that some
10715     // of the store nodes that we found may not be selected for inclusion
10716     // in the wide store. The chain we use needs to be the chain of the
10717     // latest store node which is *used* and replaced by the wide store.
10718     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10719       LatestNodeUsed = i;
10720   }
10721
10722   // The latest Node in the DAG.
10723   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10724   SDLoc DL(StoreNodes[0].MemNode);
10725
10726   SDValue StoredVal;
10727   if (UseVector) {
10728     // Find a legal type for the vector store.
10729     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10730     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10731     if (IsConstantSrc) {
10732       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10733     } else {
10734       SmallVector<SDValue, 8> Ops;
10735       for (unsigned i = 0; i < NumElem ; ++i) {
10736         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10737         SDValue Val = St->getValue();
10738         // All of the operands of a BUILD_VECTOR must have the same type.
10739         if (Val.getValueType() != MemVT)
10740           return false;
10741         Ops.push_back(Val);
10742       }
10743
10744       // Build the extracted vector elements back into a vector.
10745       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10746     }
10747   } else {
10748     // We should always use a vector store when merging extracted vector
10749     // elements, so this path implies a store of constants.
10750     assert(IsConstantSrc && "Merged vector elements should use vector store");
10751
10752     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10753     APInt StoreInt(SizeInBits, 0);
10754
10755     // Construct a single integer constant which is made of the smaller
10756     // constant inputs.
10757     bool IsLE = DAG.getDataLayout().isLittleEndian();
10758     for (unsigned i = 0; i < NumElem ; ++i) {
10759       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10760       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10761       SDValue Val = St->getValue();
10762       StoreInt <<= ElementSizeBytes * 8;
10763       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10764         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10765       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10766         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10767       } else {
10768         llvm_unreachable("Invalid constant element type");
10769       }
10770     }
10771
10772     // Create the new Load and Store operations.
10773     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10774     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10775   }
10776
10777   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10778                                   FirstInChain->getBasePtr(),
10779                                   FirstInChain->getPointerInfo(),
10780                                   false, false,
10781                                   FirstInChain->getAlignment());
10782
10783   // Replace the last store with the new store
10784   CombineTo(LatestOp, NewStore);
10785   // Erase all other stores.
10786   for (unsigned i = 0; i < NumElem ; ++i) {
10787     if (StoreNodes[i].MemNode == LatestOp)
10788       continue;
10789     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10790     // ReplaceAllUsesWith will replace all uses that existed when it was
10791     // called, but graph optimizations may cause new ones to appear. For
10792     // example, the case in pr14333 looks like
10793     //
10794     //  St's chain -> St -> another store -> X
10795     //
10796     // And the only difference from St to the other store is the chain.
10797     // When we change it's chain to be St's chain they become identical,
10798     // get CSEed and the net result is that X is now a use of St.
10799     // Since we know that St is redundant, just iterate.
10800     while (!St->use_empty())
10801       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10802     deleteAndRecombine(St);
10803   }
10804
10805   return true;
10806 }
10807
10808 void DAGCombiner::getStoreMergeAndAliasCandidates(
10809     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10810     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10811   // This holds the base pointer, index, and the offset in bytes from the base
10812   // pointer.
10813   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10814
10815   // We must have a base and an offset.
10816   if (!BasePtr.Base.getNode())
10817     return;
10818
10819   // Do not handle stores to undef base pointers.
10820   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10821     return;
10822
10823   // Walk up the chain and look for nodes with offsets from the same
10824   // base pointer. Stop when reaching an instruction with a different kind
10825   // or instruction which has a different base pointer.
10826   EVT MemVT = St->getMemoryVT();
10827   unsigned Seq = 0;
10828   StoreSDNode *Index = St;
10829   while (Index) {
10830     // If the chain has more than one use, then we can't reorder the mem ops.
10831     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10832       break;
10833
10834     // Find the base pointer and offset for this memory node.
10835     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10836
10837     // Check that the base pointer is the same as the original one.
10838     if (!Ptr.equalBaseIndex(BasePtr))
10839       break;
10840
10841     // The memory operands must not be volatile.
10842     if (Index->isVolatile() || Index->isIndexed())
10843       break;
10844
10845     // No truncation.
10846     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10847       if (St->isTruncatingStore())
10848         break;
10849
10850     // The stored memory type must be the same.
10851     if (Index->getMemoryVT() != MemVT)
10852       break;
10853
10854     // We found a potential memory operand to merge.
10855     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10856
10857     // Find the next memory operand in the chain. If the next operand in the
10858     // chain is a store then move up and continue the scan with the next
10859     // memory operand. If the next operand is a load save it and use alias
10860     // information to check if it interferes with anything.
10861     SDNode *NextInChain = Index->getChain().getNode();
10862     while (1) {
10863       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10864         // We found a store node. Use it for the next iteration.
10865         Index = STn;
10866         break;
10867       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10868         if (Ldn->isVolatile()) {
10869           Index = nullptr;
10870           break;
10871         }
10872
10873         // Save the load node for later. Continue the scan.
10874         AliasLoadNodes.push_back(Ldn);
10875         NextInChain = Ldn->getChain().getNode();
10876         continue;
10877       } else {
10878         Index = nullptr;
10879         break;
10880       }
10881     }
10882   }
10883 }
10884
10885 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10886   if (OptLevel == CodeGenOpt::None)
10887     return false;
10888
10889   EVT MemVT = St->getMemoryVT();
10890   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10891   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10892       Attribute::NoImplicitFloat);
10893
10894   // This function cannot currently deal with non-byte-sized memory sizes.
10895   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10896     return false;
10897
10898   // Don't merge vectors into wider inputs.
10899   if (MemVT.isVector() || !MemVT.isSimple())
10900     return false;
10901
10902   // Perform an early exit check. Do not bother looking at stored values that
10903   // are not constants, loads, or extracted vector elements.
10904   SDValue StoredVal = St->getValue();
10905   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10906   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10907                        isa<ConstantFPSDNode>(StoredVal);
10908   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10909
10910   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10911     return false;
10912
10913   // Only look at ends of store sequences.
10914   SDValue Chain = SDValue(St, 0);
10915   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10916     return false;
10917
10918   // Save the LoadSDNodes that we find in the chain.
10919   // We need to make sure that these nodes do not interfere with
10920   // any of the store nodes.
10921   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10922
10923   // Save the StoreSDNodes that we find in the chain.
10924   SmallVector<MemOpLink, 8> StoreNodes;
10925
10926   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10927
10928   // Check if there is anything to merge.
10929   if (StoreNodes.size() < 2)
10930     return false;
10931
10932   // Sort the memory operands according to their distance from the base pointer.
10933   std::sort(StoreNodes.begin(), StoreNodes.end(),
10934             [](MemOpLink LHS, MemOpLink RHS) {
10935     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10936            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10937             LHS.SequenceNum > RHS.SequenceNum);
10938   });
10939
10940   // Scan the memory operations on the chain and find the first non-consecutive
10941   // store memory address.
10942   unsigned LastConsecutiveStore = 0;
10943   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10944   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10945
10946     // Check that the addresses are consecutive starting from the second
10947     // element in the list of stores.
10948     if (i > 0) {
10949       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10950       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10951         break;
10952     }
10953
10954     bool Alias = false;
10955     // Check if this store interferes with any of the loads that we found.
10956     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10957       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10958         Alias = true;
10959         break;
10960       }
10961     // We found a load that alias with this store. Stop the sequence.
10962     if (Alias)
10963       break;
10964
10965     // Mark this node as useful.
10966     LastConsecutiveStore = i;
10967   }
10968
10969   // The node with the lowest store address.
10970   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10971   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10972   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10973   LLVMContext &Context = *DAG.getContext();
10974   const DataLayout &DL = DAG.getDataLayout();
10975
10976   // Store the constants into memory as one consecutive store.
10977   if (IsConstantSrc) {
10978     unsigned LastLegalType = 0;
10979     unsigned LastLegalVectorType = 0;
10980     bool NonZero = false;
10981     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10982       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10983       SDValue StoredVal = St->getValue();
10984
10985       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10986         NonZero |= !C->isNullValue();
10987       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10988         NonZero |= !C->getConstantFPValue()->isNullValue();
10989       } else {
10990         // Non-constant.
10991         break;
10992       }
10993
10994       // Find a legal type for the constant store.
10995       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10996       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
10997       if (TLI.isTypeLegal(StoreTy) &&
10998           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
10999                                  FirstStoreAlign)) {
11000         LastLegalType = i+1;
11001       // Or check whether a truncstore is legal.
11002       } else if (TLI.getTypeAction(Context, StoreTy) ==
11003                  TargetLowering::TypePromoteInteger) {
11004         EVT LegalizedStoredValueTy =
11005           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11006         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11007             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11008                                    FirstStoreAS, FirstStoreAlign)) {
11009           LastLegalType = i + 1;
11010         }
11011       }
11012
11013       // Find a legal type for the vector store.
11014       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11015       if (TLI.isTypeLegal(Ty) &&
11016           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11017                                  FirstStoreAlign)) {
11018         LastLegalVectorType = i + 1;
11019       }
11020     }
11021
11022
11023     // We only use vectors if the constant is known to be zero or the target
11024     // allows it and the function is not marked with the noimplicitfloat
11025     // attribute.
11026     if (NoVectors) {
11027       LastLegalVectorType = 0;
11028     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
11029                                                             LastLegalVectorType,
11030                                                             FirstStoreAS)) {
11031       LastLegalVectorType = 0;
11032     }
11033
11034     // Check if we found a legal integer type to store.
11035     if (LastLegalType == 0 && LastLegalVectorType == 0)
11036       return false;
11037
11038     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11039     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11040
11041     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11042                                            true, UseVector);
11043   }
11044
11045   // When extracting multiple vector elements, try to store them
11046   // in one vector store rather than a sequence of scalar stores.
11047   if (IsExtractVecEltSrc) {
11048     unsigned NumElem = 0;
11049     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11050       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11051       SDValue StoredVal = St->getValue();
11052       // This restriction could be loosened.
11053       // Bail out if any stored values are not elements extracted from a vector.
11054       // It should be possible to handle mixed sources, but load sources need
11055       // more careful handling (see the block of code below that handles
11056       // consecutive loads).
11057       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11058         return false;
11059
11060       // Find a legal type for the vector store.
11061       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11062       if (TLI.isTypeLegal(Ty) &&
11063           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11064                                  FirstStoreAlign))
11065         NumElem = i + 1;
11066     }
11067
11068     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11069                                            false, true);
11070   }
11071
11072   // Below we handle the case of multiple consecutive stores that
11073   // come from multiple consecutive loads. We merge them into a single
11074   // wide load and a single wide store.
11075
11076   // Look for load nodes which are used by the stored values.
11077   SmallVector<MemOpLink, 8> LoadNodes;
11078
11079   // Find acceptable loads. Loads need to have the same chain (token factor),
11080   // must not be zext, volatile, indexed, and they must be consecutive.
11081   BaseIndexOffset LdBasePtr;
11082   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11083     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11084     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11085     if (!Ld) break;
11086
11087     // Loads must only have one use.
11088     if (!Ld->hasNUsesOfValue(1, 0))
11089       break;
11090
11091     // The memory operands must not be volatile.
11092     if (Ld->isVolatile() || Ld->isIndexed())
11093       break;
11094
11095     // We do not accept ext loads.
11096     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11097       break;
11098
11099     // The stored memory type must be the same.
11100     if (Ld->getMemoryVT() != MemVT)
11101       break;
11102
11103     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11104     // If this is not the first ptr that we check.
11105     if (LdBasePtr.Base.getNode()) {
11106       // The base ptr must be the same.
11107       if (!LdPtr.equalBaseIndex(LdBasePtr))
11108         break;
11109     } else {
11110       // Check that all other base pointers are the same as this one.
11111       LdBasePtr = LdPtr;
11112     }
11113
11114     // We found a potential memory operand to merge.
11115     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11116   }
11117
11118   if (LoadNodes.size() < 2)
11119     return false;
11120
11121   // If we have load/store pair instructions and we only have two values,
11122   // don't bother.
11123   unsigned RequiredAlignment;
11124   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11125       St->getAlignment() >= RequiredAlignment)
11126     return false;
11127
11128   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11129   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11130   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11131
11132   // Scan the memory operations on the chain and find the first non-consecutive
11133   // load memory address. These variables hold the index in the store node
11134   // array.
11135   unsigned LastConsecutiveLoad = 0;
11136   // This variable refers to the size and not index in the array.
11137   unsigned LastLegalVectorType = 0;
11138   unsigned LastLegalIntegerType = 0;
11139   StartAddress = LoadNodes[0].OffsetFromBase;
11140   SDValue FirstChain = FirstLoad->getChain();
11141   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11142     // All loads much share the same chain.
11143     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11144       break;
11145
11146     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11147     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11148       break;
11149     LastConsecutiveLoad = i;
11150
11151     // Find a legal type for the vector store.
11152     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11153     if (TLI.isTypeLegal(StoreTy) &&
11154         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11155                                FirstStoreAlign) &&
11156         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11157                                FirstLoadAlign)) {
11158       LastLegalVectorType = i + 1;
11159     }
11160
11161     // Find a legal type for the integer store.
11162     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11163     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11164     if (TLI.isTypeLegal(StoreTy) &&
11165         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11166                                FirstStoreAlign) &&
11167         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11168                                FirstLoadAlign))
11169       LastLegalIntegerType = i + 1;
11170     // Or check whether a truncstore and extload is legal.
11171     else if (TLI.getTypeAction(Context, StoreTy) ==
11172              TargetLowering::TypePromoteInteger) {
11173       EVT LegalizedStoredValueTy =
11174         TLI.getTypeToTransformTo(Context, StoreTy);
11175       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11176           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11177           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11178           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11179           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11180                                  FirstStoreAS, FirstStoreAlign) &&
11181           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11182                                  FirstLoadAS, FirstLoadAlign))
11183         LastLegalIntegerType = i+1;
11184     }
11185   }
11186
11187   // Only use vector types if the vector type is larger than the integer type.
11188   // If they are the same, use integers.
11189   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11190   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11191
11192   // We add +1 here because the LastXXX variables refer to location while
11193   // the NumElem refers to array/index size.
11194   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11195   NumElem = std::min(LastLegalType, NumElem);
11196
11197   if (NumElem < 2)
11198     return false;
11199
11200   // The latest Node in the DAG.
11201   unsigned LatestNodeUsed = 0;
11202   for (unsigned i=1; i<NumElem; ++i) {
11203     // Find a chain for the new wide-store operand. Notice that some
11204     // of the store nodes that we found may not be selected for inclusion
11205     // in the wide store. The chain we use needs to be the chain of the
11206     // latest store node which is *used* and replaced by the wide store.
11207     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11208       LatestNodeUsed = i;
11209   }
11210
11211   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11212
11213   // Find if it is better to use vectors or integers to load and store
11214   // to memory.
11215   EVT JointMemOpVT;
11216   if (UseVectorTy) {
11217     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11218   } else {
11219     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11220     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11221   }
11222
11223   SDLoc LoadDL(LoadNodes[0].MemNode);
11224   SDLoc StoreDL(StoreNodes[0].MemNode);
11225
11226   SDValue NewLoad = DAG.getLoad(
11227       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11228       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11229
11230   SDValue NewStore = DAG.getStore(
11231       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11232       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11233
11234   // Replace one of the loads with the new load.
11235   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11236   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11237                                 SDValue(NewLoad.getNode(), 1));
11238
11239   // Remove the rest of the load chains.
11240   for (unsigned i = 1; i < NumElem ; ++i) {
11241     // Replace all chain users of the old load nodes with the chain of the new
11242     // load node.
11243     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11244     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11245   }
11246
11247   // Replace the last store with the new store.
11248   CombineTo(LatestOp, NewStore);
11249   // Erase all other stores.
11250   for (unsigned i = 0; i < NumElem ; ++i) {
11251     // Remove all Store nodes.
11252     if (StoreNodes[i].MemNode == LatestOp)
11253       continue;
11254     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11255     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11256     deleteAndRecombine(St);
11257   }
11258
11259   return true;
11260 }
11261
11262 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11263   StoreSDNode *ST  = cast<StoreSDNode>(N);
11264   SDValue Chain = ST->getChain();
11265   SDValue Value = ST->getValue();
11266   SDValue Ptr   = ST->getBasePtr();
11267
11268   // If this is a store of a bit convert, store the input value if the
11269   // resultant store does not need a higher alignment than the original.
11270   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11271       ST->isUnindexed()) {
11272     unsigned OrigAlign = ST->getAlignment();
11273     EVT SVT = Value.getOperand(0).getValueType();
11274     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11275         SVT.getTypeForEVT(*DAG.getContext()));
11276     if (Align <= OrigAlign &&
11277         ((!LegalOperations && !ST->isVolatile()) ||
11278          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11279       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11280                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11281                           ST->isNonTemporal(), OrigAlign,
11282                           ST->getAAInfo());
11283   }
11284
11285   // Turn 'store undef, Ptr' -> nothing.
11286   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11287     return Chain;
11288
11289   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11290   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11291     // NOTE: If the original store is volatile, this transform must not increase
11292     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11293     // processor operation but an i64 (which is not legal) requires two.  So the
11294     // transform should not be done in this case.
11295     if (Value.getOpcode() != ISD::TargetConstantFP) {
11296       SDValue Tmp;
11297       switch (CFP->getSimpleValueType(0).SimpleTy) {
11298       default: llvm_unreachable("Unknown FP type");
11299       case MVT::f16:    // We don't do this for these yet.
11300       case MVT::f80:
11301       case MVT::f128:
11302       case MVT::ppcf128:
11303         break;
11304       case MVT::f32:
11305         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11306             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11307           ;
11308           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11309                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11310                               MVT::i32);
11311           return DAG.getStore(Chain, SDLoc(N), Tmp,
11312                               Ptr, ST->getMemOperand());
11313         }
11314         break;
11315       case MVT::f64:
11316         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11317              !ST->isVolatile()) ||
11318             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11319           ;
11320           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11321                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11322           return DAG.getStore(Chain, SDLoc(N), Tmp,
11323                               Ptr, ST->getMemOperand());
11324         }
11325
11326         if (!ST->isVolatile() &&
11327             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11328           // Many FP stores are not made apparent until after legalize, e.g. for
11329           // argument passing.  Since this is so common, custom legalize the
11330           // 64-bit integer store into two 32-bit stores.
11331           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11332           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11333           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11334           if (DAG.getDataLayout().isBigEndian())
11335             std::swap(Lo, Hi);
11336
11337           unsigned Alignment = ST->getAlignment();
11338           bool isVolatile = ST->isVolatile();
11339           bool isNonTemporal = ST->isNonTemporal();
11340           AAMDNodes AAInfo = ST->getAAInfo();
11341
11342           SDLoc DL(N);
11343
11344           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11345                                      Ptr, ST->getPointerInfo(),
11346                                      isVolatile, isNonTemporal,
11347                                      ST->getAlignment(), AAInfo);
11348           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11349                             DAG.getConstant(4, DL, Ptr.getValueType()));
11350           Alignment = MinAlign(Alignment, 4U);
11351           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11352                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11353                                      isVolatile, isNonTemporal,
11354                                      Alignment, AAInfo);
11355           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11356                              St0, St1);
11357         }
11358
11359         break;
11360       }
11361     }
11362   }
11363
11364   // Try to infer better alignment information than the store already has.
11365   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11366     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11367       if (Align > ST->getAlignment()) {
11368         SDValue NewStore =
11369                DAG.getTruncStore(Chain, SDLoc(N), Value,
11370                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11371                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11372                                  ST->getAAInfo());
11373         if (NewStore.getNode() != N)
11374           return CombineTo(ST, NewStore, true);
11375       }
11376     }
11377   }
11378
11379   // Try transforming a pair floating point load / store ops to integer
11380   // load / store ops.
11381   if (SDValue NewST = TransformFPLoadStorePair(N))
11382     return NewST;
11383
11384   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11385                                                   : DAG.getSubtarget().useAA();
11386 #ifndef NDEBUG
11387   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11388       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11389     UseAA = false;
11390 #endif
11391   if (UseAA && ST->isUnindexed()) {
11392     // Walk up chain skipping non-aliasing memory nodes.
11393     SDValue BetterChain = FindBetterChain(N, Chain);
11394
11395     // If there is a better chain.
11396     if (Chain != BetterChain) {
11397       SDValue ReplStore;
11398
11399       // Replace the chain to avoid dependency.
11400       if (ST->isTruncatingStore()) {
11401         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11402                                       ST->getMemoryVT(), ST->getMemOperand());
11403       } else {
11404         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11405                                  ST->getMemOperand());
11406       }
11407
11408       // Create token to keep both nodes around.
11409       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11410                                   MVT::Other, Chain, ReplStore);
11411
11412       // Make sure the new and old chains are cleaned up.
11413       AddToWorklist(Token.getNode());
11414
11415       // Don't add users to work list.
11416       return CombineTo(N, Token, false);
11417     }
11418   }
11419
11420   // Try transforming N to an indexed store.
11421   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11422     return SDValue(N, 0);
11423
11424   // FIXME: is there such a thing as a truncating indexed store?
11425   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11426       Value.getValueType().isInteger()) {
11427     // See if we can simplify the input to this truncstore with knowledge that
11428     // only the low bits are being used.  For example:
11429     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11430     SDValue Shorter =
11431       GetDemandedBits(Value,
11432                       APInt::getLowBitsSet(
11433                         Value.getValueType().getScalarType().getSizeInBits(),
11434                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11435     AddToWorklist(Value.getNode());
11436     if (Shorter.getNode())
11437       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11438                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11439
11440     // Otherwise, see if we can simplify the operation with
11441     // SimplifyDemandedBits, which only works if the value has a single use.
11442     if (SimplifyDemandedBits(Value,
11443                         APInt::getLowBitsSet(
11444                           Value.getValueType().getScalarType().getSizeInBits(),
11445                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11446       return SDValue(N, 0);
11447   }
11448
11449   // If this is a load followed by a store to the same location, then the store
11450   // is dead/noop.
11451   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11452     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11453         ST->isUnindexed() && !ST->isVolatile() &&
11454         // There can't be any side effects between the load and store, such as
11455         // a call or store.
11456         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11457       // The store is dead, remove it.
11458       return Chain;
11459     }
11460   }
11461
11462   // If this is a store followed by a store with the same value to the same
11463   // location, then the store is dead/noop.
11464   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11465     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11466         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11467         ST1->isUnindexed() && !ST1->isVolatile()) {
11468       // The store is dead, remove it.
11469       return Chain;
11470     }
11471   }
11472
11473   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11474   // truncating store.  We can do this even if this is already a truncstore.
11475   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11476       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11477       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11478                             ST->getMemoryVT())) {
11479     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11480                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11481   }
11482
11483   // Only perform this optimization before the types are legal, because we
11484   // don't want to perform this optimization on every DAGCombine invocation.
11485   if (!LegalTypes) {
11486     bool EverChanged = false;
11487
11488     do {
11489       // There can be multiple store sequences on the same chain.
11490       // Keep trying to merge store sequences until we are unable to do so
11491       // or until we merge the last store on the chain.
11492       bool Changed = MergeConsecutiveStores(ST);
11493       EverChanged |= Changed;
11494       if (!Changed) break;
11495     } while (ST->getOpcode() != ISD::DELETED_NODE);
11496
11497     if (EverChanged)
11498       return SDValue(N, 0);
11499   }
11500
11501   return ReduceLoadOpStoreWidth(N);
11502 }
11503
11504 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11505   SDValue InVec = N->getOperand(0);
11506   SDValue InVal = N->getOperand(1);
11507   SDValue EltNo = N->getOperand(2);
11508   SDLoc dl(N);
11509
11510   // If the inserted element is an UNDEF, just use the input vector.
11511   if (InVal.getOpcode() == ISD::UNDEF)
11512     return InVec;
11513
11514   EVT VT = InVec.getValueType();
11515
11516   // If we can't generate a legal BUILD_VECTOR, exit
11517   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11518     return SDValue();
11519
11520   // Check that we know which element is being inserted
11521   if (!isa<ConstantSDNode>(EltNo))
11522     return SDValue();
11523   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11524
11525   // Canonicalize insert_vector_elt dag nodes.
11526   // Example:
11527   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11528   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11529   //
11530   // Do this only if the child insert_vector node has one use; also
11531   // do this only if indices are both constants and Idx1 < Idx0.
11532   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11533       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11534     unsigned OtherElt =
11535       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11536     if (Elt < OtherElt) {
11537       // Swap nodes.
11538       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11539                                   InVec.getOperand(0), InVal, EltNo);
11540       AddToWorklist(NewOp.getNode());
11541       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11542                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11543     }
11544   }
11545
11546   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11547   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11548   // vector elements.
11549   SmallVector<SDValue, 8> Ops;
11550   // Do not combine these two vectors if the output vector will not replace
11551   // the input vector.
11552   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11553     Ops.append(InVec.getNode()->op_begin(),
11554                InVec.getNode()->op_end());
11555   } else if (InVec.getOpcode() == ISD::UNDEF) {
11556     unsigned NElts = VT.getVectorNumElements();
11557     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11558   } else {
11559     return SDValue();
11560   }
11561
11562   // Insert the element
11563   if (Elt < Ops.size()) {
11564     // All the operands of BUILD_VECTOR must have the same type;
11565     // we enforce that here.
11566     EVT OpVT = Ops[0].getValueType();
11567     if (InVal.getValueType() != OpVT)
11568       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11569                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11570                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11571     Ops[Elt] = InVal;
11572   }
11573
11574   // Return the new vector
11575   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11576 }
11577
11578 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11579     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11580   EVT ResultVT = EVE->getValueType(0);
11581   EVT VecEltVT = InVecVT.getVectorElementType();
11582   unsigned Align = OriginalLoad->getAlignment();
11583   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11584       VecEltVT.getTypeForEVT(*DAG.getContext()));
11585
11586   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11587     return SDValue();
11588
11589   Align = NewAlign;
11590
11591   SDValue NewPtr = OriginalLoad->getBasePtr();
11592   SDValue Offset;
11593   EVT PtrType = NewPtr.getValueType();
11594   MachinePointerInfo MPI;
11595   SDLoc DL(EVE);
11596   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11597     int Elt = ConstEltNo->getZExtValue();
11598     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11599     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11600     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11601   } else {
11602     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11603     Offset = DAG.getNode(
11604         ISD::MUL, DL, PtrType, Offset,
11605         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11606     MPI = OriginalLoad->getPointerInfo();
11607   }
11608   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11609
11610   // The replacement we need to do here is a little tricky: we need to
11611   // replace an extractelement of a load with a load.
11612   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11613   // Note that this replacement assumes that the extractvalue is the only
11614   // use of the load; that's okay because we don't want to perform this
11615   // transformation in other cases anyway.
11616   SDValue Load;
11617   SDValue Chain;
11618   if (ResultVT.bitsGT(VecEltVT)) {
11619     // If the result type of vextract is wider than the load, then issue an
11620     // extending load instead.
11621     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11622                                                   VecEltVT)
11623                                    ? ISD::ZEXTLOAD
11624                                    : ISD::EXTLOAD;
11625     Load = DAG.getExtLoad(
11626         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11627         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11628         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11629     Chain = Load.getValue(1);
11630   } else {
11631     Load = DAG.getLoad(
11632         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11633         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11634         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11635     Chain = Load.getValue(1);
11636     if (ResultVT.bitsLT(VecEltVT))
11637       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11638     else
11639       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11640   }
11641   WorklistRemover DeadNodes(*this);
11642   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11643   SDValue To[] = { Load, Chain };
11644   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11645   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11646   // worklist explicitly as well.
11647   AddToWorklist(Load.getNode());
11648   AddUsersToWorklist(Load.getNode()); // Add users too
11649   // Make sure to revisit this node to clean it up; it will usually be dead.
11650   AddToWorklist(EVE);
11651   ++OpsNarrowed;
11652   return SDValue(EVE, 0);
11653 }
11654
11655 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11656   // (vextract (scalar_to_vector val, 0) -> val
11657   SDValue InVec = N->getOperand(0);
11658   EVT VT = InVec.getValueType();
11659   EVT NVT = N->getValueType(0);
11660
11661   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11662     // Check if the result type doesn't match the inserted element type. A
11663     // SCALAR_TO_VECTOR may truncate the inserted element and the
11664     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11665     SDValue InOp = InVec.getOperand(0);
11666     if (InOp.getValueType() != NVT) {
11667       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11668       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11669     }
11670     return InOp;
11671   }
11672
11673   SDValue EltNo = N->getOperand(1);
11674   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11675
11676   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11677   // We only perform this optimization before the op legalization phase because
11678   // we may introduce new vector instructions which are not backed by TD
11679   // patterns. For example on AVX, extracting elements from a wide vector
11680   // without using extract_subvector. However, if we can find an underlying
11681   // scalar value, then we can always use that.
11682   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11683       && ConstEltNo) {
11684     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11685     int NumElem = VT.getVectorNumElements();
11686     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11687     // Find the new index to extract from.
11688     int OrigElt = SVOp->getMaskElt(Elt);
11689
11690     // Extracting an undef index is undef.
11691     if (OrigElt == -1)
11692       return DAG.getUNDEF(NVT);
11693
11694     // Select the right vector half to extract from.
11695     SDValue SVInVec;
11696     if (OrigElt < NumElem) {
11697       SVInVec = InVec->getOperand(0);
11698     } else {
11699       SVInVec = InVec->getOperand(1);
11700       OrigElt -= NumElem;
11701     }
11702
11703     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11704       SDValue InOp = SVInVec.getOperand(OrigElt);
11705       if (InOp.getValueType() != NVT) {
11706         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11707         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11708       }
11709
11710       return InOp;
11711     }
11712
11713     // FIXME: We should handle recursing on other vector shuffles and
11714     // scalar_to_vector here as well.
11715
11716     if (!LegalOperations) {
11717       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11718       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11719                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11720     }
11721   }
11722
11723   bool BCNumEltsChanged = false;
11724   EVT ExtVT = VT.getVectorElementType();
11725   EVT LVT = ExtVT;
11726
11727   // If the result of load has to be truncated, then it's not necessarily
11728   // profitable.
11729   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11730     return SDValue();
11731
11732   if (InVec.getOpcode() == ISD::BITCAST) {
11733     // Don't duplicate a load with other uses.
11734     if (!InVec.hasOneUse())
11735       return SDValue();
11736
11737     EVT BCVT = InVec.getOperand(0).getValueType();
11738     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11739       return SDValue();
11740     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11741       BCNumEltsChanged = true;
11742     InVec = InVec.getOperand(0);
11743     ExtVT = BCVT.getVectorElementType();
11744   }
11745
11746   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11747   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11748       ISD::isNormalLoad(InVec.getNode()) &&
11749       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11750     SDValue Index = N->getOperand(1);
11751     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11752       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11753                                                            OrigLoad);
11754   }
11755
11756   // Perform only after legalization to ensure build_vector / vector_shuffle
11757   // optimizations have already been done.
11758   if (!LegalOperations) return SDValue();
11759
11760   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11761   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11762   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11763
11764   if (ConstEltNo) {
11765     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11766
11767     LoadSDNode *LN0 = nullptr;
11768     const ShuffleVectorSDNode *SVN = nullptr;
11769     if (ISD::isNormalLoad(InVec.getNode())) {
11770       LN0 = cast<LoadSDNode>(InVec);
11771     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11772                InVec.getOperand(0).getValueType() == ExtVT &&
11773                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11774       // Don't duplicate a load with other uses.
11775       if (!InVec.hasOneUse())
11776         return SDValue();
11777
11778       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11779     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11780       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11781       // =>
11782       // (load $addr+1*size)
11783
11784       // Don't duplicate a load with other uses.
11785       if (!InVec.hasOneUse())
11786         return SDValue();
11787
11788       // If the bit convert changed the number of elements, it is unsafe
11789       // to examine the mask.
11790       if (BCNumEltsChanged)
11791         return SDValue();
11792
11793       // Select the input vector, guarding against out of range extract vector.
11794       unsigned NumElems = VT.getVectorNumElements();
11795       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11796       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11797
11798       if (InVec.getOpcode() == ISD::BITCAST) {
11799         // Don't duplicate a load with other uses.
11800         if (!InVec.hasOneUse())
11801           return SDValue();
11802
11803         InVec = InVec.getOperand(0);
11804       }
11805       if (ISD::isNormalLoad(InVec.getNode())) {
11806         LN0 = cast<LoadSDNode>(InVec);
11807         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11808         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11809       }
11810     }
11811
11812     // Make sure we found a non-volatile load and the extractelement is
11813     // the only use.
11814     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11815       return SDValue();
11816
11817     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11818     if (Elt == -1)
11819       return DAG.getUNDEF(LVT);
11820
11821     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11822   }
11823
11824   return SDValue();
11825 }
11826
11827 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11828 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11829   // We perform this optimization post type-legalization because
11830   // the type-legalizer often scalarizes integer-promoted vectors.
11831   // Performing this optimization before may create bit-casts which
11832   // will be type-legalized to complex code sequences.
11833   // We perform this optimization only before the operation legalizer because we
11834   // may introduce illegal operations.
11835   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11836     return SDValue();
11837
11838   unsigned NumInScalars = N->getNumOperands();
11839   SDLoc dl(N);
11840   EVT VT = N->getValueType(0);
11841
11842   // Check to see if this is a BUILD_VECTOR of a bunch of values
11843   // which come from any_extend or zero_extend nodes. If so, we can create
11844   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11845   // optimizations. We do not handle sign-extend because we can't fill the sign
11846   // using shuffles.
11847   EVT SourceType = MVT::Other;
11848   bool AllAnyExt = true;
11849
11850   for (unsigned i = 0; i != NumInScalars; ++i) {
11851     SDValue In = N->getOperand(i);
11852     // Ignore undef inputs.
11853     if (In.getOpcode() == ISD::UNDEF) continue;
11854
11855     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11856     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11857
11858     // Abort if the element is not an extension.
11859     if (!ZeroExt && !AnyExt) {
11860       SourceType = MVT::Other;
11861       break;
11862     }
11863
11864     // The input is a ZeroExt or AnyExt. Check the original type.
11865     EVT InTy = In.getOperand(0).getValueType();
11866
11867     // Check that all of the widened source types are the same.
11868     if (SourceType == MVT::Other)
11869       // First time.
11870       SourceType = InTy;
11871     else if (InTy != SourceType) {
11872       // Multiple income types. Abort.
11873       SourceType = MVT::Other;
11874       break;
11875     }
11876
11877     // Check if all of the extends are ANY_EXTENDs.
11878     AllAnyExt &= AnyExt;
11879   }
11880
11881   // In order to have valid types, all of the inputs must be extended from the
11882   // same source type and all of the inputs must be any or zero extend.
11883   // Scalar sizes must be a power of two.
11884   EVT OutScalarTy = VT.getScalarType();
11885   bool ValidTypes = SourceType != MVT::Other &&
11886                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11887                  isPowerOf2_32(SourceType.getSizeInBits());
11888
11889   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11890   // turn into a single shuffle instruction.
11891   if (!ValidTypes)
11892     return SDValue();
11893
11894   bool isLE = DAG.getDataLayout().isLittleEndian();
11895   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11896   assert(ElemRatio > 1 && "Invalid element size ratio");
11897   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11898                                DAG.getConstant(0, SDLoc(N), SourceType);
11899
11900   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11901   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11902
11903   // Populate the new build_vector
11904   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11905     SDValue Cast = N->getOperand(i);
11906     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11907             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11908             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11909     SDValue In;
11910     if (Cast.getOpcode() == ISD::UNDEF)
11911       In = DAG.getUNDEF(SourceType);
11912     else
11913       In = Cast->getOperand(0);
11914     unsigned Index = isLE ? (i * ElemRatio) :
11915                             (i * ElemRatio + (ElemRatio - 1));
11916
11917     assert(Index < Ops.size() && "Invalid index");
11918     Ops[Index] = In;
11919   }
11920
11921   // The type of the new BUILD_VECTOR node.
11922   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11923   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11924          "Invalid vector size");
11925   // Check if the new vector type is legal.
11926   if (!isTypeLegal(VecVT)) return SDValue();
11927
11928   // Make the new BUILD_VECTOR.
11929   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11930
11931   // The new BUILD_VECTOR node has the potential to be further optimized.
11932   AddToWorklist(BV.getNode());
11933   // Bitcast to the desired type.
11934   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11935 }
11936
11937 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11938   EVT VT = N->getValueType(0);
11939
11940   unsigned NumInScalars = N->getNumOperands();
11941   SDLoc dl(N);
11942
11943   EVT SrcVT = MVT::Other;
11944   unsigned Opcode = ISD::DELETED_NODE;
11945   unsigned NumDefs = 0;
11946
11947   for (unsigned i = 0; i != NumInScalars; ++i) {
11948     SDValue In = N->getOperand(i);
11949     unsigned Opc = In.getOpcode();
11950
11951     if (Opc == ISD::UNDEF)
11952       continue;
11953
11954     // If all scalar values are floats and converted from integers.
11955     if (Opcode == ISD::DELETED_NODE &&
11956         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11957       Opcode = Opc;
11958     }
11959
11960     if (Opc != Opcode)
11961       return SDValue();
11962
11963     EVT InVT = In.getOperand(0).getValueType();
11964
11965     // If all scalar values are typed differently, bail out. It's chosen to
11966     // simplify BUILD_VECTOR of integer types.
11967     if (SrcVT == MVT::Other)
11968       SrcVT = InVT;
11969     if (SrcVT != InVT)
11970       return SDValue();
11971     NumDefs++;
11972   }
11973
11974   // If the vector has just one element defined, it's not worth to fold it into
11975   // a vectorized one.
11976   if (NumDefs < 2)
11977     return SDValue();
11978
11979   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11980          && "Should only handle conversion from integer to float.");
11981   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11982
11983   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11984
11985   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11986     return SDValue();
11987
11988   // Just because the floating-point vector type is legal does not necessarily
11989   // mean that the corresponding integer vector type is.
11990   if (!isTypeLegal(NVT))
11991     return SDValue();
11992
11993   SmallVector<SDValue, 8> Opnds;
11994   for (unsigned i = 0; i != NumInScalars; ++i) {
11995     SDValue In = N->getOperand(i);
11996
11997     if (In.getOpcode() == ISD::UNDEF)
11998       Opnds.push_back(DAG.getUNDEF(SrcVT));
11999     else
12000       Opnds.push_back(In.getOperand(0));
12001   }
12002   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12003   AddToWorklist(BV.getNode());
12004
12005   return DAG.getNode(Opcode, dl, VT, BV);
12006 }
12007
12008 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12009   unsigned NumInScalars = N->getNumOperands();
12010   SDLoc dl(N);
12011   EVT VT = N->getValueType(0);
12012
12013   // A vector built entirely of undefs is undef.
12014   if (ISD::allOperandsUndef(N))
12015     return DAG.getUNDEF(VT);
12016
12017   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12018     return V;
12019
12020   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12021     return V;
12022
12023   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12024   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12025   // at most two distinct vectors, turn this into a shuffle node.
12026
12027   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12028   if (!isTypeLegal(VT))
12029     return SDValue();
12030
12031   // May only combine to shuffle after legalize if shuffle is legal.
12032   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12033     return SDValue();
12034
12035   SDValue VecIn1, VecIn2;
12036   bool UsesZeroVector = false;
12037   for (unsigned i = 0; i != NumInScalars; ++i) {
12038     SDValue Op = N->getOperand(i);
12039     // Ignore undef inputs.
12040     if (Op.getOpcode() == ISD::UNDEF) continue;
12041
12042     // See if we can combine this build_vector into a blend with a zero vector.
12043     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12044       UsesZeroVector = true;
12045       continue;
12046     }
12047
12048     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12049     // constant index, bail out.
12050     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12051         !isa<ConstantSDNode>(Op.getOperand(1))) {
12052       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12053       break;
12054     }
12055
12056     // We allow up to two distinct input vectors.
12057     SDValue ExtractedFromVec = Op.getOperand(0);
12058     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12059       continue;
12060
12061     if (!VecIn1.getNode()) {
12062       VecIn1 = ExtractedFromVec;
12063     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12064       VecIn2 = ExtractedFromVec;
12065     } else {
12066       // Too many inputs.
12067       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12068       break;
12069     }
12070   }
12071
12072   // If everything is good, we can make a shuffle operation.
12073   if (VecIn1.getNode()) {
12074     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12075     SmallVector<int, 8> Mask;
12076     for (unsigned i = 0; i != NumInScalars; ++i) {
12077       unsigned Opcode = N->getOperand(i).getOpcode();
12078       if (Opcode == ISD::UNDEF) {
12079         Mask.push_back(-1);
12080         continue;
12081       }
12082
12083       // Operands can also be zero.
12084       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12085         assert(UsesZeroVector &&
12086                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12087                "Unexpected node found!");
12088         Mask.push_back(NumInScalars+i);
12089         continue;
12090       }
12091
12092       // If extracting from the first vector, just use the index directly.
12093       SDValue Extract = N->getOperand(i);
12094       SDValue ExtVal = Extract.getOperand(1);
12095       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12096       if (Extract.getOperand(0) == VecIn1) {
12097         Mask.push_back(ExtIndex);
12098         continue;
12099       }
12100
12101       // Otherwise, use InIdx + InputVecSize
12102       Mask.push_back(InNumElements + ExtIndex);
12103     }
12104
12105     // Avoid introducing illegal shuffles with zero.
12106     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12107       return SDValue();
12108
12109     // We can't generate a shuffle node with mismatched input and output types.
12110     // Attempt to transform a single input vector to the correct type.
12111     if ((VT != VecIn1.getValueType())) {
12112       // If the input vector type has a different base type to the output
12113       // vector type, bail out.
12114       EVT VTElemType = VT.getVectorElementType();
12115       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12116           (VecIn2.getNode() &&
12117            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12118         return SDValue();
12119
12120       // If the input vector is too small, widen it.
12121       // We only support widening of vectors which are half the size of the
12122       // output registers. For example XMM->YMM widening on X86 with AVX.
12123       EVT VecInT = VecIn1.getValueType();
12124       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12125         // If we only have one small input, widen it by adding undef values.
12126         if (!VecIn2.getNode())
12127           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12128                                DAG.getUNDEF(VecIn1.getValueType()));
12129         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12130           // If we have two small inputs of the same type, try to concat them.
12131           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12132           VecIn2 = SDValue(nullptr, 0);
12133         } else
12134           return SDValue();
12135       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12136         // If the input vector is too large, try to split it.
12137         // We don't support having two input vectors that are too large.
12138         // If the zero vector was used, we can not split the vector,
12139         // since we'd need 3 inputs.
12140         if (UsesZeroVector || VecIn2.getNode())
12141           return SDValue();
12142
12143         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12144           return SDValue();
12145
12146         // Try to replace VecIn1 with two extract_subvectors
12147         // No need to update the masks, they should still be correct.
12148         VecIn2 = DAG.getNode(
12149             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12150             DAG.getConstant(VT.getVectorNumElements(), dl,
12151                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12152         VecIn1 = DAG.getNode(
12153             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12154             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12155       } else
12156         return SDValue();
12157     }
12158
12159     if (UsesZeroVector)
12160       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12161                                 DAG.getConstantFP(0.0, dl, VT);
12162     else
12163       // If VecIn2 is unused then change it to undef.
12164       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12165
12166     // Check that we were able to transform all incoming values to the same
12167     // type.
12168     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12169         VecIn1.getValueType() != VT)
12170           return SDValue();
12171
12172     // Return the new VECTOR_SHUFFLE node.
12173     SDValue Ops[2];
12174     Ops[0] = VecIn1;
12175     Ops[1] = VecIn2;
12176     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12177   }
12178
12179   return SDValue();
12180 }
12181
12182 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12183   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12184   EVT OpVT = N->getOperand(0).getValueType();
12185
12186   // If the operands are legal vectors, leave them alone.
12187   if (TLI.isTypeLegal(OpVT))
12188     return SDValue();
12189
12190   SDLoc DL(N);
12191   EVT VT = N->getValueType(0);
12192   SmallVector<SDValue, 8> Ops;
12193
12194   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12195   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12196
12197   // Keep track of what we encounter.
12198   bool AnyInteger = false;
12199   bool AnyFP = false;
12200   for (const SDValue &Op : N->ops()) {
12201     if (ISD::BITCAST == Op.getOpcode() &&
12202         !Op.getOperand(0).getValueType().isVector())
12203       Ops.push_back(Op.getOperand(0));
12204     else if (ISD::UNDEF == Op.getOpcode())
12205       Ops.push_back(ScalarUndef);
12206     else
12207       return SDValue();
12208
12209     // Note whether we encounter an integer or floating point scalar.
12210     // If it's neither, bail out, it could be something weird like x86mmx.
12211     EVT LastOpVT = Ops.back().getValueType();
12212     if (LastOpVT.isFloatingPoint())
12213       AnyFP = true;
12214     else if (LastOpVT.isInteger())
12215       AnyInteger = true;
12216     else
12217       return SDValue();
12218   }
12219
12220   // If any of the operands is a floating point scalar bitcast to a vector,
12221   // use floating point types throughout, and bitcast everything.
12222   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12223   if (AnyFP) {
12224     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12225     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12226     if (AnyInteger) {
12227       for (SDValue &Op : Ops) {
12228         if (Op.getValueType() == SVT)
12229           continue;
12230         if (Op.getOpcode() == ISD::UNDEF)
12231           Op = ScalarUndef;
12232         else
12233           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12234       }
12235     }
12236   }
12237
12238   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12239                                VT.getSizeInBits() / SVT.getSizeInBits());
12240   return DAG.getNode(ISD::BITCAST, DL, VT,
12241                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12242 }
12243
12244 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12245 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12246 // most two distinct vectors the same size as the result, attempt to turn this
12247 // into a legal shuffle.
12248 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12249   EVT VT = N->getValueType(0);
12250   EVT OpVT = N->getOperand(0).getValueType();
12251   int NumElts = VT.getVectorNumElements();
12252   int NumOpElts = OpVT.getVectorNumElements();
12253
12254   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12255   SmallVector<int, 8> Mask;
12256
12257   for (SDValue Op : N->ops()) {
12258     // Peek through any bitcast.
12259     while (Op.getOpcode() == ISD::BITCAST)
12260       Op = Op.getOperand(0);
12261
12262     // UNDEF nodes convert to UNDEF shuffle mask values.
12263     if (Op.getOpcode() == ISD::UNDEF) {
12264       Mask.append((unsigned)NumOpElts, -1);
12265       continue;
12266     }
12267
12268     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12269       return SDValue();
12270
12271     // What vector are we extracting the subvector from and at what index?
12272     SDValue ExtVec = Op.getOperand(0);
12273
12274     // We want the EVT of the original extraction to correctly scale the
12275     // extraction index.
12276     EVT ExtVT = ExtVec.getValueType();
12277
12278     // Peek through any bitcast.
12279     while (ExtVec.getOpcode() == ISD::BITCAST)
12280       ExtVec = ExtVec.getOperand(0);
12281
12282     // UNDEF nodes convert to UNDEF shuffle mask values.
12283     if (ExtVec.getOpcode() == ISD::UNDEF) {
12284       Mask.append((unsigned)NumOpElts, -1);
12285       continue;
12286     }
12287
12288     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12289       return SDValue();
12290     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12291
12292     // Ensure that we are extracting a subvector from a vector the same
12293     // size as the result.
12294     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12295       return SDValue();
12296
12297     // Scale the subvector index to account for any bitcast.
12298     int NumExtElts = ExtVT.getVectorNumElements();
12299     if (0 == (NumExtElts % NumElts))
12300       ExtIdx /= (NumExtElts / NumElts);
12301     else if (0 == (NumElts % NumExtElts))
12302       ExtIdx *= (NumElts / NumExtElts);
12303     else
12304       return SDValue();
12305
12306     // At most we can reference 2 inputs in the final shuffle.
12307     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12308       SV0 = ExtVec;
12309       for (int i = 0; i != NumOpElts; ++i)
12310         Mask.push_back(i + ExtIdx);
12311     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12312       SV1 = ExtVec;
12313       for (int i = 0; i != NumOpElts; ++i)
12314         Mask.push_back(i + ExtIdx + NumElts);
12315     } else {
12316       return SDValue();
12317     }
12318   }
12319
12320   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12321     return SDValue();
12322
12323   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12324                               DAG.getBitcast(VT, SV1), Mask);
12325 }
12326
12327 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12328   // If we only have one input vector, we don't need to do any concatenation.
12329   if (N->getNumOperands() == 1)
12330     return N->getOperand(0);
12331
12332   // Check if all of the operands are undefs.
12333   EVT VT = N->getValueType(0);
12334   if (ISD::allOperandsUndef(N))
12335     return DAG.getUNDEF(VT);
12336
12337   // Optimize concat_vectors where all but the first of the vectors are undef.
12338   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12339         return Op.getOpcode() == ISD::UNDEF;
12340       })) {
12341     SDValue In = N->getOperand(0);
12342     assert(In.getValueType().isVector() && "Must concat vectors");
12343
12344     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12345     if (In->getOpcode() == ISD::BITCAST &&
12346         !In->getOperand(0)->getValueType(0).isVector()) {
12347       SDValue Scalar = In->getOperand(0);
12348
12349       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12350       // look through the trunc so we can still do the transform:
12351       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12352       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12353           !TLI.isTypeLegal(Scalar.getValueType()) &&
12354           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12355         Scalar = Scalar->getOperand(0);
12356
12357       EVT SclTy = Scalar->getValueType(0);
12358
12359       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12360         return SDValue();
12361
12362       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12363                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12364       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12365         return SDValue();
12366
12367       SDLoc dl = SDLoc(N);
12368       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12369       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12370     }
12371   }
12372
12373   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12374   // We have already tested above for an UNDEF only concatenation.
12375   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12376   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12377   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12378     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12379   };
12380   bool AllBuildVectorsOrUndefs =
12381       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12382   if (AllBuildVectorsOrUndefs) {
12383     SmallVector<SDValue, 8> Opnds;
12384     EVT SVT = VT.getScalarType();
12385
12386     EVT MinVT = SVT;
12387     if (!SVT.isFloatingPoint()) {
12388       // If BUILD_VECTOR are from built from integer, they may have different
12389       // operand types. Get the smallest type and truncate all operands to it.
12390       bool FoundMinVT = false;
12391       for (const SDValue &Op : N->ops())
12392         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12393           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12394           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12395           FoundMinVT = true;
12396         }
12397       assert(FoundMinVT && "Concat vector type mismatch");
12398     }
12399
12400     for (const SDValue &Op : N->ops()) {
12401       EVT OpVT = Op.getValueType();
12402       unsigned NumElts = OpVT.getVectorNumElements();
12403
12404       if (ISD::UNDEF == Op.getOpcode())
12405         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12406
12407       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12408         if (SVT.isFloatingPoint()) {
12409           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12410           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12411         } else {
12412           for (unsigned i = 0; i != NumElts; ++i)
12413             Opnds.push_back(
12414                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12415         }
12416       }
12417     }
12418
12419     assert(VT.getVectorNumElements() == Opnds.size() &&
12420            "Concat vector type mismatch");
12421     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12422   }
12423
12424   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12425   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12426     return V;
12427
12428   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12429   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12430     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12431       return V;
12432
12433   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12434   // nodes often generate nop CONCAT_VECTOR nodes.
12435   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12436   // place the incoming vectors at the exact same location.
12437   SDValue SingleSource = SDValue();
12438   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12439
12440   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12441     SDValue Op = N->getOperand(i);
12442
12443     if (Op.getOpcode() == ISD::UNDEF)
12444       continue;
12445
12446     // Check if this is the identity extract:
12447     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12448       return SDValue();
12449
12450     // Find the single incoming vector for the extract_subvector.
12451     if (SingleSource.getNode()) {
12452       if (Op.getOperand(0) != SingleSource)
12453         return SDValue();
12454     } else {
12455       SingleSource = Op.getOperand(0);
12456
12457       // Check the source type is the same as the type of the result.
12458       // If not, this concat may extend the vector, so we can not
12459       // optimize it away.
12460       if (SingleSource.getValueType() != N->getValueType(0))
12461         return SDValue();
12462     }
12463
12464     unsigned IdentityIndex = i * PartNumElem;
12465     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12466     // The extract index must be constant.
12467     if (!CS)
12468       return SDValue();
12469
12470     // Check that we are reading from the identity index.
12471     if (CS->getZExtValue() != IdentityIndex)
12472       return SDValue();
12473   }
12474
12475   if (SingleSource.getNode())
12476     return SingleSource;
12477
12478   return SDValue();
12479 }
12480
12481 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12482   EVT NVT = N->getValueType(0);
12483   SDValue V = N->getOperand(0);
12484
12485   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12486     // Combine:
12487     //    (extract_subvec (concat V1, V2, ...), i)
12488     // Into:
12489     //    Vi if possible
12490     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12491     // type.
12492     if (V->getOperand(0).getValueType() != NVT)
12493       return SDValue();
12494     unsigned Idx = N->getConstantOperandVal(1);
12495     unsigned NumElems = NVT.getVectorNumElements();
12496     assert((Idx % NumElems) == 0 &&
12497            "IDX in concat is not a multiple of the result vector length.");
12498     return V->getOperand(Idx / NumElems);
12499   }
12500
12501   // Skip bitcasting
12502   if (V->getOpcode() == ISD::BITCAST)
12503     V = V.getOperand(0);
12504
12505   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12506     SDLoc dl(N);
12507     // Handle only simple case where vector being inserted and vector
12508     // being extracted are of same type, and are half size of larger vectors.
12509     EVT BigVT = V->getOperand(0).getValueType();
12510     EVT SmallVT = V->getOperand(1).getValueType();
12511     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12512       return SDValue();
12513
12514     // Only handle cases where both indexes are constants with the same type.
12515     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12516     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12517
12518     if (InsIdx && ExtIdx &&
12519         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12520         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12521       // Combine:
12522       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12523       // Into:
12524       //    indices are equal or bit offsets are equal => V1
12525       //    otherwise => (extract_subvec V1, ExtIdx)
12526       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12527           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12528         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12529       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12530                          DAG.getNode(ISD::BITCAST, dl,
12531                                      N->getOperand(0).getValueType(),
12532                                      V->getOperand(0)), N->getOperand(1));
12533     }
12534   }
12535
12536   return SDValue();
12537 }
12538
12539 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12540                                                  SDValue V, SelectionDAG &DAG) {
12541   SDLoc DL(V);
12542   EVT VT = V.getValueType();
12543
12544   switch (V.getOpcode()) {
12545   default:
12546     return V;
12547
12548   case ISD::CONCAT_VECTORS: {
12549     EVT OpVT = V->getOperand(0).getValueType();
12550     int OpSize = OpVT.getVectorNumElements();
12551     SmallBitVector OpUsedElements(OpSize, false);
12552     bool FoundSimplification = false;
12553     SmallVector<SDValue, 4> NewOps;
12554     NewOps.reserve(V->getNumOperands());
12555     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12556       SDValue Op = V->getOperand(i);
12557       bool OpUsed = false;
12558       for (int j = 0; j < OpSize; ++j)
12559         if (UsedElements[i * OpSize + j]) {
12560           OpUsedElements[j] = true;
12561           OpUsed = true;
12562         }
12563       NewOps.push_back(
12564           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12565                  : DAG.getUNDEF(OpVT));
12566       FoundSimplification |= Op == NewOps.back();
12567       OpUsedElements.reset();
12568     }
12569     if (FoundSimplification)
12570       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12571     return V;
12572   }
12573
12574   case ISD::INSERT_SUBVECTOR: {
12575     SDValue BaseV = V->getOperand(0);
12576     SDValue SubV = V->getOperand(1);
12577     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12578     if (!IdxN)
12579       return V;
12580
12581     int SubSize = SubV.getValueType().getVectorNumElements();
12582     int Idx = IdxN->getZExtValue();
12583     bool SubVectorUsed = false;
12584     SmallBitVector SubUsedElements(SubSize, false);
12585     for (int i = 0; i < SubSize; ++i)
12586       if (UsedElements[i + Idx]) {
12587         SubVectorUsed = true;
12588         SubUsedElements[i] = true;
12589         UsedElements[i + Idx] = false;
12590       }
12591
12592     // Now recurse on both the base and sub vectors.
12593     SDValue SimplifiedSubV =
12594         SubVectorUsed
12595             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12596             : DAG.getUNDEF(SubV.getValueType());
12597     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12598     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12599       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12600                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12601     return V;
12602   }
12603   }
12604 }
12605
12606 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12607                                        SDValue N1, SelectionDAG &DAG) {
12608   EVT VT = SVN->getValueType(0);
12609   int NumElts = VT.getVectorNumElements();
12610   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12611   for (int M : SVN->getMask())
12612     if (M >= 0 && M < NumElts)
12613       N0UsedElements[M] = true;
12614     else if (M >= NumElts)
12615       N1UsedElements[M - NumElts] = true;
12616
12617   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12618   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12619   if (S0 == N0 && S1 == N1)
12620     return SDValue();
12621
12622   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12623 }
12624
12625 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12626 // or turn a shuffle of a single concat into simpler shuffle then concat.
12627 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12628   EVT VT = N->getValueType(0);
12629   unsigned NumElts = VT.getVectorNumElements();
12630
12631   SDValue N0 = N->getOperand(0);
12632   SDValue N1 = N->getOperand(1);
12633   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12634
12635   SmallVector<SDValue, 4> Ops;
12636   EVT ConcatVT = N0.getOperand(0).getValueType();
12637   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12638   unsigned NumConcats = NumElts / NumElemsPerConcat;
12639
12640   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12641   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12642   // half vector elements.
12643   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12644       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12645                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12646     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12647                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12648     N1 = DAG.getUNDEF(ConcatVT);
12649     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12650   }
12651
12652   // Look at every vector that's inserted. We're looking for exact
12653   // subvector-sized copies from a concatenated vector
12654   for (unsigned I = 0; I != NumConcats; ++I) {
12655     // Make sure we're dealing with a copy.
12656     unsigned Begin = I * NumElemsPerConcat;
12657     bool AllUndef = true, NoUndef = true;
12658     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12659       if (SVN->getMaskElt(J) >= 0)
12660         AllUndef = false;
12661       else
12662         NoUndef = false;
12663     }
12664
12665     if (NoUndef) {
12666       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12667         return SDValue();
12668
12669       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12670         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12671           return SDValue();
12672
12673       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12674       if (FirstElt < N0.getNumOperands())
12675         Ops.push_back(N0.getOperand(FirstElt));
12676       else
12677         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12678
12679     } else if (AllUndef) {
12680       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12681     } else { // Mixed with general masks and undefs, can't do optimization.
12682       return SDValue();
12683     }
12684   }
12685
12686   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12687 }
12688
12689 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12690   EVT VT = N->getValueType(0);
12691   unsigned NumElts = VT.getVectorNumElements();
12692
12693   SDValue N0 = N->getOperand(0);
12694   SDValue N1 = N->getOperand(1);
12695
12696   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12697
12698   // Canonicalize shuffle undef, undef -> undef
12699   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12700     return DAG.getUNDEF(VT);
12701
12702   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12703
12704   // Canonicalize shuffle v, v -> v, undef
12705   if (N0 == N1) {
12706     SmallVector<int, 8> NewMask;
12707     for (unsigned i = 0; i != NumElts; ++i) {
12708       int Idx = SVN->getMaskElt(i);
12709       if (Idx >= (int)NumElts) Idx -= NumElts;
12710       NewMask.push_back(Idx);
12711     }
12712     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12713                                 &NewMask[0]);
12714   }
12715
12716   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12717   if (N0.getOpcode() == ISD::UNDEF) {
12718     SmallVector<int, 8> NewMask;
12719     for (unsigned i = 0; i != NumElts; ++i) {
12720       int Idx = SVN->getMaskElt(i);
12721       if (Idx >= 0) {
12722         if (Idx >= (int)NumElts)
12723           Idx -= NumElts;
12724         else
12725           Idx = -1; // remove reference to lhs
12726       }
12727       NewMask.push_back(Idx);
12728     }
12729     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12730                                 &NewMask[0]);
12731   }
12732
12733   // Remove references to rhs if it is undef
12734   if (N1.getOpcode() == ISD::UNDEF) {
12735     bool Changed = false;
12736     SmallVector<int, 8> NewMask;
12737     for (unsigned i = 0; i != NumElts; ++i) {
12738       int Idx = SVN->getMaskElt(i);
12739       if (Idx >= (int)NumElts) {
12740         Idx = -1;
12741         Changed = true;
12742       }
12743       NewMask.push_back(Idx);
12744     }
12745     if (Changed)
12746       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12747   }
12748
12749   // If it is a splat, check if the argument vector is another splat or a
12750   // build_vector.
12751   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12752     SDNode *V = N0.getNode();
12753
12754     // If this is a bit convert that changes the element type of the vector but
12755     // not the number of vector elements, look through it.  Be careful not to
12756     // look though conversions that change things like v4f32 to v2f64.
12757     if (V->getOpcode() == ISD::BITCAST) {
12758       SDValue ConvInput = V->getOperand(0);
12759       if (ConvInput.getValueType().isVector() &&
12760           ConvInput.getValueType().getVectorNumElements() == NumElts)
12761         V = ConvInput.getNode();
12762     }
12763
12764     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12765       assert(V->getNumOperands() == NumElts &&
12766              "BUILD_VECTOR has wrong number of operands");
12767       SDValue Base;
12768       bool AllSame = true;
12769       for (unsigned i = 0; i != NumElts; ++i) {
12770         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12771           Base = V->getOperand(i);
12772           break;
12773         }
12774       }
12775       // Splat of <u, u, u, u>, return <u, u, u, u>
12776       if (!Base.getNode())
12777         return N0;
12778       for (unsigned i = 0; i != NumElts; ++i) {
12779         if (V->getOperand(i) != Base) {
12780           AllSame = false;
12781           break;
12782         }
12783       }
12784       // Splat of <x, x, x, x>, return <x, x, x, x>
12785       if (AllSame)
12786         return N0;
12787
12788       // Canonicalize any other splat as a build_vector.
12789       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12790       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12791       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12792                                   V->getValueType(0), Ops);
12793
12794       // We may have jumped through bitcasts, so the type of the
12795       // BUILD_VECTOR may not match the type of the shuffle.
12796       if (V->getValueType(0) != VT)
12797         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12798       return NewBV;
12799     }
12800   }
12801
12802   // There are various patterns used to build up a vector from smaller vectors,
12803   // subvectors, or elements. Scan chains of these and replace unused insertions
12804   // or components with undef.
12805   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12806     return S;
12807
12808   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12809       Level < AfterLegalizeVectorOps &&
12810       (N1.getOpcode() == ISD::UNDEF ||
12811       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12812        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12813     SDValue V = partitionShuffleOfConcats(N, DAG);
12814
12815     if (V.getNode())
12816       return V;
12817   }
12818
12819   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12820   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12821   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12822     SmallVector<SDValue, 8> Ops;
12823     for (int M : SVN->getMask()) {
12824       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12825       if (M >= 0) {
12826         int Idx = M % NumElts;
12827         SDValue &S = (M < (int)NumElts ? N0 : N1);
12828         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12829           Op = S.getOperand(Idx);
12830         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12831           if (Idx == 0)
12832             Op = S.getOperand(0);
12833         } else {
12834           // Operand can't be combined - bail out.
12835           break;
12836         }
12837       }
12838       Ops.push_back(Op);
12839     }
12840     if (Ops.size() == VT.getVectorNumElements()) {
12841       // BUILD_VECTOR requires all inputs to be of the same type, find the
12842       // maximum type and extend them all.
12843       EVT SVT = VT.getScalarType();
12844       if (SVT.isInteger())
12845         for (SDValue &Op : Ops)
12846           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12847       if (SVT != VT.getScalarType())
12848         for (SDValue &Op : Ops)
12849           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12850                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12851                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12852       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12853     }
12854   }
12855
12856   // If this shuffle only has a single input that is a bitcasted shuffle,
12857   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12858   // back to their original types.
12859   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12860       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12861       TLI.isTypeLegal(VT)) {
12862
12863     // Peek through the bitcast only if there is one user.
12864     SDValue BC0 = N0;
12865     while (BC0.getOpcode() == ISD::BITCAST) {
12866       if (!BC0.hasOneUse())
12867         break;
12868       BC0 = BC0.getOperand(0);
12869     }
12870
12871     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12872       if (Scale == 1)
12873         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12874
12875       SmallVector<int, 8> NewMask;
12876       for (int M : Mask)
12877         for (int s = 0; s != Scale; ++s)
12878           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12879       return NewMask;
12880     };
12881
12882     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12883       EVT SVT = VT.getScalarType();
12884       EVT InnerVT = BC0->getValueType(0);
12885       EVT InnerSVT = InnerVT.getScalarType();
12886
12887       // Determine which shuffle works with the smaller scalar type.
12888       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12889       EVT ScaleSVT = ScaleVT.getScalarType();
12890
12891       if (TLI.isTypeLegal(ScaleVT) &&
12892           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12893           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12894
12895         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12896         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12897
12898         // Scale the shuffle masks to the smaller scalar type.
12899         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12900         SmallVector<int, 8> InnerMask =
12901             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12902         SmallVector<int, 8> OuterMask =
12903             ScaleShuffleMask(SVN->getMask(), OuterScale);
12904
12905         // Merge the shuffle masks.
12906         SmallVector<int, 8> NewMask;
12907         for (int M : OuterMask)
12908           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12909
12910         // Test for shuffle mask legality over both commutations.
12911         SDValue SV0 = BC0->getOperand(0);
12912         SDValue SV1 = BC0->getOperand(1);
12913         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12914         if (!LegalMask) {
12915           std::swap(SV0, SV1);
12916           ShuffleVectorSDNode::commuteMask(NewMask);
12917           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12918         }
12919
12920         if (LegalMask) {
12921           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12922           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12923           return DAG.getNode(
12924               ISD::BITCAST, SDLoc(N), VT,
12925               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12926         }
12927       }
12928     }
12929   }
12930
12931   // Canonicalize shuffles according to rules:
12932   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12933   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12934   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12935   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12936       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12937       TLI.isTypeLegal(VT)) {
12938     // The incoming shuffle must be of the same type as the result of the
12939     // current shuffle.
12940     assert(N1->getOperand(0).getValueType() == VT &&
12941            "Shuffle types don't match");
12942
12943     SDValue SV0 = N1->getOperand(0);
12944     SDValue SV1 = N1->getOperand(1);
12945     bool HasSameOp0 = N0 == SV0;
12946     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12947     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12948       // Commute the operands of this shuffle so that next rule
12949       // will trigger.
12950       return DAG.getCommutedVectorShuffle(*SVN);
12951   }
12952
12953   // Try to fold according to rules:
12954   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12955   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12956   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12957   // Don't try to fold shuffles with illegal type.
12958   // Only fold if this shuffle is the only user of the other shuffle.
12959   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12960       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12961     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12962
12963     // The incoming shuffle must be of the same type as the result of the
12964     // current shuffle.
12965     assert(OtherSV->getOperand(0).getValueType() == VT &&
12966            "Shuffle types don't match");
12967
12968     SDValue SV0, SV1;
12969     SmallVector<int, 4> Mask;
12970     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12971     // operand, and SV1 as the second operand.
12972     for (unsigned i = 0; i != NumElts; ++i) {
12973       int Idx = SVN->getMaskElt(i);
12974       if (Idx < 0) {
12975         // Propagate Undef.
12976         Mask.push_back(Idx);
12977         continue;
12978       }
12979
12980       SDValue CurrentVec;
12981       if (Idx < (int)NumElts) {
12982         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12983         // shuffle mask to identify which vector is actually referenced.
12984         Idx = OtherSV->getMaskElt(Idx);
12985         if (Idx < 0) {
12986           // Propagate Undef.
12987           Mask.push_back(Idx);
12988           continue;
12989         }
12990
12991         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12992                                            : OtherSV->getOperand(1);
12993       } else {
12994         // This shuffle index references an element within N1.
12995         CurrentVec = N1;
12996       }
12997
12998       // Simple case where 'CurrentVec' is UNDEF.
12999       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13000         Mask.push_back(-1);
13001         continue;
13002       }
13003
13004       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13005       // will be the first or second operand of the combined shuffle.
13006       Idx = Idx % NumElts;
13007       if (!SV0.getNode() || SV0 == CurrentVec) {
13008         // Ok. CurrentVec is the left hand side.
13009         // Update the mask accordingly.
13010         SV0 = CurrentVec;
13011         Mask.push_back(Idx);
13012         continue;
13013       }
13014
13015       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13016       if (SV1.getNode() && SV1 != CurrentVec)
13017         return SDValue();
13018
13019       // Ok. CurrentVec is the right hand side.
13020       // Update the mask accordingly.
13021       SV1 = CurrentVec;
13022       Mask.push_back(Idx + NumElts);
13023     }
13024
13025     // Check if all indices in Mask are Undef. In case, propagate Undef.
13026     bool isUndefMask = true;
13027     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13028       isUndefMask &= Mask[i] < 0;
13029
13030     if (isUndefMask)
13031       return DAG.getUNDEF(VT);
13032
13033     if (!SV0.getNode())
13034       SV0 = DAG.getUNDEF(VT);
13035     if (!SV1.getNode())
13036       SV1 = DAG.getUNDEF(VT);
13037
13038     // Avoid introducing shuffles with illegal mask.
13039     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13040       ShuffleVectorSDNode::commuteMask(Mask);
13041
13042       if (!TLI.isShuffleMaskLegal(Mask, VT))
13043         return SDValue();
13044
13045       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13046       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13047       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13048       std::swap(SV0, SV1);
13049     }
13050
13051     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13052     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13053     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13054     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13055   }
13056
13057   return SDValue();
13058 }
13059
13060 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13061   SDValue InVal = N->getOperand(0);
13062   EVT VT = N->getValueType(0);
13063
13064   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13065   // with a VECTOR_SHUFFLE.
13066   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13067     SDValue InVec = InVal->getOperand(0);
13068     SDValue EltNo = InVal->getOperand(1);
13069
13070     // FIXME: We could support implicit truncation if the shuffle can be
13071     // scaled to a smaller vector scalar type.
13072     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13073     if (C0 && VT == InVec.getValueType() &&
13074         VT.getScalarType() == InVal.getValueType()) {
13075       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13076       int Elt = C0->getZExtValue();
13077       NewMask[0] = Elt;
13078
13079       if (TLI.isShuffleMaskLegal(NewMask, VT))
13080         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13081                                     NewMask);
13082     }
13083   }
13084
13085   return SDValue();
13086 }
13087
13088 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13089   SDValue N0 = N->getOperand(0);
13090   SDValue N2 = N->getOperand(2);
13091
13092   // If the input vector is a concatenation, and the insert replaces
13093   // one of the halves, we can optimize into a single concat_vectors.
13094   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13095       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13096     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13097     EVT VT = N->getValueType(0);
13098
13099     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13100     // (concat_vectors Z, Y)
13101     if (InsIdx == 0)
13102       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13103                          N->getOperand(1), N0.getOperand(1));
13104
13105     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13106     // (concat_vectors X, Z)
13107     if (InsIdx == VT.getVectorNumElements()/2)
13108       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13109                          N0.getOperand(0), N->getOperand(1));
13110   }
13111
13112   return SDValue();
13113 }
13114
13115 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13116   SDValue N0 = N->getOperand(0);
13117
13118   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13119   if (N0->getOpcode() == ISD::FP16_TO_FP)
13120     return N0->getOperand(0);
13121
13122   return SDValue();
13123 }
13124
13125 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13126   SDValue N0 = N->getOperand(0);
13127
13128   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13129   if (N0->getOpcode() == ISD::AND) {
13130     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13131     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13132       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13133                          N0.getOperand(0));
13134     }
13135   }
13136
13137   return SDValue();
13138 }
13139
13140 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13141 /// with the destination vector and a zero vector.
13142 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13143 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13144 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13145   EVT VT = N->getValueType(0);
13146   SDValue LHS = N->getOperand(0);
13147   SDValue RHS = N->getOperand(1);
13148   SDLoc dl(N);
13149
13150   // Make sure we're not running after operation legalization where it
13151   // may have custom lowered the vector shuffles.
13152   if (LegalOperations)
13153     return SDValue();
13154
13155   if (N->getOpcode() != ISD::AND)
13156     return SDValue();
13157
13158   if (RHS.getOpcode() == ISD::BITCAST)
13159     RHS = RHS.getOperand(0);
13160
13161   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13162     return SDValue();
13163
13164   EVT RVT = RHS.getValueType();
13165   unsigned NumElts = RHS.getNumOperands();
13166
13167   // Attempt to create a valid clear mask, splitting the mask into
13168   // sub elements and checking to see if each is
13169   // all zeros or all ones - suitable for shuffle masking.
13170   auto BuildClearMask = [&](int Split) {
13171     int NumSubElts = NumElts * Split;
13172     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13173
13174     SmallVector<int, 8> Indices;
13175     for (int i = 0; i != NumSubElts; ++i) {
13176       int EltIdx = i / Split;
13177       int SubIdx = i % Split;
13178       SDValue Elt = RHS.getOperand(EltIdx);
13179       if (Elt.getOpcode() == ISD::UNDEF) {
13180         Indices.push_back(-1);
13181         continue;
13182       }
13183
13184       APInt Bits;
13185       if (isa<ConstantSDNode>(Elt))
13186         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13187       else if (isa<ConstantFPSDNode>(Elt))
13188         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13189       else
13190         return SDValue();
13191
13192       // Extract the sub element from the constant bit mask.
13193       if (DAG.getDataLayout().isBigEndian()) {
13194         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13195       } else {
13196         Bits = Bits.lshr(SubIdx * NumSubBits);
13197       }
13198
13199       if (Split > 1)
13200         Bits = Bits.trunc(NumSubBits);
13201
13202       if (Bits.isAllOnesValue())
13203         Indices.push_back(i);
13204       else if (Bits == 0)
13205         Indices.push_back(i + NumSubElts);
13206       else
13207         return SDValue();
13208     }
13209
13210     // Let's see if the target supports this vector_shuffle.
13211     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13212     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13213     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13214       return SDValue();
13215
13216     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13217     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13218                                                    DAG.getBitcast(ClearVT, LHS),
13219                                                    Zero, &Indices[0]));
13220   };
13221
13222   // Determine maximum split level (byte level masking).
13223   int MaxSplit = 1;
13224   if (RVT.getScalarSizeInBits() % 8 == 0)
13225     MaxSplit = RVT.getScalarSizeInBits() / 8;
13226
13227   for (int Split = 1; Split <= MaxSplit; ++Split)
13228     if (RVT.getScalarSizeInBits() % Split == 0)
13229       if (SDValue S = BuildClearMask(Split))
13230         return S;
13231
13232   return SDValue();
13233 }
13234
13235 /// Visit a binary vector operation, like ADD.
13236 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13237   assert(N->getValueType(0).isVector() &&
13238          "SimplifyVBinOp only works on vectors!");
13239
13240   SDValue LHS = N->getOperand(0);
13241   SDValue RHS = N->getOperand(1);
13242
13243   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13244   // this operation.
13245   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13246       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13247     // Check if both vectors are constants. If not bail out.
13248     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13249           cast<BuildVectorSDNode>(RHS)->isConstant()))
13250       return SDValue();
13251
13252     SmallVector<SDValue, 8> Ops;
13253     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13254       SDValue LHSOp = LHS.getOperand(i);
13255       SDValue RHSOp = RHS.getOperand(i);
13256
13257       // Can't fold divide by zero.
13258       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13259           N->getOpcode() == ISD::FDIV) {
13260         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13261              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13262           break;
13263       }
13264
13265       EVT VT = LHSOp.getValueType();
13266       EVT RVT = RHSOp.getValueType();
13267       if (RVT != VT) {
13268         // Integer BUILD_VECTOR operands may have types larger than the element
13269         // size (e.g., when the element type is not legal).  Prior to type
13270         // legalization, the types may not match between the two BUILD_VECTORS.
13271         // Truncate one of the operands to make them match.
13272         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13273           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13274         } else {
13275           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13276           VT = RVT;
13277         }
13278       }
13279       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13280                                    LHSOp, RHSOp);
13281       if (FoldOp.getOpcode() != ISD::UNDEF &&
13282           FoldOp.getOpcode() != ISD::Constant &&
13283           FoldOp.getOpcode() != ISD::ConstantFP)
13284         break;
13285       Ops.push_back(FoldOp);
13286       AddToWorklist(FoldOp.getNode());
13287     }
13288
13289     if (Ops.size() == LHS.getNumOperands())
13290       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13291   }
13292
13293   // Try to convert a constant mask AND into a shuffle clear mask.
13294   if (SDValue Shuffle = XformToShuffleWithZero(N))
13295     return Shuffle;
13296
13297   // Type legalization might introduce new shuffles in the DAG.
13298   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13299   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13300   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13301       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13302       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13303       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13304     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13305     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13306
13307     if (SVN0->getMask().equals(SVN1->getMask())) {
13308       EVT VT = N->getValueType(0);
13309       SDValue UndefVector = LHS.getOperand(1);
13310       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13311                                      LHS.getOperand(0), RHS.getOperand(0));
13312       AddUsersToWorklist(N);
13313       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13314                                   &SVN0->getMask()[0]);
13315     }
13316   }
13317
13318   return SDValue();
13319 }
13320
13321 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13322                                     SDValue N1, SDValue N2){
13323   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13324
13325   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13326                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13327
13328   // If we got a simplified select_cc node back from SimplifySelectCC, then
13329   // break it down into a new SETCC node, and a new SELECT node, and then return
13330   // the SELECT node, since we were called with a SELECT node.
13331   if (SCC.getNode()) {
13332     // Check to see if we got a select_cc back (to turn into setcc/select).
13333     // Otherwise, just return whatever node we got back, like fabs.
13334     if (SCC.getOpcode() == ISD::SELECT_CC) {
13335       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13336                                   N0.getValueType(),
13337                                   SCC.getOperand(0), SCC.getOperand(1),
13338                                   SCC.getOperand(4));
13339       AddToWorklist(SETCC.getNode());
13340       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13341                            SCC.getOperand(2), SCC.getOperand(3));
13342     }
13343
13344     return SCC;
13345   }
13346   return SDValue();
13347 }
13348
13349 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13350 /// being selected between, see if we can simplify the select.  Callers of this
13351 /// should assume that TheSelect is deleted if this returns true.  As such, they
13352 /// should return the appropriate thing (e.g. the node) back to the top-level of
13353 /// the DAG combiner loop to avoid it being looked at.
13354 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13355                                     SDValue RHS) {
13356
13357   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13358   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13359   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13360     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13361       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13362       SDValue Sqrt = RHS;
13363       ISD::CondCode CC;
13364       SDValue CmpLHS;
13365       const ConstantFPSDNode *NegZero = nullptr;
13366
13367       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13368         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13369         CmpLHS = TheSelect->getOperand(0);
13370         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13371       } else {
13372         // SELECT or VSELECT
13373         SDValue Cmp = TheSelect->getOperand(0);
13374         if (Cmp.getOpcode() == ISD::SETCC) {
13375           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13376           CmpLHS = Cmp.getOperand(0);
13377           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13378         }
13379       }
13380       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13381           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13382           CC == ISD::SETULT || CC == ISD::SETLT)) {
13383         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13384         CombineTo(TheSelect, Sqrt);
13385         return true;
13386       }
13387     }
13388   }
13389   // Cannot simplify select with vector condition
13390   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13391
13392   // If this is a select from two identical things, try to pull the operation
13393   // through the select.
13394   if (LHS.getOpcode() != RHS.getOpcode() ||
13395       !LHS.hasOneUse() || !RHS.hasOneUse())
13396     return false;
13397
13398   // If this is a load and the token chain is identical, replace the select
13399   // of two loads with a load through a select of the address to load from.
13400   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13401   // constants have been dropped into the constant pool.
13402   if (LHS.getOpcode() == ISD::LOAD) {
13403     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13404     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13405
13406     // Token chains must be identical.
13407     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13408         // Do not let this transformation reduce the number of volatile loads.
13409         LLD->isVolatile() || RLD->isVolatile() ||
13410         // FIXME: If either is a pre/post inc/dec load,
13411         // we'd need to split out the address adjustment.
13412         LLD->isIndexed() || RLD->isIndexed() ||
13413         // If this is an EXTLOAD, the VT's must match.
13414         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13415         // If this is an EXTLOAD, the kind of extension must match.
13416         (LLD->getExtensionType() != RLD->getExtensionType() &&
13417          // The only exception is if one of the extensions is anyext.
13418          LLD->getExtensionType() != ISD::EXTLOAD &&
13419          RLD->getExtensionType() != ISD::EXTLOAD) ||
13420         // FIXME: this discards src value information.  This is
13421         // over-conservative. It would be beneficial to be able to remember
13422         // both potential memory locations.  Since we are discarding
13423         // src value info, don't do the transformation if the memory
13424         // locations are not in the default address space.
13425         LLD->getPointerInfo().getAddrSpace() != 0 ||
13426         RLD->getPointerInfo().getAddrSpace() != 0 ||
13427         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13428                                       LLD->getBasePtr().getValueType()))
13429       return false;
13430
13431     // Check that the select condition doesn't reach either load.  If so,
13432     // folding this will induce a cycle into the DAG.  If not, this is safe to
13433     // xform, so create a select of the addresses.
13434     SDValue Addr;
13435     if (TheSelect->getOpcode() == ISD::SELECT) {
13436       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13437       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13438           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13439         return false;
13440       // The loads must not depend on one another.
13441       if (LLD->isPredecessorOf(RLD) ||
13442           RLD->isPredecessorOf(LLD))
13443         return false;
13444       Addr = DAG.getSelect(SDLoc(TheSelect),
13445                            LLD->getBasePtr().getValueType(),
13446                            TheSelect->getOperand(0), LLD->getBasePtr(),
13447                            RLD->getBasePtr());
13448     } else {  // Otherwise SELECT_CC
13449       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13450       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13451
13452       if ((LLD->hasAnyUseOfValue(1) &&
13453            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13454           (RLD->hasAnyUseOfValue(1) &&
13455            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13456         return false;
13457
13458       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13459                          LLD->getBasePtr().getValueType(),
13460                          TheSelect->getOperand(0),
13461                          TheSelect->getOperand(1),
13462                          LLD->getBasePtr(), RLD->getBasePtr(),
13463                          TheSelect->getOperand(4));
13464     }
13465
13466     SDValue Load;
13467     // It is safe to replace the two loads if they have different alignments,
13468     // but the new load must be the minimum (most restrictive) alignment of the
13469     // inputs.
13470     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13471     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13472     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13473       Load = DAG.getLoad(TheSelect->getValueType(0),
13474                          SDLoc(TheSelect),
13475                          // FIXME: Discards pointer and AA info.
13476                          LLD->getChain(), Addr, MachinePointerInfo(),
13477                          LLD->isVolatile(), LLD->isNonTemporal(),
13478                          isInvariant, Alignment);
13479     } else {
13480       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13481                             RLD->getExtensionType() : LLD->getExtensionType(),
13482                             SDLoc(TheSelect),
13483                             TheSelect->getValueType(0),
13484                             // FIXME: Discards pointer and AA info.
13485                             LLD->getChain(), Addr, MachinePointerInfo(),
13486                             LLD->getMemoryVT(), LLD->isVolatile(),
13487                             LLD->isNonTemporal(), isInvariant, Alignment);
13488     }
13489
13490     // Users of the select now use the result of the load.
13491     CombineTo(TheSelect, Load);
13492
13493     // Users of the old loads now use the new load's chain.  We know the
13494     // old-load value is dead now.
13495     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13496     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13497     return true;
13498   }
13499
13500   return false;
13501 }
13502
13503 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13504 /// where 'cond' is the comparison specified by CC.
13505 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13506                                       SDValue N2, SDValue N3,
13507                                       ISD::CondCode CC, bool NotExtCompare) {
13508   // (x ? y : y) -> y.
13509   if (N2 == N3) return N2;
13510
13511   EVT VT = N2.getValueType();
13512   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13513   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13514
13515   // Determine if the condition we're dealing with is constant
13516   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13517                               N0, N1, CC, DL, false);
13518   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13519
13520   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13521     // fold select_cc true, x, y -> x
13522     // fold select_cc false, x, y -> y
13523     return !SCCC->isNullValue() ? N2 : N3;
13524   }
13525
13526   // Check to see if we can simplify the select into an fabs node
13527   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13528     // Allow either -0.0 or 0.0
13529     if (CFP->isZero()) {
13530       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13531       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13532           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13533           N2 == N3.getOperand(0))
13534         return DAG.getNode(ISD::FABS, DL, VT, N0);
13535
13536       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13537       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13538           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13539           N2.getOperand(0) == N3)
13540         return DAG.getNode(ISD::FABS, DL, VT, N3);
13541     }
13542   }
13543
13544   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13545   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13546   // in it.  This is a win when the constant is not otherwise available because
13547   // it replaces two constant pool loads with one.  We only do this if the FP
13548   // type is known to be legal, because if it isn't, then we are before legalize
13549   // types an we want the other legalization to happen first (e.g. to avoid
13550   // messing with soft float) and if the ConstantFP is not legal, because if
13551   // it is legal, we may not need to store the FP constant in a constant pool.
13552   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13553     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13554       if (TLI.isTypeLegal(N2.getValueType()) &&
13555           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13556                TargetLowering::Legal &&
13557            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13558            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13559           // If both constants have multiple uses, then we won't need to do an
13560           // extra load, they are likely around in registers for other users.
13561           (TV->hasOneUse() || FV->hasOneUse())) {
13562         Constant *Elts[] = {
13563           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13564           const_cast<ConstantFP*>(TV->getConstantFPValue())
13565         };
13566         Type *FPTy = Elts[0]->getType();
13567         const DataLayout &TD = DAG.getDataLayout();
13568
13569         // Create a ConstantArray of the two constants.
13570         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13571         SDValue CPIdx =
13572             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13573                                 TD.getPrefTypeAlignment(FPTy));
13574         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13575
13576         // Get the offsets to the 0 and 1 element of the array so that we can
13577         // select between them.
13578         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13579         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13580         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13581
13582         SDValue Cond = DAG.getSetCC(DL,
13583                                     getSetCCResultType(N0.getValueType()),
13584                                     N0, N1, CC);
13585         AddToWorklist(Cond.getNode());
13586         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13587                                           Cond, One, Zero);
13588         AddToWorklist(CstOffset.getNode());
13589         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13590                             CstOffset);
13591         AddToWorklist(CPIdx.getNode());
13592         return DAG.getLoad(
13593             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13594             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13595             false, false, false, Alignment);
13596       }
13597     }
13598
13599   // Check to see if we can perform the "gzip trick", transforming
13600   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13601   if (isNullConstant(N3) && CC == ISD::SETLT &&
13602       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13603        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13604     EVT XType = N0.getValueType();
13605     EVT AType = N2.getValueType();
13606     if (XType.bitsGE(AType)) {
13607       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13608       // single-bit constant.
13609       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13610         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13611         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13612         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13613                                        getShiftAmountTy(N0.getValueType()));
13614         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13615                                     XType, N0, ShCt);
13616         AddToWorklist(Shift.getNode());
13617
13618         if (XType.bitsGT(AType)) {
13619           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13620           AddToWorklist(Shift.getNode());
13621         }
13622
13623         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13624       }
13625
13626       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13627                                   XType, N0,
13628                                   DAG.getConstant(XType.getSizeInBits() - 1,
13629                                                   SDLoc(N0),
13630                                          getShiftAmountTy(N0.getValueType())));
13631       AddToWorklist(Shift.getNode());
13632
13633       if (XType.bitsGT(AType)) {
13634         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13635         AddToWorklist(Shift.getNode());
13636       }
13637
13638       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13639     }
13640   }
13641
13642   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13643   // where y is has a single bit set.
13644   // A plaintext description would be, we can turn the SELECT_CC into an AND
13645   // when the condition can be materialized as an all-ones register.  Any
13646   // single bit-test can be materialized as an all-ones register with
13647   // shift-left and shift-right-arith.
13648   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13649       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13650     SDValue AndLHS = N0->getOperand(0);
13651     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13652     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13653       // Shift the tested bit over the sign bit.
13654       APInt AndMask = ConstAndRHS->getAPIntValue();
13655       SDValue ShlAmt =
13656         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13657                         getShiftAmountTy(AndLHS.getValueType()));
13658       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13659
13660       // Now arithmetic right shift it all the way over, so the result is either
13661       // all-ones, or zero.
13662       SDValue ShrAmt =
13663         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13664                         getShiftAmountTy(Shl.getValueType()));
13665       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13666
13667       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13668     }
13669   }
13670
13671   // fold select C, 16, 0 -> shl C, 4
13672   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13673       TLI.getBooleanContents(N0.getValueType()) ==
13674           TargetLowering::ZeroOrOneBooleanContent) {
13675
13676     // If the caller doesn't want us to simplify this into a zext of a compare,
13677     // don't do it.
13678     if (NotExtCompare && N2C->isOne())
13679       return SDValue();
13680
13681     // Get a SetCC of the condition
13682     // NOTE: Don't create a SETCC if it's not legal on this target.
13683     if (!LegalOperations ||
13684         TLI.isOperationLegal(ISD::SETCC,
13685           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13686       SDValue Temp, SCC;
13687       // cast from setcc result type to select result type
13688       if (LegalTypes) {
13689         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13690                             N0, N1, CC);
13691         if (N2.getValueType().bitsLT(SCC.getValueType()))
13692           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13693                                         N2.getValueType());
13694         else
13695           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13696                              N2.getValueType(), SCC);
13697       } else {
13698         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13699         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13700                            N2.getValueType(), SCC);
13701       }
13702
13703       AddToWorklist(SCC.getNode());
13704       AddToWorklist(Temp.getNode());
13705
13706       if (N2C->isOne())
13707         return Temp;
13708
13709       // shl setcc result by log2 n2c
13710       return DAG.getNode(
13711           ISD::SHL, DL, N2.getValueType(), Temp,
13712           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13713                           getShiftAmountTy(Temp.getValueType())));
13714     }
13715   }
13716
13717   // Check to see if this is the equivalent of setcc
13718   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13719   // otherwise, go ahead with the folds.
13720   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13721     EVT XType = N0.getValueType();
13722     if (!LegalOperations ||
13723         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13724       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13725       if (Res.getValueType() != VT)
13726         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13727       return Res;
13728     }
13729
13730     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13731     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13732         (!LegalOperations ||
13733          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13734       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13735       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13736                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13737                                          SDLoc(Ctlz),
13738                                        getShiftAmountTy(Ctlz.getValueType())));
13739     }
13740     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13741     if (isNullConstant(N1) && CC == ISD::SETGT) {
13742       SDLoc DL(N0);
13743       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13744                                   XType, DAG.getConstant(0, DL, XType), N0);
13745       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13746       return DAG.getNode(ISD::SRL, DL, XType,
13747                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13748                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13749                                          getShiftAmountTy(XType)));
13750     }
13751     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13752     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13753       SDLoc DL(N0);
13754       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13755                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13756                                          getShiftAmountTy(N0.getValueType())));
13757       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13758                                                                     XType));
13759     }
13760   }
13761
13762   // Check to see if this is an integer abs.
13763   // select_cc setg[te] X,  0,  X, -X ->
13764   // select_cc setgt    X, -1,  X, -X ->
13765   // select_cc setl[te] X,  0, -X,  X ->
13766   // select_cc setlt    X,  1, -X,  X ->
13767   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13768   if (N1C) {
13769     ConstantSDNode *SubC = nullptr;
13770     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13771          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13772         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13773       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13774     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13775               (N1C->isOne() && CC == ISD::SETLT)) &&
13776              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13777       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13778
13779     EVT XType = N0.getValueType();
13780     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13781       SDLoc DL(N0);
13782       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13783                                   N0,
13784                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13785                                          getShiftAmountTy(N0.getValueType())));
13786       SDValue Add = DAG.getNode(ISD::ADD, DL,
13787                                 XType, N0, Shift);
13788       AddToWorklist(Shift.getNode());
13789       AddToWorklist(Add.getNode());
13790       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13791     }
13792   }
13793
13794   return SDValue();
13795 }
13796
13797 /// This is a stub for TargetLowering::SimplifySetCC.
13798 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13799                                    SDValue N1, ISD::CondCode Cond,
13800                                    SDLoc DL, bool foldBooleans) {
13801   TargetLowering::DAGCombinerInfo
13802     DagCombineInfo(DAG, Level, false, this);
13803   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13804 }
13805
13806 /// Given an ISD::SDIV node expressing a divide by constant, return
13807 /// a DAG expression to select that will generate the same value by multiplying
13808 /// by a magic number.
13809 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13810 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13811   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13812   if (!C)
13813     return SDValue();
13814
13815   // Avoid division by zero.
13816   if (C->isNullValue())
13817     return SDValue();
13818
13819   std::vector<SDNode*> Built;
13820   SDValue S =
13821       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13822
13823   for (SDNode *N : Built)
13824     AddToWorklist(N);
13825   return S;
13826 }
13827
13828 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13829 /// DAG expression that will generate the same value by right shifting.
13830 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13831   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13832   if (!C)
13833     return SDValue();
13834
13835   // Avoid division by zero.
13836   if (C->isNullValue())
13837     return SDValue();
13838
13839   std::vector<SDNode *> Built;
13840   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13841
13842   for (SDNode *N : Built)
13843     AddToWorklist(N);
13844   return S;
13845 }
13846
13847 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13848 /// expression that will generate the same value by multiplying by a magic
13849 /// number.
13850 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13851 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13852   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13853   if (!C)
13854     return SDValue();
13855
13856   // Avoid division by zero.
13857   if (C->isNullValue())
13858     return SDValue();
13859
13860   std::vector<SDNode*> Built;
13861   SDValue S =
13862       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13863
13864   for (SDNode *N : Built)
13865     AddToWorklist(N);
13866   return S;
13867 }
13868
13869 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13870   if (Level >= AfterLegalizeDAG)
13871     return SDValue();
13872
13873   // Expose the DAG combiner to the target combiner implementations.
13874   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13875
13876   unsigned Iterations = 0;
13877   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13878     if (Iterations) {
13879       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13880       // For the reciprocal, we need to find the zero of the function:
13881       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13882       //     =>
13883       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13884       //     does not require additional intermediate precision]
13885       EVT VT = Op.getValueType();
13886       SDLoc DL(Op);
13887       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13888
13889       AddToWorklist(Est.getNode());
13890
13891       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13892       for (unsigned i = 0; i < Iterations; ++i) {
13893         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13894         AddToWorklist(NewEst.getNode());
13895
13896         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13897         AddToWorklist(NewEst.getNode());
13898
13899         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13900         AddToWorklist(NewEst.getNode());
13901
13902         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13903         AddToWorklist(Est.getNode());
13904       }
13905     }
13906     return Est;
13907   }
13908
13909   return SDValue();
13910 }
13911
13912 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13913 /// For the reciprocal sqrt, we need to find the zero of the function:
13914 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13915 ///     =>
13916 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13917 /// As a result, we precompute A/2 prior to the iteration loop.
13918 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13919                                           unsigned Iterations) {
13920   EVT VT = Arg.getValueType();
13921   SDLoc DL(Arg);
13922   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13923
13924   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13925   // this entire sequence requires only one FP constant.
13926   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13927   AddToWorklist(HalfArg.getNode());
13928
13929   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13930   AddToWorklist(HalfArg.getNode());
13931
13932   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13933   for (unsigned i = 0; i < Iterations; ++i) {
13934     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13935     AddToWorklist(NewEst.getNode());
13936
13937     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13938     AddToWorklist(NewEst.getNode());
13939
13940     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13941     AddToWorklist(NewEst.getNode());
13942
13943     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13944     AddToWorklist(Est.getNode());
13945   }
13946   return Est;
13947 }
13948
13949 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13950 /// For the reciprocal sqrt, we need to find the zero of the function:
13951 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13952 ///     =>
13953 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13954 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13955                                           unsigned Iterations) {
13956   EVT VT = Arg.getValueType();
13957   SDLoc DL(Arg);
13958   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13959   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13960
13961   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13962   for (unsigned i = 0; i < Iterations; ++i) {
13963     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13964     AddToWorklist(HalfEst.getNode());
13965
13966     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13967     AddToWorklist(Est.getNode());
13968
13969     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13970     AddToWorklist(Est.getNode());
13971
13972     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13973     AddToWorklist(Est.getNode());
13974
13975     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13976     AddToWorklist(Est.getNode());
13977   }
13978   return Est;
13979 }
13980
13981 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13982   if (Level >= AfterLegalizeDAG)
13983     return SDValue();
13984
13985   // Expose the DAG combiner to the target combiner implementations.
13986   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13987   unsigned Iterations = 0;
13988   bool UseOneConstNR = false;
13989   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13990     AddToWorklist(Est.getNode());
13991     if (Iterations) {
13992       Est = UseOneConstNR ?
13993         BuildRsqrtNROneConst(Op, Est, Iterations) :
13994         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13995     }
13996     return Est;
13997   }
13998
13999   return SDValue();
14000 }
14001
14002 /// Return true if base is a frame index, which is known not to alias with
14003 /// anything but itself.  Provides base object and offset as results.
14004 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14005                            const GlobalValue *&GV, const void *&CV) {
14006   // Assume it is a primitive operation.
14007   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14008
14009   // If it's an adding a simple constant then integrate the offset.
14010   if (Base.getOpcode() == ISD::ADD) {
14011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14012       Base = Base.getOperand(0);
14013       Offset += C->getZExtValue();
14014     }
14015   }
14016
14017   // Return the underlying GlobalValue, and update the Offset.  Return false
14018   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14019   // by multiple nodes with different offsets.
14020   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14021     GV = G->getGlobal();
14022     Offset += G->getOffset();
14023     return false;
14024   }
14025
14026   // Return the underlying Constant value, and update the Offset.  Return false
14027   // for ConstantSDNodes since the same constant pool entry may be represented
14028   // by multiple nodes with different offsets.
14029   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14030     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14031                                          : (const void *)C->getConstVal();
14032     Offset += C->getOffset();
14033     return false;
14034   }
14035   // If it's any of the following then it can't alias with anything but itself.
14036   return isa<FrameIndexSDNode>(Base);
14037 }
14038
14039 /// Return true if there is any possibility that the two addresses overlap.
14040 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14041   // If they are the same then they must be aliases.
14042   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14043
14044   // If they are both volatile then they cannot be reordered.
14045   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14046
14047   // If one operation reads from invariant memory, and the other may store, they
14048   // cannot alias. These should really be checking the equivalent of mayWrite,
14049   // but it only matters for memory nodes other than load /store.
14050   if (Op0->isInvariant() && Op1->writeMem())
14051     return false;
14052
14053   if (Op1->isInvariant() && Op0->writeMem())
14054     return false;
14055
14056   // Gather base node and offset information.
14057   SDValue Base1, Base2;
14058   int64_t Offset1, Offset2;
14059   const GlobalValue *GV1, *GV2;
14060   const void *CV1, *CV2;
14061   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14062                                       Base1, Offset1, GV1, CV1);
14063   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14064                                       Base2, Offset2, GV2, CV2);
14065
14066   // If they have a same base address then check to see if they overlap.
14067   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14068     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14069              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14070
14071   // It is possible for different frame indices to alias each other, mostly
14072   // when tail call optimization reuses return address slots for arguments.
14073   // To catch this case, look up the actual index of frame indices to compute
14074   // the real alias relationship.
14075   if (isFrameIndex1 && isFrameIndex2) {
14076     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14077     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14078     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14079     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14080              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14081   }
14082
14083   // Otherwise, if we know what the bases are, and they aren't identical, then
14084   // we know they cannot alias.
14085   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14086     return false;
14087
14088   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14089   // compared to the size and offset of the access, we may be able to prove they
14090   // do not alias.  This check is conservative for now to catch cases created by
14091   // splitting vector types.
14092   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14093       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14094       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14095        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14096       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14097     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14098     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14099
14100     // There is no overlap between these relatively aligned accesses of similar
14101     // size, return no alias.
14102     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14103         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14104       return false;
14105   }
14106
14107   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14108                    ? CombinerGlobalAA
14109                    : DAG.getSubtarget().useAA();
14110 #ifndef NDEBUG
14111   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14112       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14113     UseAA = false;
14114 #endif
14115   if (UseAA &&
14116       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14117     // Use alias analysis information.
14118     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14119                                  Op1->getSrcValueOffset());
14120     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14121         Op0->getSrcValueOffset() - MinOffset;
14122     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14123         Op1->getSrcValueOffset() - MinOffset;
14124     AliasResult AAResult =
14125         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14126                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14127                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14128                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14129     if (AAResult == NoAlias)
14130       return false;
14131   }
14132
14133   // Otherwise we have to assume they alias.
14134   return true;
14135 }
14136
14137 /// Walk up chain skipping non-aliasing memory nodes,
14138 /// looking for aliasing nodes and adding them to the Aliases vector.
14139 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14140                                    SmallVectorImpl<SDValue> &Aliases) {
14141   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14142   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14143
14144   // Get alias information for node.
14145   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14146
14147   // Starting off.
14148   Chains.push_back(OriginalChain);
14149   unsigned Depth = 0;
14150
14151   // Look at each chain and determine if it is an alias.  If so, add it to the
14152   // aliases list.  If not, then continue up the chain looking for the next
14153   // candidate.
14154   while (!Chains.empty()) {
14155     SDValue Chain = Chains.pop_back_val();
14156
14157     // For TokenFactor nodes, look at each operand and only continue up the
14158     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14159     // find more and revert to original chain since the xform is unlikely to be
14160     // profitable.
14161     //
14162     // FIXME: The depth check could be made to return the last non-aliasing
14163     // chain we found before we hit a tokenfactor rather than the original
14164     // chain.
14165     if (Depth > 6 || Aliases.size() == 2) {
14166       Aliases.clear();
14167       Aliases.push_back(OriginalChain);
14168       return;
14169     }
14170
14171     // Don't bother if we've been before.
14172     if (!Visited.insert(Chain.getNode()).second)
14173       continue;
14174
14175     switch (Chain.getOpcode()) {
14176     case ISD::EntryToken:
14177       // Entry token is ideal chain operand, but handled in FindBetterChain.
14178       break;
14179
14180     case ISD::LOAD:
14181     case ISD::STORE: {
14182       // Get alias information for Chain.
14183       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14184           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14185
14186       // If chain is alias then stop here.
14187       if (!(IsLoad && IsOpLoad) &&
14188           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14189         Aliases.push_back(Chain);
14190       } else {
14191         // Look further up the chain.
14192         Chains.push_back(Chain.getOperand(0));
14193         ++Depth;
14194       }
14195       break;
14196     }
14197
14198     case ISD::TokenFactor:
14199       // We have to check each of the operands of the token factor for "small"
14200       // token factors, so we queue them up.  Adding the operands to the queue
14201       // (stack) in reverse order maintains the original order and increases the
14202       // likelihood that getNode will find a matching token factor (CSE.)
14203       if (Chain.getNumOperands() > 16) {
14204         Aliases.push_back(Chain);
14205         break;
14206       }
14207       for (unsigned n = Chain.getNumOperands(); n;)
14208         Chains.push_back(Chain.getOperand(--n));
14209       ++Depth;
14210       break;
14211
14212     default:
14213       // For all other instructions we will just have to take what we can get.
14214       Aliases.push_back(Chain);
14215       break;
14216     }
14217   }
14218
14219   // We need to be careful here to also search for aliases through the
14220   // value operand of a store, etc. Consider the following situation:
14221   //   Token1 = ...
14222   //   L1 = load Token1, %52
14223   //   S1 = store Token1, L1, %51
14224   //   L2 = load Token1, %52+8
14225   //   S2 = store Token1, L2, %51+8
14226   //   Token2 = Token(S1, S2)
14227   //   L3 = load Token2, %53
14228   //   S3 = store Token2, L3, %52
14229   //   L4 = load Token2, %53+8
14230   //   S4 = store Token2, L4, %52+8
14231   // If we search for aliases of S3 (which loads address %52), and we look
14232   // only through the chain, then we'll miss the trivial dependence on L1
14233   // (which also loads from %52). We then might change all loads and
14234   // stores to use Token1 as their chain operand, which could result in
14235   // copying %53 into %52 before copying %52 into %51 (which should
14236   // happen first).
14237   //
14238   // The problem is, however, that searching for such data dependencies
14239   // can become expensive, and the cost is not directly related to the
14240   // chain depth. Instead, we'll rule out such configurations here by
14241   // insisting that we've visited all chain users (except for users
14242   // of the original chain, which is not necessary). When doing this,
14243   // we need to look through nodes we don't care about (otherwise, things
14244   // like register copies will interfere with trivial cases).
14245
14246   SmallVector<const SDNode *, 16> Worklist;
14247   for (const SDNode *N : Visited)
14248     if (N != OriginalChain.getNode())
14249       Worklist.push_back(N);
14250
14251   while (!Worklist.empty()) {
14252     const SDNode *M = Worklist.pop_back_val();
14253
14254     // We have already visited M, and want to make sure we've visited any uses
14255     // of M that we care about. For uses that we've not visisted, and don't
14256     // care about, queue them to the worklist.
14257
14258     for (SDNode::use_iterator UI = M->use_begin(),
14259          UIE = M->use_end(); UI != UIE; ++UI)
14260       if (UI.getUse().getValueType() == MVT::Other &&
14261           Visited.insert(*UI).second) {
14262         if (isa<MemSDNode>(*UI)) {
14263           // We've not visited this use, and we care about it (it could have an
14264           // ordering dependency with the original node).
14265           Aliases.clear();
14266           Aliases.push_back(OriginalChain);
14267           return;
14268         }
14269
14270         // We've not visited this use, but we don't care about it. Mark it as
14271         // visited and enqueue it to the worklist.
14272         Worklist.push_back(*UI);
14273       }
14274   }
14275 }
14276
14277 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14278 /// (aliasing node.)
14279 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14280   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14281
14282   // Accumulate all the aliases to this node.
14283   GatherAllAliases(N, OldChain, Aliases);
14284
14285   // If no operands then chain to entry token.
14286   if (Aliases.size() == 0)
14287     return DAG.getEntryNode();
14288
14289   // If a single operand then chain to it.  We don't need to revisit it.
14290   if (Aliases.size() == 1)
14291     return Aliases[0];
14292
14293   // Construct a custom tailored token factor.
14294   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14295 }
14296
14297 /// This is the entry point for the file.
14298 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14299                            CodeGenOpt::Level OptLevel) {
14300   /// This is the main entry point to this class.
14301   DAGCombiner(*this, AA, OptLevel).Run(Level);
14302 }